qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,662,673
<p>I'm trying to implement simple <code>fread()</code> and <code>frwite()</code> example using strings. The program gives me <code>segfault</code> or <code>free(): invalid pointer</code> errors. Below is the example code I'm working with.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;fstream&gt; #include &lt;iostream&gt; static bool file_read(FILE* file) { std::string value=&quot;abcd&quot;; std::string retrieved; size_t read, write; write = fwrite(&amp;value, sizeof(value), 1, file); fseek(file, 0, SEEK_SET); read = fread(&amp;retrieved, sizeof(value), 1, file); return true; } int main(int argc, char *argv[]) { FILE *file = NULL; file = fopen(&quot;file_test&quot;, &quot;wb+&quot;); file_read(file); fclose(file); } </code></pre> <p>I checked if <code>file</code> is opened correctly and that <code>retrieved</code> has the same value as <code>value</code>. I don't think I'm freeing any variables in my code. I'm suspecting that <code>fread</code> is causing all the trouble.</p> <pre class="lang-c prettyprint-override"><code>fread(&amp;retrieved[0], sizeof(char), 4, file) </code></pre> <p>Doesn't read the value to <code>retrieved</code> and was where I am doing wrong.</p>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74662673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11372242/" ]
74,662,684
<p>I want to compare the input with the list, but the else loop continues infinitely even when i give it a input that matches the list.</p> <pre><code>def check_input(): while True: guessing_range = input(&quot;Please enter a guessing range.&quot;) if guessing_range.isdigit: guessing_range = int(guessing_range) if guessing_range in lst: break else: print(&quot;Guessing range must be 10, 100, or 1000!&quot;) continue return guessing_range check_input() </code></pre>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74662684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670709/" ]
74,662,687
<p>Three Div elements with box appearance, when user click at any div a copy from this div will be added to the end (the fired div wont be clickable any more, and the new div will be clickable). And so on…..</p> <p>I have tried this but it creates two divs at the same time and the div can be clickable again .!!</p> <pre><code> &lt;div id=&quot;parent&quot; class=&quot;p&quot;&gt; &lt;div class=&quot;red&quot; class=&quot;d&quot;&gt;&lt;/div&gt; &lt;div class=&quot;green&quot; class=&quot;d&quot;&gt;&lt;/div&gt; &lt;div class=&quot;blue&quot; class=&quot;d&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>#parent{ display: flex; flex-wrap: wrap; } .red{ width: 50px; height: 50px; background-color: red; margin: 2px; }`your text` .green{ width: 50px; height: 50px; background-color: green; margin: 2px; } .blue{ width: 50px; height: 50px; background-color: blue; margin: 2px; } </code></pre> <pre><code>let parent = document.querySelector(&quot;#parent&quot;); let div = document.querySelectorAll(&quot;.p div&quot;); parent.addEventListener(&quot;click&quot;, function createDiv(e){ console.log('1'); let child = document.createElement(&quot;div&quot;); parent.append(child); child.classList.add(e.target.className); console.log(e); e.target.removeEventListener(&quot;click&quot;,createDiv()); }); </code></pre>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74662687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20606166/" ]
74,662,717
<p>I'm trying to type a higher order function. The basic idea is that high is passed a function fn, and it returns a function that takes the exact same parameters and gives the same return type.</p> <p>It's an exercise in trying to understand the language better. I have something that works but erases the type from the input parameters. Please see the types Test1 vs Test2 below:</p> <pre><code>export function high&lt;R&gt;(fn: (...args: any[]) =&gt; R) { return (...args: any[]) =&gt; { const moddedArgs = args.map((el) =&gt; typeof el === &quot;string&quot; ? el + &quot;OMG&quot; : el ); return fn(...moddedArgs); }; } const test1 = (nr1: number, str1?: string) =&gt; (str1 ?? &quot;Wow&quot;).repeat(nr1); test1(3, &quot;yo&quot;); // returns yoyoyo test1(3); // returns WowWowWow const test2 = high(test1); test2(3, &quot;yo&quot;); // returns yoOMGyoOMGyoOMG type Test1 = typeof test1; // type Test1 = (nr1: number, str1?: string) =&gt; string type Test2 = typeof test2; // type Test2 = (...args: any[]) =&gt; string </code></pre> <p><a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVwBaYDmeAPAEoB8AFAigFxxUB0LAhlIQM4OsoCeAbQC6ASjgBeCnDJiA3gCg4cKMBhIouZmw7c4vQaIlSFSpWhyd4AWwgATW8FsBBHRL06mV1mCpVgAGzFJRVMlGD4wYAgEOACJcXE4ACJLKEwUQiS4AH5Y-zgAamSAeQBZAHEshgCQpREAbnla5VV1XFotTzsHZx0GkIBfRoGm8xRLOBhgSwBGNyoUKBmGFCQrACNgKAAaOFSZ7IZU9MIgqSp9nNykgHUIAHckkSYVSNYYBaX++SnZqgBmXZJPgQJ6NAD04Jaag0nDgIIRECavxgMwB-Uh0LacLu91xuNGFngKIATG4CMQqCiZt9SQCgSCwfJMSoYeN4RAyuUQVyeRVkRFgHAACrTVFucKRaKTMUzCFQyVC0WzeaLZZwVYbLa7faHPYwNIZM76w2EAWREVismJRXS0nyyaCy2Wa2MFhMdhcHj8YTG44ZIA" rel="nofollow noreferrer">Playground Link</a></p> <p>I tried having a P type argument for the parameters, which I sort of got working But it didn't handle optional parameters well.</p> <p>Any ideas how this can be solved?</p>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74662717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203487/" ]
74,662,724
<p>I'm trying to create a function generator prints one element in the array targets at the specified time in milliseconds in the timeArray and after the value is printed out the list will go to the next element in the time array and targets array and after the next time interval in the timeArray we print out the next value in the target array and continute to follow the same pattern until we reach the end of the array</p> <p>I tried using the code shown below but it only prints out the first 2 elements in the timeArray but it doesn't print all of the other elements but I'm not sure if it's printing them after the first two time intervals in timeArray</p> <pre><code>let j = 0; var timeArray = [6, 68, 51, 41, 94, 65, 47, 85, 76, 136];//Array that shows how long after each number printed to the console the next value should be printed var targets = [9, 10, 8, 7, 9, 7, 7, 9, 9, 7];//Array of numbers that should be printed let generator = generateSequence(); async function* generateSequence(casiInfluence){ yield new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; resolve(console.log(targetArray[j]), timeArray[j]); console.log(timeArray[j]); }); } (async function main(){ for await(var result of generateSequence()){ console.log(result); j++; result = generator.next(); } }()); </code></pre>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74662724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17102482/" ]
74,662,754
<p>I'm currently trying to code a simple game for class. Right now I want my rectangle to stay within the bounds of my canvas when i move it by using a bounce function, but it doesn't seem to be working and I cant figure out why. I have tried implementing my bounce function and calling it at the top. When I move my rectangle it goes past the bounds of the canvas without staying inside and &quot;bouncing&quot; off the border.</p> <pre><code>var canvas; var ctx; var w = 1000; var h = 700; var o1 = { x: 100, y: h/2, w: 100, h: 100, c: 0, a: 100, angle: 0, //changes angle that shape sits at distance: 10 } document.onkeydown = function(e){keypress(e, o1)} setUpCanvas(); // circle (o1); animationLoop(); function animationLoop(){ //clear clear(); //draw rect(o1); //update bounce(o1) requestAnimationFrame(animationLoop) } function bounce(o){ if(o.x+o.w/2 &gt; w || o.x-o.w/2 &lt; 0){ //makes shape bounce from edge instead of middle. collision detection o.changeX *= -1; //same as o.changeX = o.changeX = -1; } if(o.y+o.h/2 &gt; h || o.y-o.h/2 &lt;0){ o.changeY *= -1; } } function updateData(o){ o.x += o.changeX; o.y += o.changeY; } function keypress(e,o){ if (e.key == &quot;ArrowUp&quot;){ o.angle = 270; o.distance= 80; forward(o); } if (e.key == &quot;ArrowDown&quot;){ o.angle = 90; o.distance= 20; forward(o); } } function forward(o){ //makes shape able to move var cx; var cy; cx = o.distance*Math.cos(o.angle); cy = o.distance*Math.sin(o.angle) o.y += cy; } function rect(o){ var bufferx = o.x; var buffery = o.y o.x = o.x - o.w/2; o.y = o.y- o.h/2; ctx.beginPath(); //this is very important when we are changing certain ctx properties ctx.moveTo(o.x,o.y); ctx.lineTo(o.x+o.w,o.y); ctx.lineTo(o.x+o.w,o.y+o.h); ctx.lineTo(o.x, o.y+o.h); ctx.lineTo(o.x,o.y); ctx.fillStyle = &quot;hsla(&quot;+String (o.c)+&quot;,100%,50%,&quot;+o.a+&quot;)&quot;; ctx.fill(); o.x = bufferx; //o.x = o.x + o.w/2; o.y = buffery;//o.y = o.y+ o.h/2; } function clear(){ ctx.clearRect(0, 0, w, h); } function randn(range){ var r = Math.random()*range-(range/2); return r } function rand(range){ var r = Math.random()*range return r } function setUpCanvas(){ canvas = document.querySelector(&quot;#myCanvas&quot;); canvas.width = w; canvas.height = h; // canvas.style.width = &quot;1000px&quot;; // canvas.style.height = &quot;700px&quot;; canvas.style.border = &quot;10px solid black&quot;; ctx = canvas.getContext(&quot;2d&quot;); } console.log(&quot;Final Assignment&quot;) </code></pre>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74662754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670829/" ]
74,662,787
<p>I have a string like this:<br /> <code>let string = &quot;/gb/fr/firstPage/secondPage</code>.\</p> <p>I want to compare the <code>/gb/fr/</code> part against an array like below:</p> <p><code>let array = [ &quot;/fr/fr&quot;, &quot;/de/de&quot;, &quot;/es/es&quot;,&quot;/ro/ro&quot;, &quot;/it/it&quot;]</code></p> <p>and if its the same return the string, but if not the same return :</p> <p><code>string = &quot;/gb/en/firstPage/secondPage</code>\</p> <p>Can you help me out please or explain how to do it ?</p> <p>more example:</p> <p><code>&quot;/ee/et/firstPage/secondPage&quot;</code></p> <p>should return :</p> <p><code>&quot;/ee/en/firstPage/secondPage&quot;` </code></p> <p>another example :</p> <p><code>&quot;/lt/lt/firstPage/secondPage&quot;</code></p> <p>should return:</p> <p><code>&quot;/lt/en/firstPage/secondPage&quot;</code></p> <p>so it basically checks the first part <code>/fr/</code></p> <p>if it exists it will return the corresponding link otherwise it will replace the second part with `/en/`</p>
[ { "answer_id": 74662721, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 3, "selected": true, "text": "value.c_str() value.length() std::string fread char [] ifstream" }, { "answer_id": 74663736, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 1, "selected": false, "text": "std::string #include <fstream>\n#include <iostream>\n#include <string>\n#include <cstdio>\n\nstatic bool file_writeStr(std::FILE* file, const std::string &value) {\n size_t len = value.size();\n bool res = (std::fwrite(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res) res = (std::fwrite(value.c_str(), len, 1, file) == 1);\n return res;\n}\n\nstatic bool file_readStr(std::FILE* file, std::string &value) {\n size_t len;\n value.clear();\n bool res = (std::fread(reinterpret_cast<char*>(&len), sizeof(len), 1, file) == 1);\n if (res && len > 0) {\n value.resize(len);\n res = (std::fread(&value[0], len, 1, file) == 1);\n }\n return res;\n}\n\nstatic bool file_test(std::FILE* file) {\n std::string value = \"abcd\";\n std::string retrieved;\n bool res = file_writeStr(file, value);\n if (res) {\n std::fseek(file, 0, SEEK_SET);\n res = file_readStr(file, retrieved);\n }\n return res;\n}\n\nint main() {\n std::FILE *file = std::fopen(\"file_test\", \"wb+\");\n if (file_test(file))\n std::cout << \"success\";\n else\n std::cerr << \"failed\";\n std::fclose(file);\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19390997/" ]
74,662,805
<p>So I need to straight pivot my data with no aggregation. I have tried PIVOT, UNPIVOT, CROSS APPLY, and CASE statements all driving me crazy.</p> <p>Here is my current data set</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Header</th> <th>Contract Value</th> <th>Total Cost</th> <th>Profit</th> </tr> </thead> <tbody> <tr> <td>Original Budget</td> <td>1000</td> <td>900</td> <td>100</td> </tr> <tr> <td>Change Orders</td> <td>100</td> <td>90</td> <td>90</td> </tr> </tbody> </table> </div> <p>And this is what I would like to do. I want the values in the rows to be the column names.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Header</th> <th>Original Budget</th> <th>Change Orders</th> </tr> </thead> <tbody> <tr> <td>Contract Value</td> <td>1000</td> <td>100</td> </tr> <tr> <td>Total Cost</td> <td>900</td> <td>100</td> </tr> <tr> <td>Profit</td> <td>100</td> <td>10</td> </tr> </tbody> </table> </div> <p>Can someone please point me in the right direction.</p>
[ { "answer_id": 74662823, "author": "Diego Lamarão", "author_id": 11013622, "author_profile": "https://Stackoverflow.com/users/11013622", "pm_score": 1, "selected": false, "text": "PIVOT SQL PIVOT PIVOT SELECT *\nFROM yourTable\nPIVOT\n(\n MAX(ContractValue)\n FOR Header IN ([Original Budget], [Change Orders])\n) AS PivotTable\n PIVOT yourTable MAX FOR PIVOT PIVOT" }, { "answer_id": 74664589, "author": "RF1991", "author_id": 14799981, "author_profile": "https://Stackoverflow.com/users/14799981", "pm_score": 0, "selected": false, "text": "Fully Trasnpose Unpivot Pivot Cross apply Pivot CREATE TABLE mytable(\n Header VARCHAR(100) NOT NULL \n ,Contract_Value INTEGER NOT NULL\n ,Total_Cost INTEGER NOT NULL\n ,Profit INTEGER NOT NULL\n);\nINSERT INTO mytable\n(Header,Contract_Value,Total_Cost,Profit) VALUES \n('Original Budget',1000,900,100),\n('Change Orders',100,90,90);\n Unpivot Pivot SELECT \n name AS Header, \n [Original Budget], \n [Change Orders] \nFROM \n (\n select \n Header, \n name, \n value \n from \n mytable unpivot (\n value for name in (\n [Contract_Value], [Profit], [Total_Cost]\n )\n ) unpiv\n ) Src PIVOT (\n MAX(value) FOR Header IN (\n [Original Budget], [Change Orders]\n )\n ) Pvt \nORDER BY \n [Original Budget] desc\n Cross apply Pivot select name as header,\n [Original Budget],\n [Change Orders]\nfrom \n(\nselect Header,name,value1\n From mytable\n Cross Apply ( values ('Contract_Value',Contract_Value)\n ,('Total_Cost',Total_Cost)\n ,('Profit',Profit)\n ) B (name,value1)\n) src\npivot\n(\n max(value1)\n for Header in ([Original Budget], [Change Orders])\n) piv\norder by [Original Budget] desc\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2962869/" ]
74,662,809
<p>I am having a problem that I just don't know how to solve and nothing I'm finding is helping. My problem is that I have a list of names (strings), in this list I will have the same name show up more than once.</p> <pre class="lang-py prettyprint-override"><code>lst = ['hello.com', 'hello.com', 'hello.com', 'world.com', 'test1.com'] index = web_lst.index(domain)+1 print(index) </code></pre> <blockquote> <p>The issue with this code is that index() will always find and use the first 'hello.com' instead of any of the other &quot;hello.com's&quot;, so index will always be 1. If I were asking for any of the other names then it'd work I think.</p> </blockquote> <p>I am trying to get the integer representation of the 'hello.com' names (1, 2, 3, etc.), and I don't know how to do that or what else to use besides python lists. This, I don't think is going to work and I'm asking for any other ideas on what to do or use instead of using a list. (if what I'm trying to do is not possible with lists)</p> <br /> <br /> <p>My main goal is basically a login manager using sqlite3 and I want to have the ability to have multiple logins with some having the same domain name (but with different data and notes, etc.), because we like to have multiple logins/accounts for 1 website. I have a TUI (beaupy) for selecting the domain/option you want to get the login for but if you have more than 1 of the same domain name it doesn't know which one to pick. I have managed to use integers as IDs in the sqlite3 database to help but the main issue is the picking of an element from a list to get a number, to then plug into the read() function. So the list options will correlate to the &quot;IDs&quot; in the database. List index 0+1 would be option/row 1 in the database (and so on).</p> <pre class="lang-py prettyprint-override"><code>def clear(): os.system('clear||cls') def add(encrypted_data): ID = 1 database = sqlite3.connect('vault.gter') c = database.cursor() #Check to see if IDs exist and if yes then get how many/length of list and add 1 and use that instead. c.execute(&quot;SELECT id FROM logins&quot;) all_ids = c.fetchall() out = list(itertools.chain(*all_ids)) list_length = len(out) if not all_ids: pass else: for x in out: if x == list_length: ID = x+1 else: pass c.execute(f&quot;INSERT INTO logins VALUES ('{ID}', '{encrypted_data}')&quot;) database.commit() database.close() def domains(dKey): database = sqlite3.connect('vault.gter') c = database.cursor() c.execute(&quot;SELECT data FROM logins&quot;) websites = c.fetchall() enc_output = list(itertools.chain(*websites)) web_lst = [] note_lst = [] for x in enc_output: result = gcm.stringD(x, dKey) #decrypt encrypted json string. obj_result = json.loads(result) #turns back into json object website = obj_result['Domain'] notes = obj_result['Notes'] web_lst.append(website) note_lst.append(notes) for w,n in zip(web_lst, note_lst): with open('.lst', 'a') as fa: fa.writelines(f&quot;{w} ({n})\n&quot;) fa.close() with open(&quot;.lst&quot;, &quot;r+&quot;) as fr: data = fr.read() fnlst = data.strip().split('\n') fr.truncate(0) fr.close() os.remove(&quot;.lst&quot;) print(f'(Press &quot;ctrl+c&quot; to exit)\n-----------------------------------------------------------\n\nWebsite domain/name to get login for?\n') domain = beaupy.select(fnlst, cursor_style=&quot;#ffa533&quot;) clear() if domain == None: clear() return else: domain = domain.split(' ', 1)[0] #get first word in a string. print(domain) #debug index = web_lst.index(domain)+1 input(index) #debug pwd = read(index) return pwd # Come up with new way to show available options to chose from and then get number from that to use here for &quot;db_row&quot;. def read(db_row): database = sqlite3.connect('vault.gter') c = database.cursor() c.execute(&quot;SELECT id FROM logins&quot;) all_ids = c.fetchall() lst_output = list(itertools.chain(*all_ids)) if not all_ids: input(&quot;No IDS&quot;) #debug database.commit() database.close() return else: for x in lst_output: if x == db_row: c.execute(f&quot;SELECT data FROM logins WHERE id LIKE '{db_row}'&quot;) #to prevent my main issue of it not knowing what I want when two domain names are the same. stoof = c.fetchone() database.commit() database.close() return stoof[0] else: #(debug) - input(f&quot;error, x is not the same as db_row. x = {x} &amp; db_row = {db_row}&quot;) pass </code></pre> <br /> <br /> <p>If anyone has a better way of doing this whole login manager thing, I'll be very very appreciative. From handling the database and sqlite3 commands, better IDs? to perhaps completely a different (and free) way of storage. And finding a better way to handle my main problem here (with or without having to use lists). Anything is helpful. &lt;3</p> <blockquote> <p>If anyone has questions then feel free to ask away and I'll respond when I can with the best of my knowledge.</p> </blockquote>
[ { "answer_id": 74662823, "author": "Diego Lamarão", "author_id": 11013622, "author_profile": "https://Stackoverflow.com/users/11013622", "pm_score": 1, "selected": false, "text": "PIVOT SQL PIVOT PIVOT SELECT *\nFROM yourTable\nPIVOT\n(\n MAX(ContractValue)\n FOR Header IN ([Original Budget], [Change Orders])\n) AS PivotTable\n PIVOT yourTable MAX FOR PIVOT PIVOT" }, { "answer_id": 74664589, "author": "RF1991", "author_id": 14799981, "author_profile": "https://Stackoverflow.com/users/14799981", "pm_score": 0, "selected": false, "text": "Fully Trasnpose Unpivot Pivot Cross apply Pivot CREATE TABLE mytable(\n Header VARCHAR(100) NOT NULL \n ,Contract_Value INTEGER NOT NULL\n ,Total_Cost INTEGER NOT NULL\n ,Profit INTEGER NOT NULL\n);\nINSERT INTO mytable\n(Header,Contract_Value,Total_Cost,Profit) VALUES \n('Original Budget',1000,900,100),\n('Change Orders',100,90,90);\n Unpivot Pivot SELECT \n name AS Header, \n [Original Budget], \n [Change Orders] \nFROM \n (\n select \n Header, \n name, \n value \n from \n mytable unpivot (\n value for name in (\n [Contract_Value], [Profit], [Total_Cost]\n )\n ) unpiv\n ) Src PIVOT (\n MAX(value) FOR Header IN (\n [Original Budget], [Change Orders]\n )\n ) Pvt \nORDER BY \n [Original Budget] desc\n Cross apply Pivot select name as header,\n [Original Budget],\n [Change Orders]\nfrom \n(\nselect Header,name,value1\n From mytable\n Cross Apply ( values ('Contract_Value',Contract_Value)\n ,('Total_Cost',Total_Cost)\n ,('Profit',Profit)\n ) B (name,value1)\n) src\npivot\n(\n max(value1)\n for Header in ([Original Budget], [Change Orders])\n) piv\norder by [Original Budget] desc\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15114290/" ]
74,662,868
<p>In many Prolog guides the following code is used to illustrate &quot;negation by failure&quot; in Prolog.</p> <pre><code>not(Goal) :- call(Goal), !, fail. not(Goal). </code></pre> <p>However, those same tutorials and texts warn that this is not &quot;logical negation&quot;.</p> <p><strong>Question:</strong> What is the difference?</p> <p>I have tried to read those texts further, but they don't elaborate on the difference.</p>
[ { "answer_id": 74662823, "author": "Diego Lamarão", "author_id": 11013622, "author_profile": "https://Stackoverflow.com/users/11013622", "pm_score": 1, "selected": false, "text": "PIVOT SQL PIVOT PIVOT SELECT *\nFROM yourTable\nPIVOT\n(\n MAX(ContractValue)\n FOR Header IN ([Original Budget], [Change Orders])\n) AS PivotTable\n PIVOT yourTable MAX FOR PIVOT PIVOT" }, { "answer_id": 74664589, "author": "RF1991", "author_id": 14799981, "author_profile": "https://Stackoverflow.com/users/14799981", "pm_score": 0, "selected": false, "text": "Fully Trasnpose Unpivot Pivot Cross apply Pivot CREATE TABLE mytable(\n Header VARCHAR(100) NOT NULL \n ,Contract_Value INTEGER NOT NULL\n ,Total_Cost INTEGER NOT NULL\n ,Profit INTEGER NOT NULL\n);\nINSERT INTO mytable\n(Header,Contract_Value,Total_Cost,Profit) VALUES \n('Original Budget',1000,900,100),\n('Change Orders',100,90,90);\n Unpivot Pivot SELECT \n name AS Header, \n [Original Budget], \n [Change Orders] \nFROM \n (\n select \n Header, \n name, \n value \n from \n mytable unpivot (\n value for name in (\n [Contract_Value], [Profit], [Total_Cost]\n )\n ) unpiv\n ) Src PIVOT (\n MAX(value) FOR Header IN (\n [Original Budget], [Change Orders]\n )\n ) Pvt \nORDER BY \n [Original Budget] desc\n Cross apply Pivot select name as header,\n [Original Budget],\n [Change Orders]\nfrom \n(\nselect Header,name,value1\n From mytable\n Cross Apply ( values ('Contract_Value',Contract_Value)\n ,('Total_Cost',Total_Cost)\n ,('Profit',Profit)\n ) B (name,value1)\n) src\npivot\n(\n max(value1)\n for Header in ([Original Budget], [Change Orders])\n) piv\norder by [Original Budget] desc\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20343817/" ]
74,662,873
<p>I have 3 dataframes with the same dimensions. I want to create a dataframe with min value from each element in 3 dataframes. Is there a more efficient way than running loop on cloumn and then row going through each element one by one?</p> <pre><code>Dataframe X | Column A | Column B | | -------- | -------- | | Cell X1 | Cell X2 | | Cell X3 | Cell X4 | Dataframe Y | Column A | Column B | | -------- | -------- | | Cell Y1 | Cell Y2 | | Cell Y3 | Cell Y4 | Dataframe Z | Column A | Column B | | -------- | -------- | | Cell Z1 | Cell Z2 | | Cell Z3 | Cell Z4 | </code></pre> <pre><code>Dataframe Target Output | Column A | Column B | | -------- | -------- | | Min (Cell X1,Y1,Z1) | Min (Cell X2,Y2,Z2) | | Min (Cell X3,Y3,Z3) | Min (Cell X4,Y4,Z4) | </code></pre> <p>Thank you!</p> <p>I tried simple loop for each column and then each row for (c in 1:3){ for (r in 1:2){ ........ } }</p>
[ { "answer_id": 74662823, "author": "Diego Lamarão", "author_id": 11013622, "author_profile": "https://Stackoverflow.com/users/11013622", "pm_score": 1, "selected": false, "text": "PIVOT SQL PIVOT PIVOT SELECT *\nFROM yourTable\nPIVOT\n(\n MAX(ContractValue)\n FOR Header IN ([Original Budget], [Change Orders])\n) AS PivotTable\n PIVOT yourTable MAX FOR PIVOT PIVOT" }, { "answer_id": 74664589, "author": "RF1991", "author_id": 14799981, "author_profile": "https://Stackoverflow.com/users/14799981", "pm_score": 0, "selected": false, "text": "Fully Trasnpose Unpivot Pivot Cross apply Pivot CREATE TABLE mytable(\n Header VARCHAR(100) NOT NULL \n ,Contract_Value INTEGER NOT NULL\n ,Total_Cost INTEGER NOT NULL\n ,Profit INTEGER NOT NULL\n);\nINSERT INTO mytable\n(Header,Contract_Value,Total_Cost,Profit) VALUES \n('Original Budget',1000,900,100),\n('Change Orders',100,90,90);\n Unpivot Pivot SELECT \n name AS Header, \n [Original Budget], \n [Change Orders] \nFROM \n (\n select \n Header, \n name, \n value \n from \n mytable unpivot (\n value for name in (\n [Contract_Value], [Profit], [Total_Cost]\n )\n ) unpiv\n ) Src PIVOT (\n MAX(value) FOR Header IN (\n [Original Budget], [Change Orders]\n )\n ) Pvt \nORDER BY \n [Original Budget] desc\n Cross apply Pivot select name as header,\n [Original Budget],\n [Change Orders]\nfrom \n(\nselect Header,name,value1\n From mytable\n Cross Apply ( values ('Contract_Value',Contract_Value)\n ,('Total_Cost',Total_Cost)\n ,('Profit',Profit)\n ) B (name,value1)\n) src\npivot\n(\n max(value1)\n for Header in ([Original Budget], [Change Orders])\n) piv\norder by [Original Budget] desc\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670874/" ]
74,662,901
<p>I'm designing a Neocities site and on one of my pages the background image isn't showing up. I've tried doing it in HTML and CSS but neither will work.</p> <p>[This] (<a href="https://maggssszzz.neocities.org/spitbucket.html" rel="nofollow noreferrer">https://maggssszzz.neocities.org/spitbucket.html</a>) is the page in question and <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fpngtree.com%2Ffree-backgrounds-photos%2Fabstract-lines&amp;psig=AOvVaw0DqRellrv87omUXChv5XUF&amp;ust=1670010209669000&amp;source=images&amp;cd=vfe&amp;ved=0CA8QjRxqFwoTCOia0u2x2fsCFQAAAAAdAAAAABAU" rel="nofollow noreferrer">this</a> is the image I'm trying to attach.</p> <p>I initially tried placing it in the head of my HTML like this:</p> <pre><code>&lt;style&gt; background-image: &quot;url(https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fpngtree.com%2Ffree-backgrounds-photos%2Fabstract-lines&amp;psig=AOvVaw0DqRellrv87omUXChv5XUF&amp;ust=1670010209669000&amp;source=images&amp;cd=vfe&amp;ved=0CA8QjRxqFwoTCOia0u2x2fsCFQAAAAAdAAAAABAU)&quot;; &lt;/style&gt; </code></pre> <p>But that didn't do anything, so then I thought about putting it in CSS. I tried this 2 different ways and neither worked:</p> <pre><code>.body { text-align: center; background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); } .square { text-align: center; background-color: #16a868; line-height: 70px; width: 400px; height: 800px; color: #701ba1; margin: 20px auto; } </code></pre> <p>and attempt 2:</p> <pre><code>.body { text-align: center; } .square { text-align: center; background-color: #16a868; background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6); line-height: 70px; width: 400px; height: 800px; color: #701ba1; margin: 20px auto; } </code></pre> <p>But nothing works. What did I do wrong?</p>
[ { "answer_id": 74663028, "author": "Monirul Islam", "author_id": 10975723, "author_profile": "https://Stackoverflow.com/users/10975723", "pm_score": -1, "selected": false, "text": ".square {\ntext-align: center;\nbackground-color: #16a868;\nline-height: 70px;\nwidth: 400px;\nheight: 800px;\ncolor: #701ba1;\nmargin: 20px auto;\nbackground-image: url(https://www.imgonline.com.ua/examples/two-tone-blurred-background-1-big.jpg);\n" }, { "answer_id": 74680531, "author": "mags", "author_id": 20670877, "author_profile": "https://Stackoverflow.com/users/20670877", "pm_score": 0, "selected": false, "text": "<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<link rel=\"stylesheet\" href=\"spitbucket.css\" />\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?Family=Raleway\">\n<title>Spitbucket.com</title>\n<style>\n h1, p, h2, ul {font-family: \"Raleway\", sans-serif}\n body {\n background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6);\n }\n</style>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670877/" ]
74,662,904
<p>I'd like the TypeScript compiler to infer the names of properties on an object so that it's easier to invoke the appropriate functions later. However, despite considering invoking functions, TypeScript doesn't give any intellisense of the functions I can invoke.</p> <p>Taking into account the following example:</p> <pre class="lang-js prettyprint-override"><code>interface InputBase { alias: string; } const input: Array&lt;InputBase&gt; = [ { alias: 'getNotes' }, { alias: 'getComments' }, ]; const client = input.reduce((acc, curr: InputBase) =&gt; { return { ...acc, [curr.alias]: () =&gt; { return curr.alias + ' call'; }, }; }, {}); client.getNotes(); </code></pre> <p>My problem is really the lack of inference in the client variable, because currently the data type is <code>{}</code> despite appearing in the terminal <code>{getNotes: ƒ, getComments: ƒ}</code>.</p> <p>How can I resolve this?</p>
[ { "answer_id": 74663028, "author": "Monirul Islam", "author_id": 10975723, "author_profile": "https://Stackoverflow.com/users/10975723", "pm_score": -1, "selected": false, "text": ".square {\ntext-align: center;\nbackground-color: #16a868;\nline-height: 70px;\nwidth: 400px;\nheight: 800px;\ncolor: #701ba1;\nmargin: 20px auto;\nbackground-image: url(https://www.imgonline.com.ua/examples/two-tone-blurred-background-1-big.jpg);\n" }, { "answer_id": 74680531, "author": "mags", "author_id": 20670877, "author_profile": "https://Stackoverflow.com/users/20670877", "pm_score": 0, "selected": false, "text": "<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<link rel=\"stylesheet\" href=\"spitbucket.css\" />\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?Family=Raleway\">\n<title>Spitbucket.com</title>\n<style>\n h1, p, h2, ul {font-family: \"Raleway\", sans-serif}\n body {\n background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6);\n }\n</style>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13695382/" ]
74,662,928
<p>I am attempting to run python coding using vba. However, when running using vba, it was not successful . (i discovered that it is not running in anaconda prompt)</p> <p>the code is attached as follow. appreciate the help.</p> <pre><code>Sub RunPythonScript() Dim objShell As Object Dim PythonExePath As String, PythonScriptPath As String Set objShell = VBA.CreateObject(&quot;Wscript.Shell&quot;) PythonExePath = &quot;&quot;&quot;C:xxx.exe&quot;&quot;&quot; PythonScriptPath = &quot;&quot;&quot;C:xxx.py&quot;&quot;&quot; objShell.Run PythonExePath &amp; &quot; &quot; &amp; PythonScriptPath End Sub </code></pre> <p>Alternatively, I manually run in anaconda prompt and the code works.</p> <p><code>&quot;C:xxx.exe&quot; &quot;C:xxx.py&quot;</code></p> <p>What I observed on screen was the black cmd window pop out and disappeared in second. It did not work as expected. Is there anything I input incorrectly?</p> <pre><code>Sub RunPythonScript() Dim pythonExePath As String, pythonScriptPath As String pythonExePath = &quot;&quot;&quot;C:\Users\xxx\Anaconda3\python.exe&quot;&quot;&quot; pythonScriptPath = &quot;&quot;&quot;C:\Users\xxx\xxx.py&quot;&quot;&quot; Shell pythonExePath &amp; &quot; &quot; &amp; pythonScriptPath, vbNormalFocus End Sub </code></pre>
[ { "answer_id": 74663028, "author": "Monirul Islam", "author_id": 10975723, "author_profile": "https://Stackoverflow.com/users/10975723", "pm_score": -1, "selected": false, "text": ".square {\ntext-align: center;\nbackground-color: #16a868;\nline-height: 70px;\nwidth: 400px;\nheight: 800px;\ncolor: #701ba1;\nmargin: 20px auto;\nbackground-image: url(https://www.imgonline.com.ua/examples/two-tone-blurred-background-1-big.jpg);\n" }, { "answer_id": 74680531, "author": "mags", "author_id": 20670877, "author_profile": "https://Stackoverflow.com/users/20670877", "pm_score": 0, "selected": false, "text": "<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<link rel=\"stylesheet\" href=\"spitbucket.css\" />\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?Family=Raleway\">\n<title>Spitbucket.com</title>\n<style>\n h1, p, h2, ul {font-family: \"Raleway\", sans-serif}\n body {\n background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6);\n }\n</style>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20650501/" ]
74,662,947
still keeping some vertical space while list-style: none is defined. <p><a href="https://product-landing-page.freecodecamp.rocks/#how-it-works" rel="nofollow noreferrer">https://product-landing-page.freecodecamp.rocks/#how-it-works</a></p> <p>If you check this project and scroll to pricing labels there is defined exactly like mine and it behave differently.</p> <p><a href="https://i.stack.imgur.com/0WmFu.png" rel="nofollow noreferrer">My price label:</a></p> <p><a href="https://i.stack.imgur.com/XY8yU.png" rel="nofollow noreferrer">Project's label</a></p> <p>MY CSS:</p> <pre><code>/* ========== PRICE ======= */ #cost { display: flex; flex-direction: row; justify-content: center; } .price-box { display: flex; flex-direction: column; align-items: center; text-align: center; width: calc(100% / 3); margin: 10px; border: 1px solid #000; border-radius: 3px; } .lvl { background-color: #dddddd; text-align: center; font-size: 1.4em; color: rgb(65, 65, 65); padding: 5px; width: 100%; } #cost ol li { padding: 5px 0; margin: 0; } li { list-style: none; } </code></pre> <p>Project's CSS:</p> <pre><code>#pricing { margin-top: 60px; display: flex; flex-direction: row; justify-content: center; } .product { display: flex; flex-direction: column; align-items: center; text-align: center; width: calc(100% / 3); margin: 10px; border: 1px solid #000; border-radius: 3px; } .product &gt; .level { background-color: #ddd; color: black; padding: 15px 0; width: 100%; text-transform: uppercase; font-weight: 700; } .product &gt; h2 { margin-top: 15px; } .product &gt; ol { margin: 15px 0; } .product &gt; ol &gt; li { padding: 5px 0; } </code></pre> <p>Maybe someone can explain it to me so i can understand what is happening here</p>
[ { "answer_id": 74663028, "author": "Monirul Islam", "author_id": 10975723, "author_profile": "https://Stackoverflow.com/users/10975723", "pm_score": -1, "selected": false, "text": ".square {\ntext-align: center;\nbackground-color: #16a868;\nline-height: 70px;\nwidth: 400px;\nheight: 800px;\ncolor: #701ba1;\nmargin: 20px auto;\nbackground-image: url(https://www.imgonline.com.ua/examples/two-tone-blurred-background-1-big.jpg);\n" }, { "answer_id": 74680531, "author": "mags", "author_id": 20670877, "author_profile": "https://Stackoverflow.com/users/20670877", "pm_score": 0, "selected": false, "text": "<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<link rel=\"stylesheet\" href=\"spitbucket.css\" />\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?Family=Raleway\">\n<title>Spitbucket.com</title>\n<style>\n h1, p, h2, ul {font-family: \"Raleway\", sans-serif}\n body {\n background-image: url(https://us.123rf.com/450wm/leavector/leavector1901/leavector190100001/leavector190100001.jpg?ver=6);\n }\n</style>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20555678/" ]
74,662,972
<p>Inside my service I have a post method in which return type is IInfluencerRewardSetup</p> <pre><code>influencerRewardSetup(payload: IInfluencerRewardSetup): Observable&lt;IInfluencerRewardSetup&gt; { return this.httpClient.post&lt;IInfluencerRewardSetup&gt;(this.baseUrl, payload) .pipe(retry(1), this.errorHandler()); } </code></pre> <p>and</p> <pre><code>private errorHandler() { return catchError(err =&gt; { this.notificationService.error(err.message, ''); throw new Error(err.message || 'Server error'); }); } </code></pre> <p>But the problem is I am having this type of error:</p> <pre><code>Type 'Observable&lt;unknown&gt;' is not assignable to type 'Observable&lt;IInfluencerRewardSetup&gt;' </code></pre> <p>Please note that, errorHandler will handle other HTTP calls as well. Why am I having this error and how can I fix that type of issue here? can someone please help?</p>
[ { "answer_id": 74662981, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "return this.httpClient.post<IInfluencerRewardSetup>(this.baseUrl, payload)\n .pipe(\n retry(1),\n this.errorHandler() as Observable<IInfluencerRewardSetup>\n );\n private errorHandler() {\n return catchError<IInfluencerRewardSetup>(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n}\n" }, { "answer_id": 74665091, "author": "Henrik Bøgelund Lavstsen", "author_id": 1805974, "author_profile": "https://Stackoverflow.com/users/1805974", "pm_score": -1, "selected": false, "text": "handleError = () => pipe(\n catchError(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n ); \n import { pipe } from \"rxjs\";" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19866297/" ]
74,662,978
<p>Daily I’m receiving a new table (example :tablename_20220811) in the BigQuery, I want concatenate this new table data to the main_table, dataset schema are same.</p> <p>I tried using wild cards,I don’t know how to pull the daily loaded table.</p>
[ { "answer_id": 74662981, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "return this.httpClient.post<IInfluencerRewardSetup>(this.baseUrl, payload)\n .pipe(\n retry(1),\n this.errorHandler() as Observable<IInfluencerRewardSetup>\n );\n private errorHandler() {\n return catchError<IInfluencerRewardSetup>(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n}\n" }, { "answer_id": 74665091, "author": "Henrik Bøgelund Lavstsen", "author_id": 1805974, "author_profile": "https://Stackoverflow.com/users/1805974", "pm_score": -1, "selected": false, "text": "handleError = () => pipe(\n catchError(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n ); \n import { pipe } from \"rxjs\";" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670906/" ]
74,662,980
<pre><code>def add(a, b): return a + b print(&quot;choose 1 to add and 2 to subtract&quot;) select = input(&quot;enter choice 1/2&quot;) a = float(input(&quot;enter 1st nunber: &quot;)) b = float(input(&quot;enter 2nd number: &quot;)) if select == 1: print(a, &quot;+&quot;, b, &quot;=&quot;, add(a, b)) </code></pre> <p>I don't know why it doesn't wanna add</p>
[ { "answer_id": 74662981, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "return this.httpClient.post<IInfluencerRewardSetup>(this.baseUrl, payload)\n .pipe(\n retry(1),\n this.errorHandler() as Observable<IInfluencerRewardSetup>\n );\n private errorHandler() {\n return catchError<IInfluencerRewardSetup>(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n}\n" }, { "answer_id": 74665091, "author": "Henrik Bøgelund Lavstsen", "author_id": 1805974, "author_profile": "https://Stackoverflow.com/users/1805974", "pm_score": -1, "selected": false, "text": "handleError = () => pipe(\n catchError(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n ); \n import { pipe } from \"rxjs\";" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74662980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19841477/" ]
74,663,013
<p>I have the text file below:</p> <pre><code>data:&lt;SupplierParty data:xmlns=&quot;xxx&quot;&gt; data: &lt;cbc:CustomerAssignedAccountID schemeID=&quot;vendor-id&quot;&gt; data: 20750 data: &lt;/cbc:CustomerAssignedAccountID&gt; data: &lt;cbc:AdditionalAccountID schemeID=&quot;cashflow:v1&quot;&gt;151&lt;/cbc:AdditionalAccountID&gt; data:&lt;SupplierParty data:xmlns=&quot;xxx&quot;&gt; data: &lt;cbc:CustomerAssignedAccountID schemeID=&quot;vendor-id&quot;&gt; data: 20751 data: &lt;/cbc:CustomerAssignedAccountID&gt; data: &lt;cbc:AdditionalAccountID schemeID=&quot;cashflow:v1&quot;&gt;151&lt;/cbc:AdditionalAccountID&gt; data:&lt;SupplierParty data:xmlns=&quot;xxx&quot;&gt; data: &lt;cbc:CustomerAssignedAccountID schemeID=&quot;vendor-id&quot;&gt; data: 20752 data: &lt;/cbc:CustomerAssignedAccountID&gt; data: &lt;cbc:AdditionalAccountID schemeID=&quot;cashflow:v1&quot;&gt;151&lt;/cbc:AdditionalAccountID&gt; </code></pre> <p>And I only want to extract the values:</p> <pre><code>20750 20751 20752 </code></pre> <p>From the file.</p> <p>The closest I got to was:</p> <pre><code>(?&lt;=vendor-id&quot;\&gt;)(.*?)(?=\&lt;\/cbc:CustomerAssignedAccountID) </code></pre> <p>But this extracts:</p> <pre><code>data: 20751 data: </code></pre> <p>I want digits only.</p> <p>How do I do this?</p>
[ { "answer_id": 74662981, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "return this.httpClient.post<IInfluencerRewardSetup>(this.baseUrl, payload)\n .pipe(\n retry(1),\n this.errorHandler() as Observable<IInfluencerRewardSetup>\n );\n private errorHandler() {\n return catchError<IInfluencerRewardSetup>(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n}\n" }, { "answer_id": 74665091, "author": "Henrik Bøgelund Lavstsen", "author_id": 1805974, "author_profile": "https://Stackoverflow.com/users/1805974", "pm_score": -1, "selected": false, "text": "handleError = () => pipe(\n catchError(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n ); \n import { pipe } from \"rxjs\";" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12306386/" ]
74,663,037
<p>I'm trying to include header files from the atmel avr folder to work with arduino. Despite trying to include the directory of the files, it still prompts me with &quot;No such file or directory&quot; when compyling. The files are located inside &quot;C:\repositories\arduino_testing\include\avr&quot; What am I doing wrong?</p> <p><code>main.c</code></p> <pre><code>#include &lt;stdio.h&gt; #include &quot;avr\io.h&quot; int main(){ printf(&quot;This is a C code&quot;); return 0; } </code></pre> <p><code>tasks.json</code></p> <pre><code>{ &quot;tasks&quot;: [ { &quot;type&quot;: &quot;cppbuild&quot;, &quot;label&quot;: &quot;C/C++: g++.exe build active file&quot;, &quot;command&quot;: &quot;C:\\MinGW\\bin\\g++.exe&quot;, &quot;args&quot;: [ &quot;-I C:\\repositories\\arduino_testing\\include&quot;, &quot;-fdiagnostics-color=always&quot;, &quot;-g&quot;, &quot;${file}&quot;, &quot;-o&quot;, &quot;${fileDirname}\\${fileBasenameNoExtension}.exe&quot; ], &quot;options&quot;: { &quot;cwd&quot;: &quot;${fileDirname}&quot; }, &quot;problemMatcher&quot;: [ &quot;$gcc&quot; ], &quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true }, &quot;detail&quot;: &quot;Task generated by Debugger.&quot; }, { &quot;type&quot;: &quot;cppbuild&quot;, &quot;label&quot;: &quot;C/C++: cpp.exe build active file&quot;, &quot;command&quot;: &quot;C:\\MinGW\\bin\\cpp.exe&quot;, &quot;args&quot;: [ &quot;-fdiagnostics-color=always&quot;, &quot;-g&quot;, &quot;${file}&quot;, &quot;-o&quot;, &quot;${fileDirname}\\${fileBasenameNoExtension}.exe&quot; ], &quot;options&quot;: { &quot;cwd&quot;: &quot;${fileDirname}&quot; }, &quot;problemMatcher&quot;: [ &quot;$gcc&quot; ], &quot;group&quot;: &quot;build&quot;, &quot;detail&quot;: &quot;Task generated by Debugger.&quot; } ], &quot;version&quot;: &quot;2.0.0&quot; } </code></pre> <p><code>c_cpp_properties</code></p> <pre><code>{ &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Win32&quot;, &quot;includePath&quot;: [ //&quot;${workspaceFolder}/**&quot;, //&quot;C:\\repositories\\arduino_testing\\avr&quot;, &quot;C:\\repositories\\arduino_testing\\include&quot; ], &quot;defines&quot;: [ &quot;_DEBUG&quot;, &quot;UNICODE&quot;, &quot;_UNICODE&quot; ], &quot;windowsSdkVersion&quot;: &quot;10.0.18362.0&quot;, &quot;compilerPath&quot;: &quot;C:\\MinGW\\bin\\gcc.exe&quot;, &quot;cStandard&quot;: &quot;c17&quot;, &quot;cppStandard&quot;: &quot;c++17&quot;, &quot;intelliSenseMode&quot;: &quot;windows-gcc-x64&quot; } ], &quot;version&quot;: 4 } </code></pre> <pre><code></code></pre>
[ { "answer_id": 74662981, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "return this.httpClient.post<IInfluencerRewardSetup>(this.baseUrl, payload)\n .pipe(\n retry(1),\n this.errorHandler() as Observable<IInfluencerRewardSetup>\n );\n private errorHandler() {\n return catchError<IInfluencerRewardSetup>(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n}\n" }, { "answer_id": 74665091, "author": "Henrik Bøgelund Lavstsen", "author_id": 1805974, "author_profile": "https://Stackoverflow.com/users/1805974", "pm_score": -1, "selected": false, "text": "handleError = () => pipe(\n catchError(err => {\n this.notificationService.error(err.message, '');\n throw new Error(err.message || 'Server error');\n });\n ); \n import { pipe } from \"rxjs\";" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13326273/" ]
74,663,044
<p>-----<strong><strong>START EDIT</strong></strong>-----</p> <p>I don't know what I was doing wrong before, but the code below was somehow not working for me, and now is working, and it's exactly the same. I don't know how or what I was missing before, but both this minimal example and the real project I am working on is working now. Obviously I changed something, but I can't figure out what. I just know it's working now. Sorry for the confusion and thanks to everyone for helping.</p> <p>-----<strong><strong>END EDIT</strong></strong>-----</p> <p>I am new to Solidity and am using the <code>Factory</code> pattern for deploying a contract from another contract. I am trying to get the contract address of the deployed contract, but I am running into errors.</p> <p>I already tried the solution in <a href="https://stackoverflow.com/questions/42230532/getting-the-address-of-a-contract-deployed-by-another-contract">this question</a>, but I'm getting the following error: <code>Return argument type struct StorageFactory.ContractData storage ref is not implicitly convertible to expected type (type of first return variable) address.</code></p> <p>Here is my code:</p> <pre><code>// START EDIT (adding version) pragma solidity ^0.8.0; // END EDIT contract StorageFactory { struct ContractData { address contractAddress; // I want to save the deployed contract address in a mapping that includes this struct bool exists; } // mapping from address of user who deployed new Storage contract =&gt; ContractData struct (which includes the contract address) mapping(address =&gt; ContractData) public userAddressToStruct; function createStorageContract(address _userAddress) public { // require that the user has not previously deployed a storage contract require(!userAddressToStruct[_userAddress].exists, &quot;Account already exists&quot;); // TRYING TO GET THE ADDRESS OF THE NEWLY CREATED CONTRACT HERE, BUT GETTING AN ERROR address contractAddress = address(new StorageContract(_userAddress)); // trying to save the contractAddress here but unable to isolate the contract address userAddressToStruct[_userAddress].contractAddress = contractAddress; userAddressToStruct[_userAddress].exists = true; } } // arbitrary StorageContract being deployed contract StorageContract { address immutable deployedBy; constructor(address _deployedBy) { deployedBy = _deployedBy; } } </code></pre> <p>How can I get this contract address, so I can store it in the <code>ContractData</code> struct? Thanks.</p>
[ { "answer_id": 74663113, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "address contractAddress;\n(contractAddress,) = new StorageContract(_userAddress);\nuserAddressToStruct[_userAddress].contractAddress = contractAddress;\n" }, { "answer_id": 74663203, "author": "haggbart", "author_id": 15949328, "author_profile": "https://Stackoverflow.com/users/15949328", "pm_score": 0, "selected": false, "text": "// arbitrary StorageContract being deployed\ncontract StorageContract {\n address immutable deployedBy;\n\n constructor(address _deployedBy) {\n deployedBy = _deployedBy;\n }\n}\n\ncontract StorageFactory {\n\n struct ContractData {\n address contractAddress; // I want to save the deployed contract address in a mapping that includes this struct\n bool exists;\n }\n\n // mapping from address of user who deployed new Storage contract => ContractData struct (which includes the contract address)\n mapping(address => ContractData) public userAddressToStruct;\n\n function createStorageContract(address _userAddress) public {\n\n // require that the user has not previously deployed a storage contract\n require(!userAddressToStruct[_userAddress].exists, \"Account already exists\");\n\n // Declare a variable of type StorageContract to store the contract instance returned by the `new` keyword\n StorageContract storageContract = new StorageContract(_userAddress);\n\n // Get the contract address by calling the .address property on the contract instance\n address contractAddress = storageContract.address;\n\n // Save the contract address to the mapping\n userAddressToStruct[_userAddress].contractAddress = contractAddress;\n userAddressToStruct[_userAddress].exists = true;\n }\n}\n" }, { "answer_id": 74663360, "author": "Benjamin Woolston", "author_id": 20188398, "author_profile": "https://Stackoverflow.com/users/20188398", "pm_score": 0, "selected": false, "text": "// Create a new instance of the StorageContract contract\nStorageContract storageContract = new StorageContract(_userAddress);\n\n// Get the address of the newly deployed contract\naddress contractAddress = storageContract.address;\n\n// Save the contract address in the mapping\nuserAddressToStruct[_userAddress].contractAddress = contractAddress;\n // Create a new instance of the StorageContract contract\nStorageContract storageContract = new StorageContract(_userAddress);\n\n// Convert the storageContract instance to an address type\naddress contractAddress = address(storageContract);\n\n// Save the contract address in the mapping\nuserAddressToStruct[_userAddress].contractAddress = contractAddress;\n // get the contract instance and address as a tuple\n(address contractAddress, StorageContract storageContract) = new StorageContract(_userAddress);\n\n// save the contract address\nuserAddressToStruct[_userAddress].contractAddress = contractAddress;\n // arbitrary StorageContract being deployed\ncontract StorageContract {\n address immutable deployedBy;\n\n constructor(address _deployedBy) {\n deployedBy = _deployedBy;\n }\n}\n\n// StorageFactory contract\ncontract StorageFactory {\n ...\n}\n" }, { "answer_id": 74663436, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 2, "selected": true, "text": "pragma solidity >=0.7.0 <0.9.0;\n userAddressToStruct[_userAddress] = contractAddress;\n userAddressToStruct[_userAddress].contractAddress = contractAddress;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7857057/" ]
74,663,049
<p>try to get number of rows and column from user through array but it gives Segmentation fault at run time</p> <pre><code>#include&lt;stdio.h&gt; int main(){ int rows; int column; int arr[rows]; int arr1[column]; printf(&quot;Enter the number of rows: &quot;); scanf(&quot;%d&quot;,&amp;rows); printf(&quot;Enter the number of column: &quot;); scanf(&quot;%d&quot;,&amp;column); printf(&quot;\n&quot;); int i=0; while( i&lt;rows) { printf(&quot;\n&quot;); printf(&quot;Enter the value of rows index: &quot; ); scanf(&quot;%d&quot;,&amp;arr[i]); printf(&quot;\n&quot;); i++; } int j=0; while(j&lt;column) { printf(&quot;Enter the value of rows index: &quot; ); scanf(&quot;%d&quot;,&amp;arr1[j]); printf(&quot;\n&quot;); j++; } } </code></pre> <p>// giving Segmentation fault</p>
[ { "answer_id": 74663058, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "#include<stdio.h>\nint main(){\n int rows;\n int column;\n \n printf(\"Enter the number of rows: \");\n scanf(\"%d\",&rows);\n printf(\"Enter the number of column: \");\n scanf(\"%d\",&column);\n printf(\"\\n\");\n \n int arr[rows];\n int arr1[column];\n \nint i=0;\nwhile( i<rows)\n{ printf(\"\\n\");\n printf(\"Enter the value of rows index: \" );\n scanf(\"%d\",&arr[i]);\n printf(\"\\n\");\n i++;\n}\nint j=0;\nwhile(j<column)\n{\n printf(\"Enter the value of rows index: \" );\n scanf(\"%d\",&arr1[j]);\n printf(\"\\n\");\n j++;\n}\n}\n" }, { "answer_id": 74663074, "author": "NoDakker", "author_id": 6032177, "author_profile": "https://Stackoverflow.com/users/6032177", "pm_score": 1, "selected": false, "text": "int rows;\nint column;\nint arr[rows];\nint arr1[column];\n printf(\"Enter the number of rows: \");\nscanf(\"%d\",&rows);\nprintf(\"Enter the number of column: \");\nscanf(\"%d\",&column);\nprintf(\"\\n\");\nint arr[rows];\nint arr1[column];\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670977/" ]
74,663,050
<p>How can I do to type something in the field of the image below?</p> <p>I've tried without success:</p> <pre><code>from threading import local import pandas as pd import pyautogui from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC </code></pre> <p><code>wait.until(EC.presence_of_element_located((By.XPATH,&quot;//input[@type='file']&quot;))send_keys(&quot;C:/Users/my_user/Downloads/doch.jpeg&quot;)</code></p> <pre><code>for index, row in df.iterrows(): actions.send_keys((row[&quot;message&quot;])) actions.perform() </code></pre> <p>The only palliative solution was:</p> <pre><code>pyautogui.write((row[&quot;photo&quot;])) pyautogui.press(&quot;enter&quot;) </code></pre> <p>I don't want to use pyautogui as it uses the keyboard command and I can't do anything on the computer while the code is running.</p> <p><a href="https://i.stack.imgur.com/oe0cf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oe0cf.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/AI3dQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AI3dQ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74663058, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 0, "selected": false, "text": "#include<stdio.h>\nint main(){\n int rows;\n int column;\n \n printf(\"Enter the number of rows: \");\n scanf(\"%d\",&rows);\n printf(\"Enter the number of column: \");\n scanf(\"%d\",&column);\n printf(\"\\n\");\n \n int arr[rows];\n int arr1[column];\n \nint i=0;\nwhile( i<rows)\n{ printf(\"\\n\");\n printf(\"Enter the value of rows index: \" );\n scanf(\"%d\",&arr[i]);\n printf(\"\\n\");\n i++;\n}\nint j=0;\nwhile(j<column)\n{\n printf(\"Enter the value of rows index: \" );\n scanf(\"%d\",&arr1[j]);\n printf(\"\\n\");\n j++;\n}\n}\n" }, { "answer_id": 74663074, "author": "NoDakker", "author_id": 6032177, "author_profile": "https://Stackoverflow.com/users/6032177", "pm_score": 1, "selected": false, "text": "int rows;\nint column;\nint arr[rows];\nint arr1[column];\n printf(\"Enter the number of rows: \");\nscanf(\"%d\",&rows);\nprintf(\"Enter the number of column: \");\nscanf(\"%d\",&column);\nprintf(\"\\n\");\nint arr[rows];\nint arr1[column];\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20021812/" ]
74,663,060
<p>am using opensearch 2.4 and I have an index with some fields while creating , later i started saving new field to the index , now when i query on the newly created field am not getting any results</p> <p>ex : query 1 POST abc/_search</p> <pre><code>{ &quot;query&quot;: { &quot;bool&quot;: { &quot;must&quot;: [ { &quot;terms&quot;: { &quot;name&quot;: [ &quot;john&quot; ] } } ] } } } </code></pre> <p>above works fine because name fields exists since creation of index</p> <p>query 2 : POST abc/_search</p> <pre><code>{ &quot;query&quot;: { &quot;bool&quot;: { &quot;must&quot;: [ { &quot;terms&quot;: { &quot;lastname&quot;: [ &quot;William&quot; ] } } ] } } } </code></pre> <p>above query doesnt work though i have some documents with lastname william</p>
[ { "answer_id": 74663283, "author": "rabbitbr", "author_id": 18778181, "author_profile": "https://Stackoverflow.com/users/18778181", "pm_score": 1, "selected": false, "text": " {\n \"terms\": {\n \"lastname.keyword\": [\n \"William\"\n ]\n }\n }\n {\n \"terms\": {\n \"lastname\": [\n \"william\"\n ]\n }\n }\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4072009/" ]
74,663,062
<p>For the final input, your program prompts the user for their year of study. Once again, this is not a required field, that is, a default value of 1 (as in 1st year of study) should be submitted if the user chooses to leave this field blank. Additionally, you must validate the data the user provides (if provided) to ensure that it is not less than 1, and not greater than 3 (valid range is 1-3 years of study).</p> <p>If your solution detects invalid input, your program must loop to allow the user to re-enter year of study, this process continues indefinitely, until valid input is detected.</p> <hr /> <p>I have tried a few different methods and this is my most recent attempt, but after 5 hours, I needed to ask for help. Code is below ( Yes, I'm a noob :( )</p> <pre><code>do { var yearofStudy = prompt(&quot;Please enter your Year of Study&quot;, &quot;1&quot;) console.log(yearofStudy) } while ( yearofStudy &gt; 1 &amp;&amp; yearofStudy &lt;4 ) </code></pre>
[ { "answer_id": 74663132, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 1, "selected": false, "text": "do {\n var yearofStudy = parseInt(prompt(\"Please enter your Year of Study\", \"1\"));\n console.log(yearofStudy)\n} while ( yearofStudy < 1 || yearofStudy > 3 )" }, { "answer_id": 74663151, "author": "str1ng", "author_id": 12826055, "author_profile": "https://Stackoverflow.com/users/12826055", "pm_score": 0, "selected": false, "text": "var statement = true;\n while (statement){\n var yearofStudy = prompt(\"Please enter your Year of Study\", \"1\");\n if(yearofStudy > 0 && yearofStudy < 4){\n break;\n }\n }\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20392134/" ]
74,663,097
<p>I try to calculate the checksum of the file in c.</p> <p>I have a file of around 100MB random and I want to calculate the checksum.</p> <p>I try this code from here: <a href="https://stackoverflow.com/a/3464166/14888108">https://stackoverflow.com/a/3464166/14888108</a></p> <pre><code> int CheckSumCalc(char * filename){ FILE *fp = fopen(filename,&quot;rb&quot;); unsigned char checksum = 0; while (!feof(fp) &amp;&amp; !ferror(fp)) { checksum ^= fgetc(fp); } fclose(fp); return checksum; } </code></pre> <p>but I got a Segmentation fault. in this line &quot;while (!feof(fp) &amp;&amp; !ferror(fp))&quot;</p> <p>Any help will be appreciated.</p>
[ { "answer_id": 74663122, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": true, "text": "int CheckSumCalc(char * filename){\n FILE *fp = fopen(filename,\"rb\");\n if(fp == NULL)\n {\n //handle error here\n return -1;\n }\n unsigned char checksum = 0;\n while (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n }\n fclose(fp);\n return checksum;\n}\n" }, { "answer_id": 74663129, "author": "browsnick", "author_id": 19621738, "author_profile": "https://Stackoverflow.com/users/19621738", "pm_score": 0, "selected": false, "text": "int CheckSumCalc(char * filename){\nFILE *fp = fopen(filename, \"rb\");\nif (fp == NULL) {\n // Handle error: file could not be opened\n return -1;\n}\n\nunsigned char checksum = 0;\nwhile (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n}\nfclose(fp);\nreturn checksum;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14888108/" ]
74,663,109
<p>I have a byte array that I made, and I am writing it to a json file. This works, but I want to have a formatted JSON file instead of a massive wall of text.</p> <p>I have tried decoding the byte array with utf-8, but instead I get <code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte</code>. My plan was to then take this string and use json.dumps() to format it.</p> <p>Trying json.dumps() without any other formatting gives this: <code>TypeError: Object of type bytearray is not JSON serializable</code></p> <pre><code>content = bytearray() content_idx = 0 try: with open(arguments.input_file, 'rb') as input_file: while (byte:=input_file.read(1)): content += bytes([ord(byte) ^ xor_key[content_idx % (len(xor_key))]]) content_idx += 1 except (IOError, OSError) as exception: print('Error: could not read input file') exit() try: with open(arguments.output_file, 'wb') as output_file: output_file.write(json.dumps(content.decode('utf-8'), indent=4)) except (IOError, OSError) as exception: print('Error: could not create output file') exit() </code></pre>
[ { "answer_id": 74663122, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": true, "text": "int CheckSumCalc(char * filename){\n FILE *fp = fopen(filename,\"rb\");\n if(fp == NULL)\n {\n //handle error here\n return -1;\n }\n unsigned char checksum = 0;\n while (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n }\n fclose(fp);\n return checksum;\n}\n" }, { "answer_id": 74663129, "author": "browsnick", "author_id": 19621738, "author_profile": "https://Stackoverflow.com/users/19621738", "pm_score": 0, "selected": false, "text": "int CheckSumCalc(char * filename){\nFILE *fp = fopen(filename, \"rb\");\nif (fp == NULL) {\n // Handle error: file could not be opened\n return -1;\n}\n\nunsigned char checksum = 0;\nwhile (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n}\nfclose(fp);\nreturn checksum;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13406740/" ]
74,663,124
<p>I'm dealing with a ASP.NET Core Web API program.<br /> As we all know, when the url doesn't match any endpoints, the server will automatically return 404 code.</p> <p>Now that I want the service to record these requests into a log, so I want to set a default handler for them.<br /> Is it possible? How?</p>
[ { "answer_id": 74663122, "author": "DotNetRussell", "author_id": 2051392, "author_profile": "https://Stackoverflow.com/users/2051392", "pm_score": 2, "selected": true, "text": "int CheckSumCalc(char * filename){\n FILE *fp = fopen(filename,\"rb\");\n if(fp == NULL)\n {\n //handle error here\n return -1;\n }\n unsigned char checksum = 0;\n while (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n }\n fclose(fp);\n return checksum;\n}\n" }, { "answer_id": 74663129, "author": "browsnick", "author_id": 19621738, "author_profile": "https://Stackoverflow.com/users/19621738", "pm_score": 0, "selected": false, "text": "int CheckSumCalc(char * filename){\nFILE *fp = fopen(filename, \"rb\");\nif (fp == NULL) {\n // Handle error: file could not be opened\n return -1;\n}\n\nunsigned char checksum = 0;\nwhile (!feof(fp) && !ferror(fp)) {\n checksum ^= fgetc(fp);\n}\nfclose(fp);\nreturn checksum;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12692895/" ]
74,663,148
<p>I'd like to try to eliminate bounds checking on code generated by Rust. I have variables that are rarely zero and my code paths ensure they do not run into trouble. But because they can be, I cannot use <code>NonZeroU64</code>. When I am sure they are non-zero, how can I signal this to the compiler?</p> <p>For example, if I have the <a href="https://play.rust-lang.org/?version=stable&amp;mode=release&amp;edition=2021&amp;gist=ebdd2e76b5e4ddd7e515cb49be3995f2" rel="nofollow noreferrer">following function</a>, I know it will be non-zero. Can I tell the compiler this or do I have to have the unnecessary check?</p> <pre><code>pub fn f(n:u64) -&gt; u32 { n.trailing_zeros() } </code></pre> <p>I can wrap the number in <code>NonZeroU64</code> when I am sure, but then I've already incurred the check, which defeats the purpose ...</p>
[ { "answer_id": 74663647, "author": "Peng Guanwen", "author_id": 5875980, "author_profile": "https://Stackoverflow.com/users/5875980", "pm_score": 0, "selected": false, "text": "trailing_zeros() use std::num::NonZeroU64;\n\npub fn g(n: NonZeroU64) -> u32 {\n n.trailing_zeros()\n}\n\npub fn other_fun(n: u64) -> u32 {\n if n != 0 {\n println!(\"Do something with non-zero!\");\n let n = NonZeroU64::new(n).unwrap();\n g(n)\n } else {\n 42\n }\n}\n if n != 0 unwrap NonZeroU64::new(n).unwrap()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002430/" ]
74,663,165
<pre><code>cat Prog4CCM.py numberArray = [] count = 0 #filename = input(&quot;Please enter the file name: &quot;) filename = &quot;t.txt&quot; # for testing purposes file = open(filename, &quot;r&quot;) for each_line in file: numberArray.append(each_line) for i in numberArray: print(i) count = count + 1 def findMaxValue(numberArray, count): maxval = numberArray[0] for i in range(0, count): if numberArray[i] &gt; maxval: maxval = numberArray[i] return maxval def findMinValue(numberArray, count): minval = numberArray[0] for i in range(0, count): if numberArray[i] &lt; minval: minval = numberArray[i] return minval def findFirstOccurence(numberArray, vtf, count): for i in range(0, count): if numberArray[i] == vtf: return i break i = i + 1 # Function calls start print(&quot;The maxiumum value in the file is &quot;+ str(findMaxValue(numberArray, count))) print(&quot;The minimum value in the file is &quot;+str(findMinValue(numberArray, count))) vtf = input(&quot;Please insert the number you would like to find the first occurence of: &quot;) print(&quot;First occurence is at &quot;+str(findFirstOccurence(numberArray, vtf, count))) </code></pre> <p>This is supposed to call a function (Find First Occurrence) and check for the first occurrence in my array.</p> <p>It should return a proper value, but just returns &quot;None&quot;. Why might this be?</p> <p>The file reading, and max and min value all seem to work perfectly.</p>
[ { "answer_id": 74663647, "author": "Peng Guanwen", "author_id": 5875980, "author_profile": "https://Stackoverflow.com/users/5875980", "pm_score": 0, "selected": false, "text": "trailing_zeros() use std::num::NonZeroU64;\n\npub fn g(n: NonZeroU64) -> u32 {\n n.trailing_zeros()\n}\n\npub fn other_fun(n: u64) -> u32 {\n if n != 0 {\n println!(\"Do something with non-zero!\");\n let n = NonZeroU64::new(n).unwrap();\n g(n)\n } else {\n 42\n }\n}\n if n != 0 unwrap NonZeroU64::new(n).unwrap()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17215983/" ]
74,663,179
<p>How would I go about making a countdown clock using only HTML and JS? Problem is, there are a few features that are required: • It must reset on a page reload • It must count down from a certain number of hours <strong>from page load</strong> (i.e. not a universal time)</p> <p>I realize these are a lot of demands, but anything hints/tips/advice will help. Thanks in advance :]</p> <p>I've tried some online timers, but they are universal and don't reset on a page reload.</p>
[ { "answer_id": 74663647, "author": "Peng Guanwen", "author_id": 5875980, "author_profile": "https://Stackoverflow.com/users/5875980", "pm_score": 0, "selected": false, "text": "trailing_zeros() use std::num::NonZeroU64;\n\npub fn g(n: NonZeroU64) -> u32 {\n n.trailing_zeros()\n}\n\npub fn other_fun(n: u64) -> u32 {\n if n != 0 {\n println!(\"Do something with non-zero!\");\n let n = NonZeroU64::new(n).unwrap();\n g(n)\n } else {\n 42\n }\n}\n if n != 0 unwrap NonZeroU64::new(n).unwrap()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18360691/" ]
74,663,202
<p>I'm looking for a similar markdown syntax to <code>&amp;shy;</code> in HTML.</p> <p>I know there are hard breaks in markdown, but I'm looking for something that acts like <code>&amp;shy;</code> or similar.</p>
[ { "answer_id": 74663226, "author": "haggbart", "author_id": 15949328, "author_profile": "https://Stackoverflow.com/users/15949328", "pm_score": 2, "selected": true, "text": "&shy; &nbsp; &nbsp; hello&nbsp;world\n" }, { "answer_id": 74670398, "author": "tarleb", "author_id": 2425163, "author_profile": "https://Stackoverflow.com/users/2425163", "pm_score": 0, "selected": false, "text": "&shy;" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9229256/" ]
74,663,209
<p>i have a problem which i am trying to solve and cant for the life of me figure it out. I feel like its the simplest answer but yet i'm still stuck.</p> <p>The instructions stated that the application must do the following: Ask the user to input the marks for the five subjects in a list/array. The program must ensure that the marks are between 0 and 100 Display the list/array of marks entered. Find the sum of all the marks in the list (all five subjects) and display the output as: The sum of your marks is: [sum] Find the average of all the marks in the list (all five subjects) and display the output as: The average of your marks is: [average mark]</p> <p>this is what i have tried</p> <pre><code>print(&quot;please enter your 5 marks below&quot;) # read 5 inputs mark1 = int(input(&quot;enter mark 1: &quot;)) if mark1 &lt;= 0 or mark1 &lt;= 100: print(&quot;Mark is acceptable&quot;) else: print(&quot;Mark is not acceptable&quot;) mark1 = int(input(&quot;enter mark 1: &quot;)) mark2 = int(input(&quot;enter mark 2: &quot;)) if mark2 &lt;= 0 or mark2 &lt;= 100: print(&quot;Mark is acceptable&quot;) else: print(&quot;Mark is not acceptable&quot;) mark2 = int(input(&quot;enter mark 2: &quot;)) mark3 = int(input(&quot;enter mark 3: &quot;)) if mark3 &lt;= 0 or mark3 &lt;= 100: print(&quot;Mark is acceptable&quot;) else: print(&quot;Mark is not acceptable&quot;) mark3 = int(input(&quot;enter mark 3: &quot;)) mark4 = int(input(&quot;enter mark 4: &quot;)) if mark4 &lt;= 0 or mark4 &lt;= 100: print(&quot;Mark is acceptable&quot;) else: print(&quot;Mark is not acceptable&quot;) mark4 = int(input(&quot;enter mark 4: &quot;)) mark5 = int(input(&quot;enter mark 5: &quot;)) if mark5 &lt;= 0 or mark5 &lt;= 100: print(&quot;Mark is acceptable&quot;) # create array/list with five marks marksList = [mark1, mark2, mark3, mark4, mark5] # print the array/list print(marksList) # calculate the sum and average sumOfMarks = sum(marksList) averageOfMarks = sum(marksList) / 5 # display results print(&quot;The sum of your marks is: &quot; + str(sumOfMarks)) print(&quot;The average of your marks is: &quot; + str(averageOfMarks)) </code></pre>
[ { "answer_id": 74663271, "author": "J Muzhen", "author_id": 12341397, "author_profile": "https://Stackoverflow.com/users/12341397", "pm_score": 0, "selected": false, "text": "while marksList = []\ni = 1\n\nwhile len(marksList) < 5:\n mark = int(input(f\"Input mark {i}\"))\n if 0 <= mark <= 100:\n print(\"Mark is acceptable\")\n marksList.append(mark)\n i += 1\n else:\n print(\"Mark is not acceptable\")\n while print(marksList)\n\nsum = sum(marksList) # sum\naverage = average(marksList) # there is a built-in average() function!\n\nprint(...)\n try-except # ... (same code)\nwhile len(marksList) < 5:\n try:\n mark = int(input(f\"Input mark {i}\"))\n except ValueError:\n print(\"Please enter an integer.\")\n continue\n # ... (same code)\n" }, { "answer_id": 74663292, "author": "Craze XD", "author_id": 15866230, "author_profile": "https://Stackoverflow.com/users/15866230", "pm_score": 0, "selected": false, "text": "marks = []\nfor i in range(1, 6): # needs to be 1 to 6 since the 6 won't be included but the 1 will \n mark = int(input(f\"Enter mark number {i}: \")\n while mark<0 or mark>100:\n print(\"Invalid mark\")\n mark = int(input(f\"Enter mark number {i}: \")\n marks+=mark\n\n\nsums = sum(marks)\nprint(f\"The sum of your marks is {sums}\")\nprint(f\"The average of your marks is {sums/5}\")\n" }, { "answer_id": 74663296, "author": "ChioStar", "author_id": 20243451, "author_profile": "https://Stackoverflow.com/users/20243451", "pm_score": -1, "selected": false, "text": "map map(function, iter) function int int input().split() all() True x == True n = list(map(int, input().split()))\nx = all(i >= 0 and i <= 100 for i in n)\nif x == True:\n print('The sum of your marks is: ', sum(n))\n print('The average of your marks is:', sum(n) / 5)\n try/except/else x == False x == True while True:\n try:\n n = list(map(int, input().split()))\n x = all(i >= 0 and i <= 100 for i in n)\n if x == False:\n raise Exception\n except Exception:\n pass\n else:\n print('The sum of your marks is: ', sum(n))\n print('The average of your marks is:', sum(n) / 5)\n break\n" }, { "answer_id": 74663584, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "while try except := range() print(\"please enter your 5 marks below\")\nmarks, nth= list(), 1\nwhile len(marks) < 5:\n try:\n if not (mark := int(input(f\"enter mark {nth}: \"))) in range(101):\n print(\"Mark is not acceptable\")\n else:\n print(\"Mark is acceptable\")\n marks += [mark]\n nth += 1\n except ValueError:\n print(\"Mark is not acceptable\")\n\nprint(\"Your marks: \", *marks)\nprint(\"The sum of your marks is: \", sum(marks))\nprint(\"The average of your marks is: \", sum(marks)/len(marks))\n please enter your 5 marks below\nenter mark 1: no\nMark is not acceptable\nenter mark 1: 67\nMark is acceptable\nenter mark 2: 0\nMark is acceptable\nenter mark 3: \nMark is not acceptable\nenter mark 3: 56\nMark is acceptable\nenter mark 4: 101\nMark is not acceptable\nenter mark 4: 75\nMark is acceptable\nenter mark 5: 81\nMark is acceptable\nYour marks: 67 0 56 75 81\nThe sum of your marks is: 279\nThe average of your marks is: 55.8\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671087/" ]
74,663,224
<p>I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just need help on the line where the error is occurring to start with.</p> <p>Instructions:</p> <ul> <li>create a function that asks the user to enter their birthday and returns a date object. Validate user input as well. This function must NOT take any parameters.</li> <li>create another function that takes the date object as a parameter. Calculate the age of the user using their birth year and the current year.</li> </ul> <pre><code>def func1(): bd = input(&quot;When is your birthday? &quot;) try: dt.datetime.strptime(bd, &quot;%m/%d/%Y&quot;) except ValueError as e: print(&quot;There is a ValueError. Please format as MM/DD/YYY&quot;) except Exception as e: print(e) return bd def func2(bd): today = dt.datetime.today() age = today.year - bd.year return age </code></pre> <p>This is the Error I get:</p> <pre><code>TypeError: func2() missing 1 required positional argument: 'bday' </code></pre> <p>So far, I've tried:</p> <ul> <li>assigning the func1 to a variable and passing the variable as func2 parameter</li> <li>calling func1 inside func2</li> <li>defining func1 inside func2</li> </ul>
[ { "answer_id": 74663271, "author": "J Muzhen", "author_id": 12341397, "author_profile": "https://Stackoverflow.com/users/12341397", "pm_score": 0, "selected": false, "text": "while marksList = []\ni = 1\n\nwhile len(marksList) < 5:\n mark = int(input(f\"Input mark {i}\"))\n if 0 <= mark <= 100:\n print(\"Mark is acceptable\")\n marksList.append(mark)\n i += 1\n else:\n print(\"Mark is not acceptable\")\n while print(marksList)\n\nsum = sum(marksList) # sum\naverage = average(marksList) # there is a built-in average() function!\n\nprint(...)\n try-except # ... (same code)\nwhile len(marksList) < 5:\n try:\n mark = int(input(f\"Input mark {i}\"))\n except ValueError:\n print(\"Please enter an integer.\")\n continue\n # ... (same code)\n" }, { "answer_id": 74663292, "author": "Craze XD", "author_id": 15866230, "author_profile": "https://Stackoverflow.com/users/15866230", "pm_score": 0, "selected": false, "text": "marks = []\nfor i in range(1, 6): # needs to be 1 to 6 since the 6 won't be included but the 1 will \n mark = int(input(f\"Enter mark number {i}: \")\n while mark<0 or mark>100:\n print(\"Invalid mark\")\n mark = int(input(f\"Enter mark number {i}: \")\n marks+=mark\n\n\nsums = sum(marks)\nprint(f\"The sum of your marks is {sums}\")\nprint(f\"The average of your marks is {sums/5}\")\n" }, { "answer_id": 74663296, "author": "ChioStar", "author_id": 20243451, "author_profile": "https://Stackoverflow.com/users/20243451", "pm_score": -1, "selected": false, "text": "map map(function, iter) function int int input().split() all() True x == True n = list(map(int, input().split()))\nx = all(i >= 0 and i <= 100 for i in n)\nif x == True:\n print('The sum of your marks is: ', sum(n))\n print('The average of your marks is:', sum(n) / 5)\n try/except/else x == False x == True while True:\n try:\n n = list(map(int, input().split()))\n x = all(i >= 0 and i <= 100 for i in n)\n if x == False:\n raise Exception\n except Exception:\n pass\n else:\n print('The sum of your marks is: ', sum(n))\n print('The average of your marks is:', sum(n) / 5)\n break\n" }, { "answer_id": 74663584, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "while try except := range() print(\"please enter your 5 marks below\")\nmarks, nth= list(), 1\nwhile len(marks) < 5:\n try:\n if not (mark := int(input(f\"enter mark {nth}: \"))) in range(101):\n print(\"Mark is not acceptable\")\n else:\n print(\"Mark is acceptable\")\n marks += [mark]\n nth += 1\n except ValueError:\n print(\"Mark is not acceptable\")\n\nprint(\"Your marks: \", *marks)\nprint(\"The sum of your marks is: \", sum(marks))\nprint(\"The average of your marks is: \", sum(marks)/len(marks))\n please enter your 5 marks below\nenter mark 1: no\nMark is not acceptable\nenter mark 1: 67\nMark is acceptable\nenter mark 2: 0\nMark is acceptable\nenter mark 3: \nMark is not acceptable\nenter mark 3: 56\nMark is acceptable\nenter mark 4: 101\nMark is not acceptable\nenter mark 4: 75\nMark is acceptable\nenter mark 5: 81\nMark is acceptable\nYour marks: 67 0 56 75 81\nThe sum of your marks is: 279\nThe average of your marks is: 55.8\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671018/" ]
74,663,272
<p>In this case, the &quot;all_lines&quot; variable is initalised in the context manager, and it is accessible from the function &quot;part_1&quot;.</p> <pre><code>total = 0 with open(&quot;advent_input.txt&quot;, &quot;r&quot;) as txt: all_lines = [] context_total = 0 for line in txt: all_lines.append((line.rstrip().split(&quot; &quot;))) def part_1(): # total = 0 for line in all_lines: if line[0] == &quot;A&quot;: if line[1] == &quot;Y&quot;: total += 8 elif line[1] == &quot;X&quot;: context_total += 4 </code></pre> <p>However, &quot;context_total&quot;, which is also initalised in the context manager, does not work in the function &quot;part_1&quot;. And &quot;total&quot; from the global scope does not work either. How come &quot;all_lines&quot; works?</p>
[ { "answer_id": 74663290, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "all_lines" }, { "answer_id": 74663298, "author": "Carcigenicate", "author_id": 3000206, "author_profile": "https://Stackoverflow.com/users/3000206", "pm_score": 1, "selected": false, "text": "with context_total global += global context_total" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671144/" ]
74,663,274
<p>I'm getting the error</p> <blockquote> <p>CS0426 &quot;the type name 'GetRequest' does not exist in the type 'Request'</p> </blockquote> <p>when I'm quite sure that it does. I don't understand what I possibly did wrong here. Here's the code I'm working with:</p> <pre><code>public class Request { public static Request GetRequest() { return null; } } </code></pre> <p>In this class you can clearly see that <code>GetRequest</code> does infact exist within the type 'Request'. However when I try and use this method I get an error saying that it doesn't exist.</p> <p>This line generates the error I have been getting:</p> <pre><code>Request req = new Request.GetRequest(); </code></pre>
[ { "answer_id": 74663314, "author": "SilicDev", "author_id": 20614914, "author_profile": "https://Stackoverflow.com/users/20614914", "pm_score": 1, "selected": false, "text": "new Request.GetRequest(msg); Request.GetRequest(msg) GetRequest" }, { "answer_id": 74663325, "author": "haggbart", "author_id": 15949328, "author_profile": "https://Stackoverflow.com/users/15949328", "pm_score": 2, "selected": false, "text": "Request req = Request.GetRequest(msg);\n Request request = new Request();\nRequest req = request.GetRequest(msg);\n public Request GetRequest(String request)\n{\n if (string.IsNullOrEmpty(request)) { return null; } //return null if the string is empty or nothing\n\n String[] tokens = request.Split(' ');\n String type = tokens[0];\n String url = tokens[1];\n String host = tokens[4];\n\n return new Request(type, url, host);\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17978542/" ]
74,663,305
<p>Is there a way to continue a function based on where it was last run.</p> <p>We want each call to do something else, e.g. (first call adds 1, second adds 2, third call adds 3), and then do something else.</p> <pre class="lang-py prettyprint-override"><code>def a_generator(): yield lambda x: x + 1 yield lambda x: x + 2 yield lambda x: x + 3 yield lambda x: f&quot;Okay we are almost complete {x}&quot; generator = a_generator() </code></pre> <p>What currently works:</p> <pre class="lang-py prettyprint-override"><code>assert next(generator)(5) == 6 assert next(generator)(5) == 7 assert next(generator)(5) == 8 assert next(generator)(5) == &quot;Okay we are almost complete 5&quot; </code></pre> <p>What I want to be able to do:</p> <pre class="lang-py prettyprint-override"><code>assert generator(5) == 6 assert generator(5) == 7 assert generator(5) == 8 assert generator(5) == &quot;Okay we are almost complete 5&quot; </code></pre>
[ { "answer_id": 74663418, "author": "Kenny Ostrom", "author_id": 1766544, "author_profile": "https://Stackoverflow.com/users/1766544", "pm_score": 1, "selected": false, "text": "def a_generator():\n yield lambda x: x + 1\n yield lambda x: x + 2\n yield lambda x: x + 3\n yield lambda x: f\"Okay we are almost complete {x}\"\n\nfor generator in a_generator():\n print(generator(5))\n" }, { "answer_id": 74674795, "author": "A H", "author_id": 8751871, "author_profile": "https://Stackoverflow.com/users/8751871", "pm_score": 0, "selected": false, "text": "generator = a_generator()\n\ndef generator_consumer(x, generator=generator):\n try:\n return next(generator)(x)\n except StopIteration:\n raise ValueError(\"Can't Run the generator anymore\")\n generator=generator assert generator_consumer(5) == 6\nassert generator_consumer(5) == 7\nassert generator_consumer(5) == 8\nassert generator_consumer(5) == \"Okay we are almost complete 5\"\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8751871/" ]
74,663,328
<p>Currently I was trying to do a machine learning classification of 6 time series datasets (in .csv format) using MiniRocket, an sktime machine learning package. However, when I imported the .csv files using pd.read_csv and run them through MiniRocket, the error &quot;TypeError: X must be in an sktime compatible format&quot; pops up, and it says that the following data types are sktime compatible: ['pd.Series', 'pd.DataFrame', 'np.ndarray', 'nested_univ', 'numpy3D', 'pd-multiindex', 'df-list', 'pd_multiindex_hier'] Then I checked the data type of my imported .csv files and got &quot;pandas.core.Frame.DataFrame&quot;, which is a data type that I never saw before and is obviously different from the sktime compatible pd.DataFrame. What is the difference between pandas.core.Frame.DataFrame and pd.DataFrame, and how to convert pandas.core.Frame.DataFrame to the sktime compatible pd.DataFrame?</p> <p>I tried to convert pandas.core.Frame.DataFrame to pd.DataFrame using df.join and df.pop functions, but neither of them was able to convert my data from pandas.core.Frame.DataFrame to pd.DataFrame (after conversion I checked the type again and it is still the same).</p>
[ { "answer_id": 74663418, "author": "Kenny Ostrom", "author_id": 1766544, "author_profile": "https://Stackoverflow.com/users/1766544", "pm_score": 1, "selected": false, "text": "def a_generator():\n yield lambda x: x + 1\n yield lambda x: x + 2\n yield lambda x: x + 3\n yield lambda x: f\"Okay we are almost complete {x}\"\n\nfor generator in a_generator():\n print(generator(5))\n" }, { "answer_id": 74674795, "author": "A H", "author_id": 8751871, "author_profile": "https://Stackoverflow.com/users/8751871", "pm_score": 0, "selected": false, "text": "generator = a_generator()\n\ndef generator_consumer(x, generator=generator):\n try:\n return next(generator)(x)\n except StopIteration:\n raise ValueError(\"Can't Run the generator anymore\")\n generator=generator assert generator_consumer(5) == 6\nassert generator_consumer(5) == 7\nassert generator_consumer(5) == 8\nassert generator_consumer(5) == \"Okay we are almost complete 5\"\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671165/" ]
74,663,337
<pre><code>import { useState, useRef } from 'react' import './App.css' function App() { const [circle, setCircle] = useState([]) const refElement = useRef(null); const width = 500; const height = 500; const circleX= Math.floor(Math.random() * 400); const circleY = Math.floor(Math.random() * 400); const circleRadius = 20; const randomColor = '#' + (Math.random().toString(16) + &quot;000000&quot;).substring(2,8) const LeadCircle = &lt;circle cx={circleX} cy={circleY} r={circleRadius} fill={randomColor} stroke={&quot;black&quot;} strokeWidth={&quot;10&quot;}/&gt; const Circle = &lt;circle cx={circleX} cy={circleY} r={circleRadius} fill={randomColor}/&gt; const addLead = () =&gt;{ console.log(&quot;circleLead added &quot; + LeadCircle) LeadCircle setCircle(previous =&gt;[...circle,previous]); } const addNormal = () =&gt;{ console.log(&quot;circleNormal added &quot; + Circle) } const removeLast = () =&gt;{ } const removeAll = () =&gt;{ } return ( &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;doobverse setup with svg&lt;/h1&gt; &lt;div className=&quot;card&quot;&gt; &lt;div id=&quot;svg-container&quot;&gt; &lt;svg width={width} height={height} style={{border:&quot;2px solid white&quot;}} useref={refElement}&gt; {LeadCircle} &lt;/svg&gt; &lt;/div&gt; &lt;br&gt;&lt;/br&gt; &lt;br&gt;&lt;/br&gt; &lt;button id={&quot;addLead&quot;} onClick={addLead}&gt; Add lead &lt;/button&gt; &lt;button onClick={addNormal}&gt; Add normal &lt;/button&gt; &lt;br&gt;&lt;/br&gt;&lt;br&gt;&lt;/br&gt; &lt;button onClick={removeLast}&gt; remove one &lt;/button&gt; &lt;button onClick={removeAll}&gt; remove all &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ) } export default App </code></pre> <p>So thats my Code,</p> <p>I just want to have a simple React app, where you can add a circle on button click, remove the last drawn circle, and remove all drawn circles... Ive tried to do this with canvas before. I could draw circles on click but had Problems removing them, so I have asked in a Discord where they explained me that you need to clear and redraw the canvas every time you want to remove an element and that its easier to work with svgs, so I've set the thing up with svgs but now its not even working with the add function...</p> <p>Thx for help !!</p> <p>:)</p>
[ { "answer_id": 74663418, "author": "Kenny Ostrom", "author_id": 1766544, "author_profile": "https://Stackoverflow.com/users/1766544", "pm_score": 1, "selected": false, "text": "def a_generator():\n yield lambda x: x + 1\n yield lambda x: x + 2\n yield lambda x: x + 3\n yield lambda x: f\"Okay we are almost complete {x}\"\n\nfor generator in a_generator():\n print(generator(5))\n" }, { "answer_id": 74674795, "author": "A H", "author_id": 8751871, "author_profile": "https://Stackoverflow.com/users/8751871", "pm_score": 0, "selected": false, "text": "generator = a_generator()\n\ndef generator_consumer(x, generator=generator):\n try:\n return next(generator)(x)\n except StopIteration:\n raise ValueError(\"Can't Run the generator anymore\")\n generator=generator assert generator_consumer(5) == 6\nassert generator_consumer(5) == 7\nassert generator_consumer(5) == 8\nassert generator_consumer(5) == \"Okay we are almost complete 5\"\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20152076/" ]
74,663,343
<p>In a number without leading zeroes I would do this</p> <pre><code>import math num = 1001 digits = int(math.log10(num))+1 print (digits) &gt;&gt;&gt; 4 </code></pre> <p>but if use a number with leading zeroes like &quot;0001&quot; I get</p> <p><code>SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers</code></p> <p>I would like to be able to count the digits including the leading zeroes. What would be the best way to achieve this?</p>
[ { "answer_id": 74663366, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 1, "selected": false, "text": ">>> value = input(\"enter a number: \")\nenter a number: 0001\n>>> value_clean = value.lstrip(\"0\")\n>>> leading_zeros = len(value) - len(value_clean)\n>>> print(\"leading zeros: {}\".format(leading_zeros))\n3\n int() >>> int(\"0001\")\n1\n" }, { "answer_id": 74663734, "author": "user4611642", "author_id": 4611642, "author_profile": "https://Stackoverflow.com/users/4611642", "pm_score": 0, "selected": false, "text": "num = 0001\nnum_string = str(num) \nprint (len(num_string))\n\n >>> 4\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4611642/" ]
74,663,367
<p>When I run this:</p> <pre><code>import pandas as pd data = {'id': ['earn', 'earn','lose', 'earn'], 'game': ['darts', 'balloons', 'balloons', 'darts'] } df = pd.DataFrame(data) print(df) print(df.loc[[1],['id']] == 'earn') </code></pre> <p>The output is:<br /> id game<br /> 0 earn darts<br /> 1 earn balloons<br /> 2 lose balloons<br /> 3 earn darts<br /> id<br /> 1 True</p> <p>But when I try to run this loop:</p> <pre><code>for i in range(len(df)): if (df.loc[[i],['id']] == 'earn'): print('yes') else: print('no') </code></pre> <p>I get the error 'ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' I am not sure what the problem is. Any help or advice is appreciated -- I am just starting.</p> <p>I expected the output to be 'yes' from the loop. But I just got the 'ValueError' message. But, when I run the condition by itself, the output is 'True' so I'm not sure what is wrong.</p>
[ { "answer_id": 74663550, "author": "Ty Batten", "author_id": 4595201, "author_profile": "https://Stackoverflow.com/users/4595201", "pm_score": 1, "selected": false, "text": "for i,row in df.iterrows():\n if row.id == \"earn\":\n print(\"yes\")\n" }, { "answer_id": 74663553, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 1, "selected": true, "text": "pandas df.loc DataFrame Series DataFrame Series == DataFrame >>> foo = df.loc[[1], ['id']]\n>>> type(foo)\n<class 'pandas.core.frame.DataFrame'>\n>>> foo\n id\n1 earn\n>>> foo == \"earn\"\n id\n1 True\n Series >>> foo = df.loc[[1], 'id']\n>>> type(foo)\n<class 'pandas.core.series.Series'>\n>>> foo\n1 earn\nName: id, dtype: object\n>>> foo == 'earn'\n1 True\nName: id, dtype: bool\n >>> foo = df.loc[1, 'id']\n>>> type(foo)\n<class 'str'>\n>>> foo\n'earn'\n>>> foo == 'earn'\nTrue\n True True for i in range(len(df)): \n if (df.loc[i,'id'] == 'earn'): \n print('yes') \n else: \n print('no')\n >>> earn = df[id'] == 'earn'\n>>> earn\n0 True\n1 True\n2 False\n3 True\nName: id, dtype: bool\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671149/" ]
74,663,374
<p>I need to track how long many processes take and so my code looks like this:</p> <pre><code>console.log(&quot;Doing thing 1&quot;); var startTime = performance.now(); var thing = doThing() times.loadTime = performance.now() - startTime; console.log(&quot;Doing thing 2&quot;); startTime = performance.now(); var thing2 = doOtherThing(); var endTime = performance.now(); times.thingTime2 = endTime - startTime; console.log(&quot;Doing thing 3&quot;); var thing3 = doThing3(); ties.thingTime3 = performance.now() - endTime; </code></pre> <p>As you can guess, this is getting hard to read.</p> <p>I know that in my current environment I can use things like:</p> <pre><code>console.startTime(); console.startTime(&quot;Thing 1&quot;); console.endTime(); </code></pre> <p>And so on. See the <a href="https://developer.mozilla.org/en-US/docs/Web/API/console" rel="nofollow noreferrer">console</a> object.</p> <p>But I think I've seen something where javascript code was using blocks or labels like this:</p> <pre><code>thing1 { var thing = doThing() } thing2 { var thing2 = doOtherThing(); } thing3 { var thing3 = doThing3(); } // desired result { name: &quot;thing1&quot;, startTime: 0, endTime: 10 } console.log(thing1); </code></pre> <p>Or labels:</p> <pre><code>thing1: var thing = doThing() end </code></pre> <p>These look much more readable to me.</p> <p>Is there a way to do this in JavaScript?</p>
[ { "answer_id": 74663386, "author": "Diego Lamarão", "author_id": 11013622, "author_profile": "https://Stackoverflow.com/users/11013622", "pm_score": 1, "selected": false, "text": "console.time(\"Doing thing 1\");\nvar thing = doThing()\nconsole.timeEnd(\"Doing thing 1\");\n\nconsole.time(\"Doing thing 2\");\nvar thing2 = doOtherThing();\nconsole.timeEnd(\"Doing thing 2\");\n\nconsole.time(\"Doing thing 3\");\nvar thing3 = doThing3();\nconsole.timeEnd(\"Doing thing 3\");\n" }, { "answer_id": 74663403, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 1, "selected": false, "text": "performance.now const times = [];\nconst measure = (cb) => {\n const startTime = performance.now();\n const result = cb();\n times.push(performance.now() - startTime);\n return result;\n};\n\nconst thing = measure(() => ({ thing1: 'foo' }));\nconst thing2 = measure(() => {\n for (let i = 0; i < 1e7; i++);\n return { thing2: 'foo' };\n});\nconst thing3 = measure(() => ({ thing3: 'foo' }));\nconsole.log(times); const times = [];\nconst measure = (name, cb) => {\n const startTime = performance.now();\n const result = cb();\n times.push({ name, time: performance.now() - startTime });\n return result;\n};\n\nconst thing = measure('thing', () => ({ thing1: 'foo' }));\nconst thing2 = measure('thing2', () => {\n for (let i = 0; i < 1e7; i++);\n return { thing2: 'foo' };\n});\nconst thing3 = measure('thing3', () => ({ thing3: 'foo' }));\nconsole.log(times);" }, { "answer_id": 74663424, "author": "EpsilonCode", "author_id": 12270119, "author_profile": "https://Stackoverflow.com/users/12270119", "pm_score": 0, "selected": false, "text": "const useMeasure = (fn) => {\n const start = performance.now();\n const res = fn();\n const end = performance.now();\n return [res, end - start];\n}\n function count() {\n let cnt = 0;\n for (let i = 0; i < 100000; i++) {\n cnt++;\n }\n return cnt;\n}\n\nconst [result, timeTaken] = useMeasure(count);\n\nconsole.log(result, timeTaken);\n const useMeasureWithArgs = (fn, ...args) => {\n const start = performance.now();\n const res = fn(...args);\n const end = performance.now();\n return [res, end - start];\n}\n function countUpTo(x) {\n let cnt = 0;\n for (let i = 0; i < x; i++) {\n cnt++;\n }\n return cnt;\n}\n\nconst [result, timeTaken] = useMeasureWithArgs(countUpTo, 1000);\n\nconsole.log(result, timeTaken);\n" }, { "answer_id": 74665190, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 1, "selected": false, "text": "console.timeEnd const T = (name='') => {\n T.timers = T.timers || []\n\n if (name)\n T.timers.push([name, performance.now()])\n else {\n let end = performance.now()\n let [name, start] = T.timers.pop()\n console.log('TIMER:', name, (end - start).toFixed(3))\n }\n}\n T('step1')\nfor (let i = 0; i < 1e6; i++) {\n heavy stuff\n}\nT()\n\nT('step2')\nfor (let i = 0; i < 1e7; i++) {\n more heavy stuff\n}\nT()\n T" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441016/" ]
74,663,376
<p>I am trying to remove all characters that are not digit, dot (.), plus/minus sign (+/-) with empty character/string for float conversion.<br> When I pass my string through regex_replace function I am returned an empty string.<br> I belive something is wrong with my regex expression <code>std::regex reg_exp(&quot;\\D|[^+-.]&quot;)</code><br><br> Code</p> <pre><code>#include &lt;iostream&gt; #include &lt;regex&gt; int main() { std::string temporary_recieve_data = &quot; S S +456.789 tg\r\n&quot;; std::string::size_type sz; const std::regex reg_exp(&quot;\\D|[^+-.]&quot;); // matches not digit, decimal point (.), plus sign, minus sign std::string numeric_string = std::regex_replace(temporary_recieve_data, reg_exp, &quot;&quot;); //replace the character that are not digit, dot (.), plus-minus sign (+,-) with empty character/string for float conversion std::cout &lt;&lt; &quot;Numeric String : &quot; &lt;&lt; numeric_string &lt;&lt; std::endl; if (numeric_string.empty()) { return 0; } float data_value = std::stof(numeric_string, &amp;sz); std::cout &lt;&lt; &quot;Float Value : &quot; &lt;&lt; data_value &lt;&lt; std::endl; return 0; } </code></pre> <hr /> <p>I have been trying to evaluate my regex expression on regex101.com for past 2 days but I am unable to figure out where I am wrong with my regular expression. When I just put \D, the editor substitutes non-digit character properly but soon as I add or condition <code>|</code> for not dot <code>.</code> or plus <code>+</code> or minus <code>-</code> sign the editor returns empty string.</p>
[ { "answer_id": 74663437, "author": "Mehmet Masa", "author_id": 20671270, "author_profile": "https://Stackoverflow.com/users/20671270", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <regex>\n\nusing namespace std;\n\nint main() {\n string input = \"Hello, world!\";\n regex pattern(\"world\");\n\n string result = regex_replace(input, pattern, \"there\");\n cout << result << endl; // Outputs \"Hello, there!\"\n\n return 0;\n}\n" }, { "answer_id": 74663653, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 3, "selected": true, "text": "\\D [^+-.] +-. \\D \\d [^\\d.+-]+\n +" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6319901/" ]
74,663,377
<p>This is more a design question so please bear with me.</p> <p>I have a system that stores locations consisting of the ID, Longitude and Latitude.</p> <p>I need to compare the distance between my current location and the locations in the database a only choose ones that are within a certain distance.</p> <p>I have the formula that calculates the distance between 2 locations based on the long/lat and that works great.</p> <p>My issue is I may have 10 of thousands of locations in the database and don't want to loop through them all every time I need a list of locations close by.</p> <p>Not sure what other datapoint I can store with the location to make it so I only have to compare a smaller subset.</p> <p>Thanks.</p>
[ { "answer_id": 74669578, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 2, "selected": true, "text": "DECLARE @g geography = 'POINT(-121.626 47.8315)';\n\nSELECT TOP(7) SpatialLocation.ToString(), City\nFROM Person.Address \nWHERE SpatialLocation.STDistance(@g) IS NOT NULL \nORDER BY SpatialLocation.STDistance(@g); \n top" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2125182/" ]
74,663,379
<p>I have the code below:</p> <pre><code> &lt;ng-select [multiple]=&quot;true&quot; [addTag]=&quot;addTag&quot; id=&quot;fieldId&quot; [ngClass]=&quot;formValidatorHelper.applyCssError(MyService.form.controls['fieldId'])&quot; formControlName=&quot;fieldId&quot;&gt; &lt;/ng-select&gt; </code></pre> <p>I Need to add the mask '000.000.000-00' for each data added.. Can someone help-me?</p> <p>I tryed to add mask=&quot;000.000.000-00&quot; but not ok.</p>
[ { "answer_id": 74669578, "author": "Ben Thul", "author_id": 568209, "author_profile": "https://Stackoverflow.com/users/568209", "pm_score": 2, "selected": true, "text": "DECLARE @g geography = 'POINT(-121.626 47.8315)';\n\nSELECT TOP(7) SpatialLocation.ToString(), City\nFROM Person.Address \nWHERE SpatialLocation.STDistance(@g) IS NOT NULL \nORDER BY SpatialLocation.STDistance(@g); \n top" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19175887/" ]
74,663,397
<p>To get the minimum value in an array, I made the method minValue</p> <pre class="lang-java prettyprint-override"><code>public int minValue() { int smallestVal = 0; //field if (intArray.length == 0) { //if array is empty, return 0 return 0; } int a = intArray[0]; //field for (int i : intArray) { if (i &gt; a) { smallestVal = a; } else { a = i; } } return smallestVal; //returns the smallest value } </code></pre> <p>Tested it in a main method with <code>arr9 = { 1, 2, -1, 40, 1, 40, 0, 0, -3, 2, 2, -2, -5, 0, 1, -4, -5 }</code> and <code>arr10 = { 4, 5, 5, 4, 1, 5, -3, 4, -1, -2, -2, -2, -2, -2, -2, 1, 4, 5, -5 }</code></p> <p>For arr9, it returns -5 but for arr10 it returns -3 instead of -5. Is there something I need to change in my code?</p>
[ { "answer_id": 74663412, "author": "Erik McKelvey", "author_id": 13179199, "author_profile": "https://Stackoverflow.com/users/13179199", "pm_score": 1, "selected": false, "text": "smallestVal a int smallestVal = intArray[0]; //field\nfor (int i : intArray){\n if (i < smallestVal){\n smallestVal = i;\n }\n }\n" }, { "answer_id": 74663422, "author": "SilicDev", "author_id": 20614914, "author_profile": "https://Stackoverflow.com/users/20614914", "pm_score": 0, "selected": false, "text": "if (i > a) {\n smallestVal = a;\n}\nelse {\n a = i;\n}\n a i i a smallestVal a i a i a a smalledtVal smallestVal a a a smallestVal" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671199/" ]
74,663,441
<p>I am using <code>flask</code> and <code>flask-restx</code> try to create a protocol to get a specific string from another service. I am wonder if there is a way I can pass the parameter from another function to server side. For example, here's my server side:</p> <pre><code>from flask_restx import Api,fields,Resource from flask import Flask app = Flask(__name__) api = Api(app) parent = api.model('Parent', { 'name': fields.String(get_answer(a,b)), 'class': fields.String(discriminator=True) }) @api.route('/language') class Language(Resource): # @api.marshal_with(data_stream_request) @api.marshal_with(parent) @api.response(403, &quot;Unauthorized&quot;) def get(self): return {&quot;happy&quot;: &quot;good&quot;} </code></pre> <p>get_answer function in a different file:</p> <pre><code>get_answer(a,b): return a + b </code></pre> <p>What I expect is to get the result of <code>get_answer</code> from a file, and then my API is generated so that the GET request can get it. I know that if there is a web page, we can use <code>render_template(</code> or <code>form</code> to get it. But what if I want to get the value from another function? I know we only run the server with <code>app.run()</code>, but are we able to pass any value into the server? Guessing <code>app.run(a,b)</code> should not work in this case. We definite need to pass two parameter into the server. Or we can store the answer of <code>get_answer(a,b)</code> in main with specific value of <code>a</code> and <code>b</code>, then pass the number into the server side. But it will need the parameter either way.</p> <hr /> <p>One thing I've tested is wrapping up the server into a function. But in our case, is it a good idea to wrap a class inside a function as we have <code>class Language(Resource):</code>?</p>
[ { "answer_id": 74663412, "author": "Erik McKelvey", "author_id": 13179199, "author_profile": "https://Stackoverflow.com/users/13179199", "pm_score": 1, "selected": false, "text": "smallestVal a int smallestVal = intArray[0]; //field\nfor (int i : intArray){\n if (i < smallestVal){\n smallestVal = i;\n }\n }\n" }, { "answer_id": 74663422, "author": "SilicDev", "author_id": 20614914, "author_profile": "https://Stackoverflow.com/users/20614914", "pm_score": 0, "selected": false, "text": "if (i > a) {\n smallestVal = a;\n}\nelse {\n a = i;\n}\n a i i a smallestVal a i a i a a smalledtVal smallestVal a a a smallestVal" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19574548/" ]
74,663,469
<p>I can collect all of the input data, but I just can't seem to do anything with it. I would like to print all of data or add or subtract the numbers, perform calculations. I am not sure how to work with nested data.</p> <pre><code>import java.util.Scanner; public class Names { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(&quot;How many students do you want to enter?&quot;); String[] names = new String[2]; for (int stnumber = 0; stnumber &lt; 2; stnumber++) { System.out.println(&quot;Enter the first student &quot; + (stnumber + 1)); names[stnumber] = input.next(); String[] quiz = new String[2]; for (int qznumber = 0; qznumber &lt; 2; qznumber++) { System.out.println(&quot;Enter quiz mark &quot; + (qznumber + 1)); quiz[qznumber] = input.next(); } String[] midterm = new String[1]; for (int mtnumber = 0; mtnumber &lt; 1; mtnumber++) { System.out.println(&quot;Enter midterm mark &quot; + (mtnumber + 1)); midterm[mtnumber] = input.next(); } String[] myfinal = new String[1]; for (int fnnumber = 0; fnnumber &lt; 1; fnnumber++) { System.out.println(&quot;Enter final mark &quot; + (fnnumber + 1)); myfinal[fnnumber] = input.next(); } } input.close(); System.out.println(&quot;The students marks are&quot;); for (int stnumber = 0; stnumber &lt; 2; stnumber++) { System.out.println(names[stnumber]); } } } </code></pre>
[ { "answer_id": 74663516, "author": "Erik McKelvey", "author_id": 13179199, "author_profile": "https://Stackoverflow.com/users/13179199", "pm_score": 0, "selected": false, "text": "class public class Student {\n String name;\n String[] quizzes;\n String[] midterms;\n String[] finals;\n}\n public Student(String name) {\n this.name = name;\n this.quizzes = new String[2];\n this.midterms = new String[2];\n this.finals = new String[1];\n} \n Student newStudent = new Student(\"put the name here\");\n newStudent.midterms[0] = \"midterm 1 grade\";\n" }, { "answer_id": 74671299, "author": "Newbe", "author_id": 20671289, "author_profile": "https://Stackoverflow.com/users/20671289", "pm_score": -1, "selected": false, "text": "public class Student {\nString name;\nString[] quizzes;\nString[] midterms;\nString[] finals;\n}\n\n\npublic Student(String name) {\nthis.name = name;\nthis.quizzes = new String[2];\nthis.midterms = new String[2];\nthis.finals = new String[1];\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671289/" ]
74,663,472
<p>How do you <code>x.py install</code> rust built from git source to a prefix other than <code>/usr/local</code>?</p> <p>I tried:</p> <pre><code>git/rust&gt; python x.py install --prefix=/my/prefix </code></pre> <p>but it doesn't work:</p> <pre><code>error: Unrecognized option: 'prefix' </code></pre>
[ { "answer_id": 74663516, "author": "Erik McKelvey", "author_id": 13179199, "author_profile": "https://Stackoverflow.com/users/13179199", "pm_score": 0, "selected": false, "text": "class public class Student {\n String name;\n String[] quizzes;\n String[] midterms;\n String[] finals;\n}\n public Student(String name) {\n this.name = name;\n this.quizzes = new String[2];\n this.midterms = new String[2];\n this.finals = new String[1];\n} \n Student newStudent = new Student(\"put the name here\");\n newStudent.midterms[0] = \"midterm 1 grade\";\n" }, { "answer_id": 74671299, "author": "Newbe", "author_id": 20671289, "author_profile": "https://Stackoverflow.com/users/20671289", "pm_score": -1, "selected": false, "text": "public class Student {\nString name;\nString[] quizzes;\nString[] midterms;\nString[] finals;\n}\n\n\npublic Student(String name) {\nthis.name = name;\nthis.quizzes = new String[2];\nthis.midterms = new String[2];\nthis.finals = new String[1];\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1131467/" ]
74,663,485
<p>I have a checkout cart where you have different cart items, and for each one you can change the quantity prior to purchase.</p> <p>Here's how the code looks:</p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import PureInput from &quot;./PureInput&quot;; import { useForm, Controller } from &quot;react-hook-form&quot;; const CartInner = React.forwardRef( ( { control, element, value, handleOnChange, images, name, monthlyAmount, price, projectedGrowth, id, ...inputProps }: any, ref: any ) =&gt; { return ( &lt;div className=&quot;grid gap-8 grid-cols-2 mb-12 py-6 px-8 border-2 border-slate-200&quot;&gt; &lt;div&gt; &lt;PureInput min={200} max={price} onChange={handleOnChange} type=&quot;number&quot; step={200} defaultValue={element.price} id={id} ref={ref} {...inputProps} /&gt; &lt;/div&gt; &lt;/div&gt; ); } ); export default function Checkout() { const { control, handleSubmit } = useForm(); const handleOnChange = (index: any, e: any) =&gt; { console.log(e, &quot;e&quot;); }; const onSubmit = async (data: any) =&gt; { console.log(data, &quot;data from Form.tsx&quot;); }; return ( &lt;form onSubmit={handleSubmit(onSubmit)} className=&quot;grid gap-8 grid-cols-3&quot;&gt; &lt;div className=&quot;col-span-2&quot;&gt; {[0, 2].map((element, index) =&gt; { return ( &lt;fieldset key={index}&gt; &lt;Controller render={({ field }) =&gt; ( &lt;CartInner element={element} handleOnChange={(e) =&gt; handleOnChange(index, e)} {...field} /&gt; )} name={`test.${index}.lastName`} control={control} /&gt; &lt;/fieldset&gt; ); })} &lt;button&gt;Progess to payment&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; ); } </code></pre> <p>And the PureInput:</p> <pre><code>import * as React from &quot;react&quot;; type IProps = any; const PureInput = React.forwardRef( ({ className, id, onChange, ...inputProps }: IProps, ref: any) =&gt; { return ( &lt;input id={id} ref={ref} onChange={onChange} type=&quot;input&quot; className={`${className} block w-full bg-white text-black rounded-md border-2 font-bold border-grey-200 text-xl px-4 py-4 focus:border-orange-500 focus:ring-orange-500`} {...inputProps} /&gt; ); } ); export default PureInput; </code></pre> <p>Everything works fine in terms of submitting the form. When I do, I get an array of whatever values I have entered into the input:</p> <pre><code>[{lastName: &quot;1600&quot;} {lastName: &quot;800&quot;}] </code></pre> <p>My package versions:</p> <pre><code>&quot;react-dom&quot;: &quot;18.2.0&quot;, &quot;react-hook-form&quot;: &quot;^7.29.0&quot;, </code></pre> <p>But my onChange no longer fires. How can I get the onChange to fire so I can log the value of the input inside <code>&lt;Checkout /&gt;</code> component?</p> <p>Here's a <a href="https://codesandbox.io/s/realestateinvestmentcalculator-styling-y4jm9b?file=/src/PureInput.tsx:0-538" rel="nofollow noreferrer">codesandbox</a> if it helps</p>
[ { "answer_id": 74663770, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 1, "selected": false, "text": "onChange handleSubmit react-hook-form Checkout import React, { useEffect, useState } from \"react\";\nimport { useForm } from \"react-hook-form\";\n\nconst CartInner = React.forwardRef(\n (\n {\n control,\n element,\n value,\n handleOnChange,\n images,\n name,\n monthlyAmount,\n price,\n projectedGrowth,\n id,\n ...inputProps\n }: any,\n ref: any\n ) => {\n return (\n <div className=\"grid gap-8 grid-cols-2 mb-12 py-6 px-8 border-2 border-slate-200\">\n <div>\n <PureInput\n min={200}\n max={price}\n onChange={handleOnChange}\n type=\"number\"\n step={200}\n defaultValue={element.price}\n id={id}\n ref={ref}\n {...inputProps}\n />\n </div>\n </div>\n );\n }\n);\n\nexport default function Checkout() {\n const { control, handleSubmit } = useForm();\n\n const handleOnChange = (index: any, e: any) => {\n console.log(e, \"e\");\n };\n\n const onSubmit = async (data: any) => {\n console.log(data, \"data from Form.tsx\");\n };\n\n return (\n <form onSubmit={handleSubmit(onSubmit)} className=\"grid gap-8 grid-cols-3\">\n <div className=\"col-span-2\">\n {[0, 2].map((element, index) => {\n return (\n <fieldset key={index}>\n <Controller\n render={({ field }) => (\n <CartInner\n element={element}\n handleOnChange={(e) => handleOnChange(index, e)}\n {...field}\n />\n )}\n name={`test.${index}.lastName`}\n control={control}\n />\n </fieldset>\n );\n })}\n <button>Progess to payment</button>\n </div>\n </form>\n );\n}\n" }, { "answer_id": 74664088, "author": "a7dc", "author_id": 7317408, "author_profile": "https://Stackoverflow.com/users/7317408", "pm_score": 0, "selected": false, "text": "import React, { useEffect, useState } from \"react\";\n\nimport PureInput from \"./PureInput\";\nimport { useForm, Controller } from \"react-hook-form\";\n\nconst CartInner = React.forwardRef(\n ({ onChange, onBlur, name, label, ...inputProps }: any, ref: any) => {\n return (\n <input\n name={name}\n ref={ref}\n onChange={onChange}\n onBlur={onBlur}\n type=\"number\"\n />\n );\n }\n);\n\nexport default function Checkout() {\n const { control, handleSubmit } = useForm();\n\n const handleOnChange = (index: any, e: any) => {\n console.log(e.target.value, \"e\");\n };\n\n const onSubmit = async (data: any) => {\n console.log(data, \"data from Form.tsx\");\n };\n\n return (\n <form onSubmit={handleSubmit(onSubmit)} className=\"grid gap-8 grid-cols-3\">\n <div className=\"col-span-2\">\n {[0, 2].map((element, index) => {\n return (\n <fieldset key={index}>\n <Controller\n render={({ field: { onBlur, value, name, ref } }) => (\n <CartInner\n key={index}\n name={name}\n ref={ref}\n onChange={(e) => handleOnChange(index, e)}\n onBlur={onBlur}\n />\n )}\n name={`test.${index}.lastName`}\n control={control}\n />\n </fieldset>\n );\n })}\n <button>Progess to payment</button>\n </div>\n </form>\n );\n}\n\n// add delete\n// total money\n// add the cart documents to a history with a timestamp and show it was a BUY ORDER\n// delete the documents from the cart\n" }, { "answer_id": 74664520, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 2, "selected": true, "text": " // pass an event handler name with different name \n <PureInput\n min={200}\n max={price}\n // pass a handler with different name as inputOptions overrides that prop\n handleOnChange={handleOnChange}\n type=\"number\"\n step={200}\n defaultValue={element.price}\n id={id}\n ref={ref}\n {...inputProps}\n />\n\n//plug into the default onchange to call you handler also\n <input\n id={id}\n ref={ref}\n onChange={(e) => {\n console.log(\"on change\");\n // call react-hook-form onChange\n onChange(e);\n // call your handler\n handleOnChange(e);\n }}\n type=\"input\"\n className={`${className} block w-full bg-white text-black rounded-md border-2 font-bold border-grey-200 text-xl px-4 py-4 focus:border-orange-500 focus:ring-orange-500`}\n {...inputProps}\n />\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7317408/" ]
74,663,489
<p>i created a file with the colors that i want to use in my project, but when i try to used, flutter does not acept the variables as a correct color.</p> <p>This is the colors file:</p> <pre><code>import 'package:flutter/material.dart'; class ColorSkh { static Color innovation = const Color.fromARGB(255, 59, 18, 45); static Color fresh = const Color.fromARGB(255, 172, 155, 163); static Color hightech = const Color.fromARGB(255, 0, 128, 157); static Color sophisticated = const Color.fromARGB(255, 230, 231, 232); static Color sk = const Color.fromARGB(255, 191, 205, 217); static Color white = const Color.fromARGB(255, 255, 255, 255); } </code></pre> <p>And this is how i am using it</p> <pre><code> import 'package:analytic_skh/ui/color_skh.dart'; . . . SizedBox( *height: height * 0.10, child: Align( alignment: Alignment.centerLeft, child: ElevatedButton.icon( onPressed: onPressed, icon: const Icon(Icons.settings), label: const Text('Settings', style: TextStyle(backgroundColor: ColorSkh.innovation)), style: ElevatedButton.styleFrom( backgroundColor: Colors.white, ), )), )* </code></pre> <p>but i get the error that this is a invalid constant</p>
[ { "answer_id": 74663527, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "Text static final SizedBox(\n *height: height * 0.10,\n child: Align(\n alignment: Alignment.centerLeft,\n child: ElevatedButton.icon(\n onPressed: onPressed,\n icon: const Icon(Icons.settings),\n label: Text('Settings',\n style:\n TextStyle(backgroundColor: ColorSkh.innovation)),\n style: ElevatedButton.styleFrom(\n backgroundColor: Colors.white,\n ),\n )),\n )*\n" }, { "answer_id": 74663555, "author": "MaNDOOoo", "author_id": 14434806, "author_profile": "https://Stackoverflow.com/users/14434806", "pm_score": 2, "selected": true, "text": "const class ColorSkh {\n static const Color innovation = Color.fromARGB(255, 59, 18, 45);\n static const Color fresh = Color.fromARGB(255, 172, 155, 163);\n static const Color hightech = Color.fromARGB(255, 0, 128, 157);\n static const Color sophisticated = Color.fromARGB(255, 230, 231, 232);\n static const Color sk = Color.fromARGB(255, 191, 205, 217);\n static const Color white = Color.fromARGB(255, 255, 255, 255);\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19906590/" ]
74,663,497
<p>I want to change the color of recyclervView item that I clicked(so user can understand that already checked the detail of the item) and go detail fragment page. However this background color change must be permanent should I store it in livedata of recycler view items. I share my codes at the end I am new to android programming so please explain your solution for beginner and my english level is not good. Thanks for everything.</p> <pre><code>class AdapterRecycler() : RecyclerView.Adapter&lt;AdapterRecycler.ViewHolder&gt;() class ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) { val name: TextView = view.findViewById(R.id.gameId) val score: TextView = view.findViewById(R.id.scoreId) val genre: TextView = view.findViewById(R.id.genres) val layout1: RelativeLayout = view.findViewById(R.id.rowlayout) init { // Define click listener for the ViewHolder's View. //val textView : TextView = view.findViewById(R.id.gameId) itemView.setOnClickListener { layout1.setBackgroundColor(Color.rgb(224,224,224)) listener.onItemClick(adapterPosition) } } } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { // Create a new view, which defines the UI of the list item val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.text_row_item, viewGroup, false) return ViewHolder(view, listenerItems) } </code></pre> <pre><code>class Games : Fragment() { ... override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ... adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener { override fun onItemClick(position: Int) { // Fragment transaction to detail page requireActivity().supportFragmentManager.beginTransaction() .replace(R.id.fragmentContainerView2, Details()).commit() } }) } </code></pre> <p>Should I store a boolean value in here to save item checked status?</p> <pre><code> data class Game(val name : String, val score : Int, val genres : Array&lt;String&gt;) </code></pre> <p>I tried solution at my codes and I get transaction but not the color changes of item layout.</p>
[ { "answer_id": 74663527, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "Text static final SizedBox(\n *height: height * 0.10,\n child: Align(\n alignment: Alignment.centerLeft,\n child: ElevatedButton.icon(\n onPressed: onPressed,\n icon: const Icon(Icons.settings),\n label: Text('Settings',\n style:\n TextStyle(backgroundColor: ColorSkh.innovation)),\n style: ElevatedButton.styleFrom(\n backgroundColor: Colors.white,\n ),\n )),\n )*\n" }, { "answer_id": 74663555, "author": "MaNDOOoo", "author_id": 14434806, "author_profile": "https://Stackoverflow.com/users/14434806", "pm_score": 2, "selected": true, "text": "const class ColorSkh {\n static const Color innovation = Color.fromARGB(255, 59, 18, 45);\n static const Color fresh = Color.fromARGB(255, 172, 155, 163);\n static const Color hightech = Color.fromARGB(255, 0, 128, 157);\n static const Color sophisticated = Color.fromARGB(255, 230, 231, 232);\n static const Color sk = Color.fromARGB(255, 191, 205, 217);\n static const Color white = Color.fromARGB(255, 255, 255, 255);\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671278/" ]
74,663,502
<p>I need my C program to run in the background, so without any open window or without blocking the terminal if run from there.</p> <p>I can't find much info on how to do it online.</p> <p>edit: To do what i needed, i just added -mwindows to the gcc command.</p>
[ { "answer_id": 74663659, "author": "Anders", "author_id": 3501, "author_profile": "https://Stackoverflow.com/users/3501", "pm_score": 0, "selected": false, "text": "WinMain main" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19400931/" ]
74,663,514
<p>I have a form that I created to make my work easier and recently figured out how to make certain fields automatically generate a comma and separates after 5 letters or numbers have been typed into it (CPT codes for medical claims that I have to look up) using the same coding you would for putting spaces between numbers. I also have coding here that would force letters to be capitalized since I'm a bit OCD about that stuff for work:</p> <pre><code>&lt;input name=&quot;checkbox24&quot; type=&quot;checkbox&quot; id=&quot;checkbox24&quot; onClick=&quot;FillDetails24(this.form);&quot; /&gt;&lt;span style=&quot;background-color:yellow&quot;&gt;CPT&lt;/span&gt; &lt;input type = &quot;text&quot; size=&quot;8&quot; class = &quot;uc-text-smooth&quot; name=&quot;textfield24&quot; id=&quot;textfield24&quot; /&gt; &lt;script language = &quot;JavaScript&quot;&gt; const forceKeyPressUppercase = (e) =&gt; { let el = e.target; let charInput = e.keyCode; if((charInput &gt;=97) &amp;&amp; (charInput &lt;= 122)) { // lowercase if(!e.ctrlKey &amp;&amp; !e.metaKey &amp;&amp; !e.altKey) { // no modifier key let newChar = charInput - 32; let start = el.selectionStart; let end = el.selectionEnd; el.value = el.value.substring(0, start) + String.fromCharCode(newChar) + el.value.substring(end); el.setSelectionRange(start+1, start+1); e.preventDefault(); } } }; document.querySelectorAll(&quot;.uc-text-smooth&quot;).forEach(function(current) { current.addEventListener(&quot;keypress&quot;, forceKeyPressUppercase); }); document.getElementById('textfield24').addEventListener('input', function (g) { g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim(); }); &lt;/script&gt; </code></pre> <p>When I use the checkbox, it automatically generates pre-written text using the following JavaScript:</p> <pre><code>function FillDetails24(f) { const elem = f.Reason; const x = f.Action; const y = f.Resolution; f.Reason.value += (&quot;Verify CPT &quot; + f.textfield24.value + &quot;. &quot; + '\n'); f.Action.value += (&quot;Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. &quot; + '\n'); f.Resolution.value += (&quot;Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT &quot; + f.textfield24.value + &quot;. &quot; + '\n' + '\n' ); } </code></pre> <p>However, because of the way that I put it together, the end result would be, &quot;Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. &quot; The extra comma at the end is driving me nuts.</p> <p>Since it was my first time using this</p> <pre><code> document.getElementById('textfield24').addEventListener('input', function (g) { g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim(); }); </code></pre> <p>with this</p> <pre><code>function FillDetails24(f) { const elem = f.Reason; const x = f.Action; const y = f.Resolution; f.Reason.value += (&quot;Verify CPT &quot; + f.textfield24.value + &quot;. &quot; + '\n'); f.Action.value += (&quot;Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. &quot; + '\n'); f.Resolution.value += (&quot;Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT &quot; + f.textfield24.value + &quot;. &quot; + '\n' + '\n' ); } </code></pre> <p>I'm not certain how I can code it to eliminate the last comma generated at the end when it pulls the value of textfield24.</p> <p>This is a very long, complex html form I've coded by hand for fun and for personal use at work for 4 years with only a couple years of HTML training and a little bit of JavaScript I learned in high school forever ago and I've been busting my butt to make this work perfectly so that I only have to tweak the pre-written stuff when things change at work.</p> <p>I'm at a loss on how to continue. Any suggestions?</p>
[ { "answer_id": 74663659, "author": "Anders", "author_id": 3501, "author_profile": "https://Stackoverflow.com/users/3501", "pm_score": 0, "selected": false, "text": "WinMain main" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671218/" ]
74,663,556
<p>I'm trying to avoid the extremely verbose hash maps and arrays, as commonly used in powershell. Why? Because I have 100's of lines, and it just doesn't make any sense to have to wrap every single line in a <code>@(name='foo; id='bar')</code> etc.), when all I need is a CSV type of array.</p> <pre><code>$header = @('name', 'id', 'type', 'loc') $mycsv = @( # name, id, type, loc 'Brave', 'Brave.Brave', 1, 'winget' 'Adobe Acrobat (64-bit)', '{AC76BA86-1033-1033-7760-BC15014EA700}', 2, '' 'GitHub CLI', 'GitHub.cli', 3, 'C:\portable' ) # Do some magic here to set the CSV / hash headers so I can use them as shown below Foreach ($app in $mycsv) { Write-Host &quot;App Name: $app.name&quot; Write-Host &quot;App Type: $app.type&quot; Write-Host &quot;App id : $app.id&quot; Write-Host &quot;App Loc : $app.type&quot; Write-Host (&quot;-&quot;*40) } </code></pre> <p>I'm sure you see where I am going.</p> <p><strong>So how can I process the inline CSV line-by-line using the header names?</strong></p> <p>Expected output:</p> <pre><code>App Name: Brave App Type: 1 App id : Brave.Brave App Loc : winget ---------------------------------------- ... </code></pre> <hr /> <p><strong>UPDATE: <code>2022-12-03</code></strong></p> <p>The ultimate solution is the following very brief and non-verbose code:</p> <pre><code>$my = @' name,id,type,loc Brave, Brave.Brave,1,winget &quot;Adobe Acrobat (64-bit)&quot;,{AC76BA86-1033-1033-7760-BC15014EA700},2, GitHub CLI,GitHub.cli,,C:\portable '@ ConvertFrom-Csv $my | % { Write-Host &quot;App Name: $($_.name)&quot; Write-Host &quot;App Type: $($_.type)&quot; Write-Host &quot;App id : $($_.id)&quot; Write-Host &quot;App Loc : $($_.loc)&quot; Write-Host $(&quot;-&quot;*40) } </code></pre> <p> </p>
[ { "answer_id": 74663777, "author": "aHelpfulcoder", "author_id": 20670253, "author_profile": "https://Stackoverflow.com/users/20670253", "pm_score": 1, "selected": false, "text": "$header = @('name', 'id', 'type', 'loc')\n\n$mycsv = @(\n # name, id, type, loc\n 'Brave', 'Brave.Brave', 1, 'winget'\n 'Adobe Acrobat (64-bit)', '{AC76BA86-1033-1033-7760-BC15014EA700}', 2, ''\n 'GitHub CLI', 'GitHub.cli', 3, 'C:\\portable'\n)\n\n# Convert the CSV data into objects with properties\n$apps = $mycsv | ConvertFrom-Csv -Header $header\n\nForeach ($app in $apps) {\n Write-Host \"App Name: $($app.name)\"\n Write-Host \"App Type: $($app.type)\"\n Write-Host \"App id : $($app.id)\"\n Write-Host \"App Loc : $($app.loc)\"\n Write-Host (\"-\"*40)\n}\n $mycsv = @(\n # name, id, type, loc\n 'Brave', 'Brave.Brave', 1, 'winget'\n 'Adobe Acrobat (64-bit)', '{AC76BA86-1033-1033-7760-BC15014EA700}', 2, ''\n 'GitHub CLI', 'GitHub.cli', 3, 'C:\\portable'\n)\n\n# Convert the CSV data into objects with properties\n$apps = $mycsv | ConvertFrom-Csv -Property @('name', 'id', 'type', 'loc')\n" }, { "answer_id": 74663798, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 2, "selected": false, "text": "ConvertFrom-Csv # This creates objects ([pscustomobject] instances) with properties\n# named for the fields in the header line (the first line), i.e: \n# .name, .id. .type, and .loc\n# NOTE: \n# * The whitespace around the fields is purely for *readability*.\n# * If any field values contain \",\" themselves, enclose them in \"...\"\n$mycsv =\n@'\n name, id, type, loc\n Brave, Brave.Brave, 1, winget\n Adobe Acrobat (64-bit), {AC76BA86-1033-1033-7760-BC15014EA700}, 2,\n GitHub CLI, GitHub.cli, 3, C:\\portable\n'@ | ConvertFrom-Csv\n $mycsv | Format-List Format-List Format-Table Format-List Write-Host $_.name $(...) \"...\" , \"...\" , '...' ' \" \"\" , | ConvertFrom-Csv -Delimiter ConvertFrom-Csv Import-Csv [string ConvertFrom-CsvTyped ConvertFrom-Csv [int] ID [int] [long] [double] [decimal] [datetime] [datetimeoffset] [timespan] [bool] 0 1 [timespan] '01:00' [byte] 0x40 [int] [datetime] @'\n Name, [int] ID, [datetime] Timestamp\n Forty-two, 0x2a, 1970-01-01\n Forty-three, 0x2b, 1970-01-02\n'@ | ConvertFrom-CsvTyped\n [datetime] Name ID Timestamp\n---- -- ---------\nForty-two 42 1/1/1970 12:00:00 AM\nForty-three 43 1/2/1970 12:00:00 AM\n -AsSourceCode [pscustomobject] @'\n Name, [int] ID, [datetime] Timestamp\n Forty-two, 0x2a, 1970-01-01\n Forty-three, 0x2b, 1970-01-02\n'@ | ConvertFrom-CsvTyped -AsSourceCode\n Invoke-Expression @(\n [pscustomobject] @{ Name = 'Forty-two'; ID = [int] 0x2a; Timestamp = [datetime] '1970-01-01' }\n [pscustomobject] @{ Name = 'Forty-three'; ID = [int] 0x2b; Timestamp = [datetime] '1970-01-02' }\n)\n ConvertFrom-CsvTyped function ConvertFrom-CsvTyped {\n <#\n.SYNOPSIS\n Converts CSV data to objects with typed properties;\n.DESCRIPTION\n This command enhances ConvertFrom-Csv as follows:\n * Header fields (column names) may be preceded by type literals in order\n to specify a type for the properties of the resulting objects, e.g. \"[int] Id\"\n * With -AsSourceCode, the data can be transformed to an array of \n [pscustomobject] literals.\n\n.PARAMETER Delimiter\n The single-character delimiter (separator) that separates the column values.\n \",\" is the (culture-invariant) default.\n\n.PARAMETER AsSourceCode\n Instead of outputting the parsed CSV data as objects, output them as\n as source-code representations in the form of an array of [pscustomobject] literals.\n\n.EXAMPLE\n \"Name, [int] ID, [datetime] Timestamp`nForty-two, 0x40, 1970-01-01Z\" | ConvertFrom-CsvTyped\n \n Parses the CSV input into an object with typed properties, resulting in the following for-display output:\n Name ID Timestamp\n ---- -- ---------\n Forty-two 64 12/31/1969 7:00:00 PM \n\n .EXAMPLE\n \"Name, [int] ID, [datetime] Timestamp`nForty-two, 0x40, 1970-01-01Z\" | ConvertFrom-CsvTyped -AsSourceCode\n \n Transforms the CSV input into an equivalent source-code representation, expressed\n as an array of [pscustomobject] literals:\n @(\n [pscustomobject] @{ Name = 'Forty-two'; ID = [int] 0x40; Timestamp = [datetime] '1970-01-01Z' }\n )\n#>\n\n [CmdletBinding(PositionalBinding = $false)]\n param(\n [Parameter(Mandatory, ValueFromPipeline)]\n [string[]] $InputObject,\n [char] $Delimiter = ',',\n [switch] $AsSourceCode\n )\n begin {\n $allLines = ''\n }\n process {\n if (-not $allLines) {\n $allLines = $InputObject -join \"`n\"\n }\n else {\n $allLines += \"`n\" + ($InputObject -join \"`n\")\n }\n }\n end {\n\n $header, $dataLines = $allLines -split '\\r?\\n'\n\n # Parse the header line in order to derive the column (property) names.\n $colNames = ($header, $header | ConvertFrom-Csv -ErrorAction Stop -Delimiter $Delimiter)[0].psobject.Properties.Name\n [string[]] $colTypeNames = , 'string' * $colNames.Count\n [type[]] $colTypes = , $null * $colNames.Count\n $mustReType = $false; $mustRebuildHeader = $false\n\n if (-not $dataLines) { throw \"No data found after the header line; input must be valid CSV data.\" }\n\n foreach ($i in 0..($colNames.Count - 1)) {\n if ($colNames[$i] -match '^\\[([^]]+)\\]\\s*(.*)$') {\n if ('' -eq $Matches[2]) { throw \"Missing column name after type specifier '[$($Matches[1])]'\" }\n if ($Matches[1] -notin 'string', 'System.String') {\n $mustReType = $true\n $colTypeNames[$i] = $Matches[1]\n try {\n $colTypes[$i] = [type] $Matches[1]\n }\n catch { throw }\n }\n $mustRebuildHeader = $true\n $colNames[$i] = $Matches[2]\n }\n }\n if ($mustRebuildHeader) {\n $header = $(foreach ($colName in $colNames) { if ($colName -match [regex]::Escape($Delimiter)) { '\"{0}\"' -f $colName.Replace('\"', '\"\"') } else { $colName } }) -join $Delimiter\n }\n\n if ($AsSourceCode) {\n # Note: To make the output suitable for direct piping to Invoke-Expression (which is helpful for testing),\n # a *single* string mut be output.\n (& {\n \"@(\"\n & { $header; $dataLines } | ConvertFrom-Csv -Delimiter $Delimiter | ForEach-Object {\n @\"\n [pscustomobject] @{ $(\n $(foreach ($i in 0..($colNames.Count-1)) {\n if (($propName = $colNames[$i]) -match '\\W') {\n $propName = \"'{0}'\" -f $propName.Replace(\"'\", \"''\")\n }\n $isString = $colTypes[$i] -in $null, [string]\n $cast = if (-not $isString) { '[{0}] ' -f $colTypeNames[$i] }\n $value = $_.($colNames[$i])\n if ($colTypes[$i] -in [bool] -and ($value -as [int]) -notin 0, 1) { Write-Warning \"'$value' is interpreted as `$true - use 0 or 1 to represent [bool] values.\" }\n if ($isString -or $null -eq ($value -as [double])) { $value = \"'{0}'\" -f $(if ($null -ne $value) { $value.Replace(\"'\", \"''\") }) }\n '{0} = {1}{2}' -f $colNames[$i], $cast, $value\n }) -join '; ') }\n\"@\n }\n \")\"\n }) -join \"`n\"\n }\n else {\n if (-not $mustReType) {\n # No type-casting needed - just pass the data through to ConvertFrom-Csv\n & { $header; $dataLines } | ConvertFrom-Csv -ErrorAction Stop -Delimiter $Delimiter\n }\n else {\n # Construct a class with typed properties matching the CSV input dynamically\n $i = 0\n @\"\nclass __ConvertFromCsvTypedHelper {\n$(\n $(foreach ($i in 0..($colNames.Count-1)) {\n ' [{0}] ${{{1}}}' -f $colTypeNames[$i], $colNames[$i]\n }) -join \"`n\"\n)\n}\n\"@ | Invoke-Expression\n\n # Pass the data through to ConvertFrom-Csv and cast the results to the helper type.\n try {\n [__ConvertFromCsvTypedHelper[]] (& { $header; $dataLines } | ConvertFrom-Csv -ErrorAction Stop -Delimiter $Delimiter)\n }\n catch { $_ }\n }\n }\n }\n}\n" }, { "answer_id": 74666639, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": true, "text": "$mycsv = @\"\nname, id, type, loc\n\"Brave\", \"Brave.Brave\", 1, \"winget\"\n\"Adobe Acrobat (64-bit)\", \"{AC76BA86-1033-1033-7760-BC15014EA700}\", 2,\n\"GitHub CLI\", \"GitHub.cli\", 3, \"C:\\portable\"\n\"@\n\nConvertFrom-CSV $mycsv | Format-List\n\nConvertFrom-Csv $mycsv | % {@\"\nApp Name: $($_.name)\nApp Type: $($_.type)\nApp id : $($_.id)\nApp Loc : $($_.loc)\n$(\"-\"*40)\n\"@\n}\n\nConvertFrom-CSV $mycsv | gm\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147688/" ]
74,663,566
<p>I’m a beginner in the field of Graph Matching and Parallel Computing. I read <a href="https://arxiv.org/abs/1302.4587" rel="nofollow noreferrer">a paper</a> that talks about an efficient parallel matching algorithm. They explained the importance of the locality, but I don't know it represents what? and What is good and bad locality?</p> <blockquote> <p>Our distributed memory parallelization (using MPI) on p processing elements (PEs or MPI processes) assigns nodes to PEs and stores all edges incident to a node locally. This can be done in a load balanced way if no node has degree exceeding m/p. The second pass of the basic algorithm from Section 2 has to exchange information on candidate edges that cross a PE boundary. In the worst case, this can involve all edges handled by a PE, i.e., we can expect better performance if we manage to keep most edges locally. In our experiments, one PE owns nodes whose numbers are a consecutive range of the input numbers. <strong>Thus, depending on how much locality the input numbering contains we have a highly local or a highly non-local situation.</strong></p> </blockquote>
[ { "answer_id": 74663777, "author": "aHelpfulcoder", "author_id": 20670253, "author_profile": "https://Stackoverflow.com/users/20670253", "pm_score": 1, "selected": false, "text": "$header = @('name', 'id', 'type', 'loc')\n\n$mycsv = @(\n # name, id, type, loc\n 'Brave', 'Brave.Brave', 1, 'winget'\n 'Adobe Acrobat (64-bit)', '{AC76BA86-1033-1033-7760-BC15014EA700}', 2, ''\n 'GitHub CLI', 'GitHub.cli', 3, 'C:\\portable'\n)\n\n# Convert the CSV data into objects with properties\n$apps = $mycsv | ConvertFrom-Csv -Header $header\n\nForeach ($app in $apps) {\n Write-Host \"App Name: $($app.name)\"\n Write-Host \"App Type: $($app.type)\"\n Write-Host \"App id : $($app.id)\"\n Write-Host \"App Loc : $($app.loc)\"\n Write-Host (\"-\"*40)\n}\n $mycsv = @(\n # name, id, type, loc\n 'Brave', 'Brave.Brave', 1, 'winget'\n 'Adobe Acrobat (64-bit)', '{AC76BA86-1033-1033-7760-BC15014EA700}', 2, ''\n 'GitHub CLI', 'GitHub.cli', 3, 'C:\\portable'\n)\n\n# Convert the CSV data into objects with properties\n$apps = $mycsv | ConvertFrom-Csv -Property @('name', 'id', 'type', 'loc')\n" }, { "answer_id": 74663798, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 2, "selected": false, "text": "ConvertFrom-Csv # This creates objects ([pscustomobject] instances) with properties\n# named for the fields in the header line (the first line), i.e: \n# .name, .id. .type, and .loc\n# NOTE: \n# * The whitespace around the fields is purely for *readability*.\n# * If any field values contain \",\" themselves, enclose them in \"...\"\n$mycsv =\n@'\n name, id, type, loc\n Brave, Brave.Brave, 1, winget\n Adobe Acrobat (64-bit), {AC76BA86-1033-1033-7760-BC15014EA700}, 2,\n GitHub CLI, GitHub.cli, 3, C:\\portable\n'@ | ConvertFrom-Csv\n $mycsv | Format-List Format-List Format-Table Format-List Write-Host $_.name $(...) \"...\" , \"...\" , '...' ' \" \"\" , | ConvertFrom-Csv -Delimiter ConvertFrom-Csv Import-Csv [string ConvertFrom-CsvTyped ConvertFrom-Csv [int] ID [int] [long] [double] [decimal] [datetime] [datetimeoffset] [timespan] [bool] 0 1 [timespan] '01:00' [byte] 0x40 [int] [datetime] @'\n Name, [int] ID, [datetime] Timestamp\n Forty-two, 0x2a, 1970-01-01\n Forty-three, 0x2b, 1970-01-02\n'@ | ConvertFrom-CsvTyped\n [datetime] Name ID Timestamp\n---- -- ---------\nForty-two 42 1/1/1970 12:00:00 AM\nForty-three 43 1/2/1970 12:00:00 AM\n -AsSourceCode [pscustomobject] @'\n Name, [int] ID, [datetime] Timestamp\n Forty-two, 0x2a, 1970-01-01\n Forty-three, 0x2b, 1970-01-02\n'@ | ConvertFrom-CsvTyped -AsSourceCode\n Invoke-Expression @(\n [pscustomobject] @{ Name = 'Forty-two'; ID = [int] 0x2a; Timestamp = [datetime] '1970-01-01' }\n [pscustomobject] @{ Name = 'Forty-three'; ID = [int] 0x2b; Timestamp = [datetime] '1970-01-02' }\n)\n ConvertFrom-CsvTyped function ConvertFrom-CsvTyped {\n <#\n.SYNOPSIS\n Converts CSV data to objects with typed properties;\n.DESCRIPTION\n This command enhances ConvertFrom-Csv as follows:\n * Header fields (column names) may be preceded by type literals in order\n to specify a type for the properties of the resulting objects, e.g. \"[int] Id\"\n * With -AsSourceCode, the data can be transformed to an array of \n [pscustomobject] literals.\n\n.PARAMETER Delimiter\n The single-character delimiter (separator) that separates the column values.\n \",\" is the (culture-invariant) default.\n\n.PARAMETER AsSourceCode\n Instead of outputting the parsed CSV data as objects, output them as\n as source-code representations in the form of an array of [pscustomobject] literals.\n\n.EXAMPLE\n \"Name, [int] ID, [datetime] Timestamp`nForty-two, 0x40, 1970-01-01Z\" | ConvertFrom-CsvTyped\n \n Parses the CSV input into an object with typed properties, resulting in the following for-display output:\n Name ID Timestamp\n ---- -- ---------\n Forty-two 64 12/31/1969 7:00:00 PM \n\n .EXAMPLE\n \"Name, [int] ID, [datetime] Timestamp`nForty-two, 0x40, 1970-01-01Z\" | ConvertFrom-CsvTyped -AsSourceCode\n \n Transforms the CSV input into an equivalent source-code representation, expressed\n as an array of [pscustomobject] literals:\n @(\n [pscustomobject] @{ Name = 'Forty-two'; ID = [int] 0x40; Timestamp = [datetime] '1970-01-01Z' }\n )\n#>\n\n [CmdletBinding(PositionalBinding = $false)]\n param(\n [Parameter(Mandatory, ValueFromPipeline)]\n [string[]] $InputObject,\n [char] $Delimiter = ',',\n [switch] $AsSourceCode\n )\n begin {\n $allLines = ''\n }\n process {\n if (-not $allLines) {\n $allLines = $InputObject -join \"`n\"\n }\n else {\n $allLines += \"`n\" + ($InputObject -join \"`n\")\n }\n }\n end {\n\n $header, $dataLines = $allLines -split '\\r?\\n'\n\n # Parse the header line in order to derive the column (property) names.\n $colNames = ($header, $header | ConvertFrom-Csv -ErrorAction Stop -Delimiter $Delimiter)[0].psobject.Properties.Name\n [string[]] $colTypeNames = , 'string' * $colNames.Count\n [type[]] $colTypes = , $null * $colNames.Count\n $mustReType = $false; $mustRebuildHeader = $false\n\n if (-not $dataLines) { throw \"No data found after the header line; input must be valid CSV data.\" }\n\n foreach ($i in 0..($colNames.Count - 1)) {\n if ($colNames[$i] -match '^\\[([^]]+)\\]\\s*(.*)$') {\n if ('' -eq $Matches[2]) { throw \"Missing column name after type specifier '[$($Matches[1])]'\" }\n if ($Matches[1] -notin 'string', 'System.String') {\n $mustReType = $true\n $colTypeNames[$i] = $Matches[1]\n try {\n $colTypes[$i] = [type] $Matches[1]\n }\n catch { throw }\n }\n $mustRebuildHeader = $true\n $colNames[$i] = $Matches[2]\n }\n }\n if ($mustRebuildHeader) {\n $header = $(foreach ($colName in $colNames) { if ($colName -match [regex]::Escape($Delimiter)) { '\"{0}\"' -f $colName.Replace('\"', '\"\"') } else { $colName } }) -join $Delimiter\n }\n\n if ($AsSourceCode) {\n # Note: To make the output suitable for direct piping to Invoke-Expression (which is helpful for testing),\n # a *single* string mut be output.\n (& {\n \"@(\"\n & { $header; $dataLines } | ConvertFrom-Csv -Delimiter $Delimiter | ForEach-Object {\n @\"\n [pscustomobject] @{ $(\n $(foreach ($i in 0..($colNames.Count-1)) {\n if (($propName = $colNames[$i]) -match '\\W') {\n $propName = \"'{0}'\" -f $propName.Replace(\"'\", \"''\")\n }\n $isString = $colTypes[$i] -in $null, [string]\n $cast = if (-not $isString) { '[{0}] ' -f $colTypeNames[$i] }\n $value = $_.($colNames[$i])\n if ($colTypes[$i] -in [bool] -and ($value -as [int]) -notin 0, 1) { Write-Warning \"'$value' is interpreted as `$true - use 0 or 1 to represent [bool] values.\" }\n if ($isString -or $null -eq ($value -as [double])) { $value = \"'{0}'\" -f $(if ($null -ne $value) { $value.Replace(\"'\", \"''\") }) }\n '{0} = {1}{2}' -f $colNames[$i], $cast, $value\n }) -join '; ') }\n\"@\n }\n \")\"\n }) -join \"`n\"\n }\n else {\n if (-not $mustReType) {\n # No type-casting needed - just pass the data through to ConvertFrom-Csv\n & { $header; $dataLines } | ConvertFrom-Csv -ErrorAction Stop -Delimiter $Delimiter\n }\n else {\n # Construct a class with typed properties matching the CSV input dynamically\n $i = 0\n @\"\nclass __ConvertFromCsvTypedHelper {\n$(\n $(foreach ($i in 0..($colNames.Count-1)) {\n ' [{0}] ${{{1}}}' -f $colTypeNames[$i], $colNames[$i]\n }) -join \"`n\"\n)\n}\n\"@ | Invoke-Expression\n\n # Pass the data through to ConvertFrom-Csv and cast the results to the helper type.\n try {\n [__ConvertFromCsvTypedHelper[]] (& { $header; $dataLines } | ConvertFrom-Csv -ErrorAction Stop -Delimiter $Delimiter)\n }\n catch { $_ }\n }\n }\n }\n}\n" }, { "answer_id": 74666639, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 2, "selected": true, "text": "$mycsv = @\"\nname, id, type, loc\n\"Brave\", \"Brave.Brave\", 1, \"winget\"\n\"Adobe Acrobat (64-bit)\", \"{AC76BA86-1033-1033-7760-BC15014EA700}\", 2,\n\"GitHub CLI\", \"GitHub.cli\", 3, \"C:\\portable\"\n\"@\n\nConvertFrom-CSV $mycsv | Format-List\n\nConvertFrom-Csv $mycsv | % {@\"\nApp Name: $($_.name)\nApp Type: $($_.type)\nApp id : $($_.id)\nApp Loc : $($_.loc)\n$(\"-\"*40)\n\"@\n}\n\nConvertFrom-CSV $mycsv | gm\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20235419/" ]
74,663,573
<p>I am trying to make an program which will add two number and i am a beginner i got my stored in a variable but cannot convert it to number</p> <pre><code>var num1 = Number.parseInt(num0) </code></pre> <p>i tried using parse int but i still dont get the correct input</p> <p>heres my full code</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;input type=&quot;text&quot; id=&quot;text&quot; placeholder=&quot;Number 1&quot;&gt;&lt;/input&gt; &lt;input type=&quot;text&quot; id=&quot;text2&quot; placeholder=&quot;Number 2&quot;&gt;&lt;/input&gt; &lt;button type=&quot;submit&quot; id=&quot;submit&quot; onclick=&quot;put()&quot;&gt;Click Me&lt;/button&gt; &lt;p id=&quot;myp&quot;&gt;&lt;/p&gt; &lt;script&gt; function put() { var num0 = document.getElementById(&quot;text&quot;) var num1 = Number.parseInt(num0) var num4 = document.getElementById(&quot;text2&quot;) var num2 = Number.parseInt(num4) var sub = document.getElementById(&quot;submit&quot;) var res = num1 + num2 document.getElementById(&quot;myp&quot;).innerHTML = num1.value + num2.value } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="https://i.stack.imgur.com/bk0py.png" rel="nofollow noreferrer">enter image description here</a></p> <p>if i try num1.value its undefined and if only try num1 its considered as text</p>
[ { "answer_id": 74663592, "author": "Christian Fritz", "author_id": 1087119, "author_profile": "https://Stackoverflow.com/users/1087119", "pm_score": 1, "selected": false, "text": " function put() {\n var num0 = document.getElementById(\"text\")\n var num1 = Number(num0.value)\n var num4 = document.getElementById(\"text2\")\n var num2 = Number(num4.value)\n var sub = document.getElementById(\"submit\")\n var res = num1 + num2\n document.getElementById(\"myp\").innerHTML = num1 + num2\n }\n" }, { "answer_id": 74663596, "author": "lv_", "author_id": 14325417, "author_profile": "https://Stackoverflow.com/users/14325417", "pm_score": 1, "selected": false, "text": "function put() {\n var num0 = document.getElementById(\"text\").value\n var num1 = Number.parseInt(num0)\n var num4 = document.getElementById(\"text2\").value\n var num2 = Number.parseInt(num4)\n\n var res = num1 + num2\n document.getElementById(\"myp\").innerHTML = res\n}\n" }, { "answer_id": 74664328, "author": "s.kuznetsov", "author_id": 13573444, "author_profile": "https://Stackoverflow.com/users/13573444", "pm_score": 0, "selected": false, "text": "+ var num1 = +num0.value;\n...\nvar num2 = +num4.value;\n <input type=\"text\" id=\"text\" placeholder=\"Number 1\" />\n<input type=\"text\" id=\"text2\" placeholder=\"Number 2\" />\n<button type=\"submit\" id=\"submit\" onclick=\"put()\">Click Me</button>\n<p id=\"myp\"></p>\n\n<script>\n function put() {\n var num0 = document.getElementById(\"text\");\n var num1 = +num0.value;\n var num4 = document.getElementById(\"text2\");\n var num2 = +num4.value;\n var sub = document.getElementById(\"submit\");\n var res = num1 + num2;\n document.getElementById(\"myp\").innerHTML = res;\n }\n</script>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17969931/" ]
74,663,591
<p>I'm trying to remake Tic-Tac-Toe on python. But, it wont work.</p> <p>I tried `</p> <pre><code>game_board = ['_'] * 9 print(game_board[0]) + &quot; | &quot; + (game_board[1]) + ' | ' + (game_board[2]) print(game_board[3]) + ' | ' + (game_board[4]) + ' | ' + (game_board[5]) print(game_board[6]) + ' | ' + (game_board[7]) + ' | ' + (game_board[8]) </code></pre> <p>` but it returns</p> <p>`</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\username\PycharmProjects\pythonProject\tutorial.py&quot;, line 2, in &lt;module&gt; print(game_board[0]) + &quot; | &quot; + (game_board[1]) + ' | ' + (game_board[2]) ~~~~~~~~~~~~~~~~~~~~~^~~~~~~ TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' </code></pre> <p>`</p>
[ { "answer_id": 74663592, "author": "Christian Fritz", "author_id": 1087119, "author_profile": "https://Stackoverflow.com/users/1087119", "pm_score": 1, "selected": false, "text": " function put() {\n var num0 = document.getElementById(\"text\")\n var num1 = Number(num0.value)\n var num4 = document.getElementById(\"text2\")\n var num2 = Number(num4.value)\n var sub = document.getElementById(\"submit\")\n var res = num1 + num2\n document.getElementById(\"myp\").innerHTML = num1 + num2\n }\n" }, { "answer_id": 74663596, "author": "lv_", "author_id": 14325417, "author_profile": "https://Stackoverflow.com/users/14325417", "pm_score": 1, "selected": false, "text": "function put() {\n var num0 = document.getElementById(\"text\").value\n var num1 = Number.parseInt(num0)\n var num4 = document.getElementById(\"text2\").value\n var num2 = Number.parseInt(num4)\n\n var res = num1 + num2\n document.getElementById(\"myp\").innerHTML = res\n}\n" }, { "answer_id": 74664328, "author": "s.kuznetsov", "author_id": 13573444, "author_profile": "https://Stackoverflow.com/users/13573444", "pm_score": 0, "selected": false, "text": "+ var num1 = +num0.value;\n...\nvar num2 = +num4.value;\n <input type=\"text\" id=\"text\" placeholder=\"Number 1\" />\n<input type=\"text\" id=\"text2\" placeholder=\"Number 2\" />\n<button type=\"submit\" id=\"submit\" onclick=\"put()\">Click Me</button>\n<p id=\"myp\"></p>\n\n<script>\n function put() {\n var num0 = document.getElementById(\"text\");\n var num1 = +num0.value;\n var num4 = document.getElementById(\"text2\");\n var num2 = +num4.value;\n var sub = document.getElementById(\"submit\");\n var res = num1 + num2;\n document.getElementById(\"myp\").innerHTML = res;\n }\n</script>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671383/" ]
74,663,611
<p>LinkedHashMap has underlying double-linked list, which enables preservation of the insertion order during the iteration. Non-structural changes, i.e. replacement of the value of an already inserted key, does not affect iteration order. However, I am still wondering, <strong>whether remove(key) operation changes the iteration order in LinkedHashMap</strong>. As I have tested on really small examples, it does not affect the order of the elements, except for the missing element, which is not included during iteration, obviously - but anecdotes are not proofs. Supposedly, removal works as if in LinkedList (where the halves of the list split are at the index of the element are joined together) - on the other hand, the programmer maybe should take into account rehashing or reallocation.</p> <p>I am really confused and after reading the documentation of LinkedHashMap thoroughly, also still very doubtful, as I need a structure which preserves the order of insertion but enables an easy lookup and removal of the entries.</p>
[ { "answer_id": 74663627, "author": "Mehmet Masa", "author_id": 20671270, "author_profile": "https://Stackoverflow.com/users/20671270", "pm_score": 1, "selected": false, "text": "LinkedHashMap<String, Integer> map = new LinkedHashMap<>();\n\nmap.put(\"apple\", 1);\nmap.put(\"banana\", 2);\nmap.put(\"cherry\", 3);\n\n// Remove the \"banana\" element from the map\nmap.remove(\"banana\");\n\n// Iterate over the map and print the elements\nfor (Map.Entry<String, Integer> entry : map.entrySet()) {\n System.out.println(entry.getKey() + \": \" + entry.getValue());\n}\n apple: 1\ncherry: 3\n" }, { "answer_id": 74663755, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "k m m.put(k, v) m.containsKey(k) LinkedHashMap" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10600152/" ]
74,663,626
<p>I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I want to accumulate all the errorCounts so that if it hit 5 the program will terminate.</p> <p>for example: if the user answers question 1 incorrectly twice then the errorCount will be two. If the user answers question 2 incorrectly three times then the program will be terminated. However, the program is allowing the user to make 5 mistakes for every problem.</p> <pre><code># Level 5: print(&quot;You have the jewel in your possession, and defeated Joker at his own game&quot;) print(&quot;You now hold the precious jewel in your hands, but it's not over, you must leave the maze!&quot;) print(&quot;*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*&quot;) # put an error limit # space everything out to make it look more neat # Make sure you can fail the level **errorCount = 0** position = 0 while True: answer1 = input(&quot;Choose either Right, Left, Straight: &quot;) try: if answer1.lower() == &quot;right&quot;: print(&quot;You have chosen the correct path, now you proceed to the next step!&quot;) print() break * if errorCount == 5: print(&quot;you made too many mistakes and got captured, you have to restart&quot;)* elif answer1.lower() == &quot;left&quot;: print(&quot;You see a boulder blocking your path which forces you to go back.&quot;) errorCount = 1 + errorCount elif answer1.lower() == &quot;straight&quot;: print(&quot;On your way to the next stage you are exposed to a toxic gas that forces you to go back .&quot;) errorCount = 1 + errorCount else: print(&quot;Wrong input. Please try again..&quot;) errorCount = 1 + errorCount except Exception: print(&quot;Wrong input. Please try again..&quot;) # if errors &gt;= 5: while True: answer1 = input(&quot;Choose either Right, Left, Straight: &quot;) if errorCount == 5: print(&quot;you made too many mistakes and got captured, you have to restart&quot;) try: if answer1.lower() == &quot;straight&quot;: print(&quot;You have chosen the correct path, now you proceed to the next step!&quot;) break elif answer1.lower() == &quot;left&quot;: print(&quot;You chose the wrong path, go back&quot;) errorCount = 1 + errorCount elif answer1.lower() == &quot;right&quot;: print(&quot;You chose the wrong path, go back&quot;) errorCount = 1 + errorCount else: print(&quot;Wrong input. Please try again..&quot;) errorCount = 1 + errorCount except Exception: print(&quot;Wrong input. Please try again..&quot;) print(&quot;You are now on the third stage, you notice a screen that is asking you a riddle&quot;) while True: riddle1 = input(&quot;What gets wet when drying? &quot;) if errorCount == 5: print(&quot;you made too many mistakes and got captured, you have to restart&quot;) try: if riddle1.lower() == &quot;towel&quot;: print(&quot;You have chosen the correct answer&quot;) print(&quot;The giant stone blocking the entrance of the maze opens, and the outside lights shine through..&quot;) break else: print(&quot;Incorrect! Try again..&quot;) errorCount = 1 + errorCount print(&quot;Heres a hint: You use it after taking a shower...&quot;) except Exception: print(&quot;Incorrect! Try again..&quot;) errorCount = 1 + errorCount I do not know how to fix this issue </code></pre>
[ { "answer_id": 74663627, "author": "Mehmet Masa", "author_id": 20671270, "author_profile": "https://Stackoverflow.com/users/20671270", "pm_score": 1, "selected": false, "text": "LinkedHashMap<String, Integer> map = new LinkedHashMap<>();\n\nmap.put(\"apple\", 1);\nmap.put(\"banana\", 2);\nmap.put(\"cherry\", 3);\n\n// Remove the \"banana\" element from the map\nmap.remove(\"banana\");\n\n// Iterate over the map and print the elements\nfor (Map.Entry<String, Integer> entry : map.entrySet()) {\n System.out.println(entry.getKey() + \": \" + entry.getValue());\n}\n apple: 1\ncherry: 3\n" }, { "answer_id": 74663755, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "k m m.put(k, v) m.containsKey(k) LinkedHashMap" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671368/" ]
74,663,634
<p>Consider the following snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#parent { display: grid; grid-template-columns: repeat(2, 1fr); grid-template-rows: repeat(2, 1fr); width: 275px; border: 2px solid green; padding: 10px; } input { background-color: hotpink; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="parent"&gt; &lt;input /&gt; &lt;input /&gt; &lt;input /&gt; &lt;input /&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>If you run the snippet, you will find that the inputs overflow the parent div along the x-axis and refuses to fit inside the div (tested in Chromium-based Edge). Basically, when you give the parent with <code>display: grid</code> a fixed width, the input children don't seem to fit.</p> <p>I've tried all the properties I could think of, but none of them seemed to keep the inputs where they belong (I expect a nice 2x2 grid where the children fit evenly into the grid). How can I keep the inputs in the grid?</p>
[ { "answer_id": 74663627, "author": "Mehmet Masa", "author_id": 20671270, "author_profile": "https://Stackoverflow.com/users/20671270", "pm_score": 1, "selected": false, "text": "LinkedHashMap<String, Integer> map = new LinkedHashMap<>();\n\nmap.put(\"apple\", 1);\nmap.put(\"banana\", 2);\nmap.put(\"cherry\", 3);\n\n// Remove the \"banana\" element from the map\nmap.remove(\"banana\");\n\n// Iterate over the map and print the elements\nfor (Map.Entry<String, Integer> entry : map.entrySet()) {\n System.out.println(entry.getKey() + \": \" + entry.getValue());\n}\n apple: 1\ncherry: 3\n" }, { "answer_id": 74663755, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "k m m.put(k, v) m.containsKey(k) LinkedHashMap" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15359157/" ]
74,663,643
<p>I would like my array to from index to index like thisfor example: (0,0), (1,0), (2,0) etc. I've tried what seems like it should be the right way, but my loops stop after the first column and I get an index out of bounds exception.</p> <p>Here's what I did:</p> <pre><code>int[][] array2d = { {4,5, 3,8}, {8,3,99,6}, {5,7, 9,1} }; </code></pre> <pre><code>int currentRow = 0; for (int currentColumn = 0; currentColumn &lt; (array2d[currentRow].length); currentColumn++) { for(currentRow = 0; currentRow &lt; array2d.length; currentRow++) { System.out.println(array2d[currentRow][currentColumn]); } } </code></pre>
[ { "answer_id": 74663726, "author": "ProgrammingGeek11", "author_id": 14232884, "author_profile": "https://Stackoverflow.com/users/14232884", "pm_score": 0, "selected": false, "text": " int[][] array2d =\n {\n {1,2,3,4},\n {5,6,7,8},\n { 9,10,11,12}\n };\n int r=array2d.length,c=array2d[0].length;\n for (int i=0;i<c;i++)\n {\n for(int j=0;j<r;j++)\n {\n System.out.print(array2d[j][i]+\" \");\n }\n System.out.println();\n }\n" }, { "answer_id": 74663811, "author": "モキャデ", "author_id": 20607467, "author_profile": "https://Stackoverflow.com/users/20607467", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n int[][] array2d = {\n {4, 5, 3, 8},\n {},\n {8, 6},\n {2},\n {5, 7, 9, 1, 0}\n };\n int maxRow = array2d.length;\n int maxColumn = array2d[0].length;\n for (int r = 1; r < maxRow; ++r)\n maxColumn = Math.max(maxColumn, array2d[r].length);\n for (int c = 0; c < maxColumn; ++c) {\n for (int r = 0; r < maxRow; ++r)\n if (c < array2d[r].length)\n System.out.print(array2d[r][c] + \" \");\n else\n System.out.print(\"* \");\n System.out.println();\n }\n}\n 4 * 8 2 5 \n5 * 6 * 7 \n3 * * * 9 \n8 * * * 1 \n* * * * 0 \n public static void main(String[] args) {\n int[][] array2d = {\n {4, 5, 3, 8},\n {},\n {8, 6},\n {2},\n {5, 7, 9, 1, 0}\n };\n int rowSie = array2d.length;\n for (int c = 0; true; ++c) {\n StringBuilder sb = new StringBuilder();\n boolean out = false;\n for (int r = 0; r < rowSie; ++r)\n if (c < array2d[r].length) {\n sb.append(array2d[r][c]).append(\" \");\n out = true;\n } else\n sb.append(\"* \");\n if (!out)\n break;\n System.out.println(sb);\n }\n}\n 4 * 8 2 5 \n5 * 6 * 7 \n3 * * * 9 \n8 * * * 1 \n* * * * 0 \n" }, { "answer_id": 74663907, "author": "Old Dog Programmer", "author_id": 5103317, "author_profile": "https://Stackoverflow.com/users/5103317", "pm_score": 1, "selected": false, "text": "int i;\nfor (i = 0; i < 10; i++) { /* loop body */ }\n i < 10 false i 10 for (currentRow = 0; currentRow < array2d.length; currentRow++) \n currentRow array2d.length currentColumn < (array2d[currentRow].length) array2d[currentRow] IndexOutOfBoundsException for (int row = 0; row < array2d.length; row++) { \n for (int column = 0; column < array2d[row].length; column++ { \n // things to do in inner loop\n }\n for (int column = 0; column < array2d[0].length; column++) { \n for (int row = 0; row < array2d.length; row++) {\n // loop body\n }\n }\n int maxColumns = 0;\n for (int i = 0; i < array.length; i++) { \n maxColumns = Math.max (maxColumns, array2d[i].length);\n }\n for (int column = 0; column < maxColumns; column++) { \n for (int row = 0; row < array2d.length; row++) { \n if (column < array2d[row].length) {\n // do something with array2d [row][column]\n } else { \n // do something for the case where \n // array2d [row] doesn't have a value in \"column\" \n }\n }\n }\n ArrayIndexOutOfBoundsException" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671295/" ]
74,663,651
<p>I need to set margin on every page using dompdf like image below (page 2)</p> <p><a href="https://i.stack.imgur.com/wTmLi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wTmLi.jpg" alt="page 2" /></a></p> <p><a href="https://pastebin.pl/view/ea972d3f" rel="nofollow noreferrer">this my fully code</a></p> <p>Can anyone help for my problem ? Thanks</p>
[ { "answer_id": 74663726, "author": "ProgrammingGeek11", "author_id": 14232884, "author_profile": "https://Stackoverflow.com/users/14232884", "pm_score": 0, "selected": false, "text": " int[][] array2d =\n {\n {1,2,3,4},\n {5,6,7,8},\n { 9,10,11,12}\n };\n int r=array2d.length,c=array2d[0].length;\n for (int i=0;i<c;i++)\n {\n for(int j=0;j<r;j++)\n {\n System.out.print(array2d[j][i]+\" \");\n }\n System.out.println();\n }\n" }, { "answer_id": 74663811, "author": "モキャデ", "author_id": 20607467, "author_profile": "https://Stackoverflow.com/users/20607467", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n int[][] array2d = {\n {4, 5, 3, 8},\n {},\n {8, 6},\n {2},\n {5, 7, 9, 1, 0}\n };\n int maxRow = array2d.length;\n int maxColumn = array2d[0].length;\n for (int r = 1; r < maxRow; ++r)\n maxColumn = Math.max(maxColumn, array2d[r].length);\n for (int c = 0; c < maxColumn; ++c) {\n for (int r = 0; r < maxRow; ++r)\n if (c < array2d[r].length)\n System.out.print(array2d[r][c] + \" \");\n else\n System.out.print(\"* \");\n System.out.println();\n }\n}\n 4 * 8 2 5 \n5 * 6 * 7 \n3 * * * 9 \n8 * * * 1 \n* * * * 0 \n public static void main(String[] args) {\n int[][] array2d = {\n {4, 5, 3, 8},\n {},\n {8, 6},\n {2},\n {5, 7, 9, 1, 0}\n };\n int rowSie = array2d.length;\n for (int c = 0; true; ++c) {\n StringBuilder sb = new StringBuilder();\n boolean out = false;\n for (int r = 0; r < rowSie; ++r)\n if (c < array2d[r].length) {\n sb.append(array2d[r][c]).append(\" \");\n out = true;\n } else\n sb.append(\"* \");\n if (!out)\n break;\n System.out.println(sb);\n }\n}\n 4 * 8 2 5 \n5 * 6 * 7 \n3 * * * 9 \n8 * * * 1 \n* * * * 0 \n" }, { "answer_id": 74663907, "author": "Old Dog Programmer", "author_id": 5103317, "author_profile": "https://Stackoverflow.com/users/5103317", "pm_score": 1, "selected": false, "text": "int i;\nfor (i = 0; i < 10; i++) { /* loop body */ }\n i < 10 false i 10 for (currentRow = 0; currentRow < array2d.length; currentRow++) \n currentRow array2d.length currentColumn < (array2d[currentRow].length) array2d[currentRow] IndexOutOfBoundsException for (int row = 0; row < array2d.length; row++) { \n for (int column = 0; column < array2d[row].length; column++ { \n // things to do in inner loop\n }\n for (int column = 0; column < array2d[0].length; column++) { \n for (int row = 0; row < array2d.length; row++) {\n // loop body\n }\n }\n int maxColumns = 0;\n for (int i = 0; i < array.length; i++) { \n maxColumns = Math.max (maxColumns, array2d[i].length);\n }\n for (int column = 0; column < maxColumns; column++) { \n for (int row = 0; row < array2d.length; row++) { \n if (column < array2d[row].length) {\n // do something with array2d [row][column]\n } else { \n // do something for the case where \n // array2d [row] doesn't have a value in \"column\" \n }\n }\n }\n ArrayIndexOutOfBoundsException" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12257400/" ]
74,663,654
<p>Say I have a table:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE staff ( id INT, name CHAR(9) ); </code></pre> <p>With data:</p> <pre><code>INSERT INTO staff (id, name) VALUES (1, 'Joe'); INSERT INTO staff (id, name) VALUES (2, 'Bob'); INSERT INTO staff (id, name) VALUES (3, 'Alice'); </code></pre> <p>I need to create a multi row UDF, something like the built-in <code>AVG</code> function, such that I can call it in the following manner:</p> <pre class="lang-sql prettyprint-override"><code>SELECT vowel_count(name) FROM staff; </code></pre> <p>And assuming vowels are <code>[AaEeIiOoUu]</code>, get the following result:</p> <pre><code>| vowel_count(name) | |-------------------| | 6 | </code></pre> <p>What is the syntax to take a table column as input to a UDF?</p> <pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION vowel_cnt(/* what goes here? */) RETURN NUMBER IS ... BEGIN ... END; </code></pre> <p>The function must be table agnostic, just like <code>SUM</code>, <code>AVG</code>, etc.</p> <p>I am using Oracle PL/SQL and SQL Developer.</p>
[ { "answer_id": 74664773, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": -1, "selected": false, "text": "SELECT vowel_count(name) FROM staff;\n create or replace Function VOWEL_COUNT_FROM_STRING(p_string VarChar2) RETURN Number IS\nBEGIN\n Declare\n vowels VarChar2(5) := 'AEIOU';\n mRet Number(6) := 0;\n Begin\n For i in 1..Length(p_string) Loop\n If InStr(vowels, SubStr(Upper(p_string), i, 1)) > 0 Then\n mRet := mRet + 1;\n End If;\n End Loop;\n RETURN mRet; \n End;\nEND VOWEL_COUNT_FROM_STRING;\n\n-- ----------------------------------------------------------\n\ncreate or replace Function VOWEL_COUNT RETURN Number IS\nBEGIN\n Declare\n CURSOR c IS SELECT Upper(NAME) FROM A_TBL;\n vowels VarChar2(5) := 'AEIOU';\n mName A_TBL.NAME%TYPE;\n mRet Number(6) := 0;\n Begin\n OPEN c;\n LOOP\n FETCH c InTo mName;\n EXIT WHEN c%NOTFOUND;\n For i in 1..Length(mName) Loop\n If InStr(vowels, SubStr(mName, i, 1)) > 0 Then\n mRet := mRet + 1;\n End If;\n End Loop;\n END LOOP;\n Close c;\n RETURN mRet; \n End;\nEND VOWEL_COUNT;\n Select ID, NAME, VOWEL_COUNT_FROM_STRING(NAME) \"VOWELS\", VOWEL_COUNT() \"TOTAL_VOWELS\" From A_TBL\n Select ID, NAME, VOWEL_COUNT_FROM_STRING(NAME) \"VOWELS\", Sum(VOWEL_COUNT_FROM_STRING(NAME)) OVER() \"TOTAL_VOWELS\" From A_TBL\n create or replace Function VOWEL_COUNT_FROM_TABLE_COLUMN(p_table VarChar2, p_column VarChar2) RETURN Number IS\nBEGIN\n Declare\n vowels VarChar2(5) := 'AEIOU';\n mCmd VarChar2(1000);\n mString VarChar2(32000); -- NOTE the limitation in this variable length\n mRet Number(6) := 0;\n Begin\n mCmd := 'Select LISTAGG(' || p_column || ', '','') WITHIN GROUP (Order By ' || p_column || ') From ' || p_table;\n Execute Immediate mCmd Into mString;\n --\n For i in 1..Length(mString) Loop\n If InStr(vowels, SubStr(Upper(mString), i, 1)) > 0 Then\n mRet := mRet + 1;\n End If;\n End Loop;\n --\n RETURN mRet; \n End;\nEND VOWEL_COUNT_FROM_TABLE_COLUMN;\n Select VOWEL_COUNT_FROM_TABLE_COLUMN('A_TBL', 'NAME') \"TOTAL_VOWELS\" From Dual;\n\n-- Result:\n-- TOTAL_VOWELS\n-- ------------\n-- 6\n" }, { "answer_id": 74665701, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 3, "selected": true, "text": "create or replace type t_vowel_count as object (\n g_count number,\n static function ODCIAggregateInitialize(\n p_ctx in out t_vowel_count\n ) return number,\n member function ODCIAggregateIterate(\n self in out t_vowel_count, p_string varchar2\n ) return number,\n member function ODCIAggregateTerminate(\n self in out t_vowel_count, p_result out number, p_flags in number\n ) return number,\n member function ODCIAggregateMerge(\n self in out t_vowel_count, p_ctx in t_vowel_count\n ) return number\n);\n/\n create or replace type body t_vowel_count as\n static function ODCIAggregateInitialize(\n p_ctx in out t_vowel_count\n ) return number is\n begin\n p_ctx := t_vowel_count(null);\n -- initialise count to zero\n p_ctx.g_count := 0;\n return ODCIConst.success;\n end ODCIAggregateInitialize;\n\n member function ODCIAggregateIterate(\n self in out t_vowel_count, p_string varchar2\n ) return number is\n begin\n -- regex is clearer...\n -- self.g_count := self.g_count + regexp_count(p_string, '[aeiou]', 1, 'i');\n -- but translate is faster...\n self.g_count := self.g_count\n + coalesce(length(p_string), 0)\n - coalesce(length(translate(p_string, 'xaAeEiIoOuU', 'x')), 0);\n return ODCIConst.success;\n end ODCIAggregateIterate;\n\n member function ODCIAggregateTerminate(\n self in out t_vowel_count, p_result out number, p_flags in number\n ) return number is\n begin\n p_result := self.g_count;\n return ODCIConst.success;\n end ODCIAggregateTerminate;\n\n member function ODCIAggregateMerge(\n self in out t_vowel_count, p_ctx in t_vowel_count\n ) return number is\n begin\n self.g_count := self.g_count + p_ctx.g_count;\n return ODCIConst.success;\n end ODCIAggregateMerge;\nend t_vowel_count;\n/\n translate() create or replace function vowel_count (p_string varchar2)\nreturn number\nparallel_enable\naggregate using t_vowel_count;\n/\n SELECT vowel_count(name) FROM staff;\n" }, { "answer_id": 74667891, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION vowel_count(\n value IN VARCHAR2\n) RETURN NUMBER DETERMINISTIC\nIS\nBEGIN\n RETURN LENGTH(value) - COALESCE(LENGTH(TRANSLATE(value, '_AaEeIiOoUu', '_')), 0);\nEND;\n/\n SELECT SUM(vowel_count(name)) AS total_vowel_count\nFROM staff;\n CREATE TABLE staff (id, name) AS\n SELECT 1, 'Alice' FROM DUAL UNION ALL\n SELECT 2, 'Betty' FROM DUAL UNION ALL\n SELECT 3, 'Carol' FROM DUAL UNION ALL\n SELECT 4, 'Aeia' FROM DUAL;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16471560/" ]
74,663,657
<p>My first time trying to extract data from an SVG element, following is the SVG element and the code I have tried to put up by reading stuff on the internet, I have absolutely no clue how wrong I am and why so.</p> <pre><code>&lt;svg class=&quot;rv-xy-plot__inner&quot; width=&quot;282&quot; height=&quot;348&quot;&gt; &lt;g class=&quot;rv-xy-plot__series rv-xy-plot__series--bar &quot; transform=&quot;rrr&quot;&gt; &lt;rect y=&quot;rrr&quot; height=&quot;rrr&quot; x=&quot;0&quot; width=&quot;rrr&quot; style=&quot;rrr;&quot;&gt;&lt;/rect&gt; &lt;rect y=&quot;rrr&quot; height=&quot;rrr&quot; x=&quot;0&quot; width=&quot;rrr&quot; style=&quot;rrr;&quot;&gt;&lt;/rect&gt; &lt;/g&gt; &lt;g class=&quot;rv-xy-plot__series rv-xy-plot__series--bar &quot; transform=&quot;rrr&quot;&gt; &lt;rect y=&quot;rrr&quot; height=&quot;rrr&quot; x=&quot;rrr&quot; width=&quot;rrr&quot; style=&quot;rrr;&quot;&gt;&lt;/rect&gt; &lt;rect y=&quot;rrr&quot; height=&quot;rrr&quot; x=&quot;rrr&quot; width=&quot;rrr&quot; style=&quot;rrr;&quot;&gt;&lt;/rect&gt; &lt;/g&gt; &lt;g class=&quot;rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary&quot; transform=&quot;rrr&quot;&gt; &lt;text dominant-baseline=&quot;rrr&quot; class=&quot;rv-xy-plot__series--label-text&quot;&gt;Category 1&lt;/text&gt; &lt;text dominant-baseline=&quot;rrr&quot; class=&quot;rv-xy-plot__series--label-text&quot;&gt;Category 2&lt;/text&gt; &lt;/g&gt; &lt;g class=&quot;rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary&quot; transform=&quot;rrr&quot;&gt; &lt;text dominant-baseline=&quot;rrr&quot; class=&quot;rv-xy-plot__series--label-text&quot;&gt;44.83%&lt;/text&gt; &lt;text dominant-baseline=&quot;rrr&quot; class=&quot;rv-xy-plot__series--label-text&quot;&gt;0.00%&lt;/text&gt; &lt;/g&gt; &lt;/svg&gt; </code></pre> <p>I am trying to get the Categories and corresponding Percentages from the last 2 blocks of the SVG, I've replaced all the values with the string 'rrr' just to make it more readable here.</p> <p>I'm trying,</p> <pre><code>driver.find_element(By.XPATH,&quot;//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']&quot;).get_attribute('innerText') </code></pre> <p>Like I said, I don't know what I'm doing here, what I've so far understood is svg elements need to be represented as a 'custom ?' XPATH which involves stacking all elements into an XPATH which is relative to each other, however I have no clue on how to extract the expected output like below.</p> <pre><code>Category 1 - 44.83% Category 2 - 0.00% </code></pre> <p>Any help is appreciated. Thanks.</p>
[ { "answer_id": 74664377, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 2, "selected": true, "text": "for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']\"):\n txt= sv.find_emlement(By.XPATH, './/text').text\n print(txt)\n for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//text\"):\n txt= sv.text\n print(txt)\n \n \n" }, { "answer_id": 74668403, "author": "babsdoc", "author_id": 1592397, "author_profile": "https://Stackoverflow.com/users/1592397", "pm_score": 0, "selected": false, "text": "sv = driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']\")\n //*[name()='text']" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1592397/" ]
74,663,663
<p>I have many string to match against a regex. Many strings start with the same substring. To speed up my search, I would like to check whether the regex could match a string which begins with the common substring...</p> <h5>Example</h5> <p>I have a regex like for instance: <code>/^(.[3e]|[o0]+)+l+$/</code> and many strings, like for instance these:</p> <pre><code>... goo goober good goodhearted goodly goods goody goof goofball google goon goose ... held helical helices helicopter helipad heliport hell help hellion helm helmet ... </code></pre> <p>Half of the strings start with <code>goo</code>: I'd like to test whether <code>goo</code> is a valid beginning for a match. It's not (no string starting with <code>goo</code> can ever match that regex), thus I'd discard all those words at once.</p> <p>The other half start with <code>hel</code>: I'd like to test whether <code>hel</code> is a valid beginning for a match. It is (some strings starting with <code>hel</code> may match that regex), thus I proceed testing those strings.</p> <p>Is there any function to do this with a generic regex, without having to manually re-engineer it?</p>
[ { "answer_id": 74664377, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 2, "selected": true, "text": "for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']\"):\n txt= sv.find_emlement(By.XPATH, './/text').text\n print(txt)\n for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//text\"):\n txt= sv.text\n print(txt)\n \n \n" }, { "answer_id": 74668403, "author": "babsdoc", "author_id": 1592397, "author_profile": "https://Stackoverflow.com/users/1592397", "pm_score": 0, "selected": false, "text": "sv = driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']\")\n //*[name()='text']" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13948744/" ]
74,663,667
<p>I've been trying to get this to work forever and still no luck</p> <p>I have:</p> <ul> <li>GTX 1050 Ti (on Lenovo Legion laptop)</li> <li>the laptop also has an Intel UHD Graphics 630 (i'm not sure if maybe this is interfering?)</li> <li>Anaconda</li> <li>Visual Studio</li> <li>Python 3.9.13</li> <li>CUDA 11.2</li> <li>cuDNN 8.1</li> <li>I added these to the PATH: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\libnvvp</li> <li>finally I installed tensorflow and created its own environment</li> </ul> <p>and I still can't get it to read my GPU</p> <p>basically followed <a href="https://www.youtube.com/watch?v=hHWkvEcDBO0&amp;t=295s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=hHWkvEcDBO0&amp;t=295s</a></p> <p>AND I'm still having no luck.</p> <pre><code>from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) </code></pre> <p>yields only information on the CPU</p> <p>Can anyone please help?</p>
[ { "answer_id": 74664377, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 2, "selected": true, "text": "for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']\"):\n txt= sv.find_emlement(By.XPATH, './/text').text\n print(txt)\n for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//text\"):\n txt= sv.text\n print(txt)\n \n \n" }, { "answer_id": 74668403, "author": "babsdoc", "author_id": 1592397, "author_profile": "https://Stackoverflow.com/users/1592397", "pm_score": 0, "selected": false, "text": "sv = driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']\")\n //*[name()='text']" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671394/" ]
74,663,674
<p><a href="https://dev.mysql.com/doc/refman/8.0/en/mysqldump.html#option_mysqldump_single-transaction" rel="nofollow noreferrer">MySQL documentation</a> says</p> <blockquote> <p>--single-transaction</p> </blockquote> <blockquote> <p>This option sets the transaction isolation mode to <strong>REPEATABLE READ</strong> and sends a START TRANSACTION SQL statement to the server before dumping data. It is useful only with transactional tables such as InnoDB, because then it dumps the consistent state of the database at the time when START TRANSACTION was issued without blocking any applications.</p> </blockquote> <p>My doubt is that, it says the isolation is set as <strong>REPEATABLE READ</strong>, but this may not guarantee a consistent database state.</p> <p>For example, if we have a table <code>Employee</code>, and a table <code>Hobby</code>, and a table <code>EmployeeHobby</code> which stores employee id and hobby id.</p> <p>When we use <code>–single-transaction</code> (i.e., <code>REPEATABLE READ</code>) to dump the database. Let's denote the transaction as <code>A</code>.</p> <p>In <code>A</code> we first dump table <code>Employee</code>, then some concurrent transaction <code>B</code> insert a new employee into <code>Employee</code>, and <code>B</code> adds related hobby into <code>Hobby</code> and <code>EmployeeHobby</code> (this does not violate <code>REPEATABLE_READ</code> since <code>A</code> never reads <code>Employee</code> afterwards), and then <code>A</code> dump table <code>EmployeeHobby</code> and <code>Hobby</code>.</p> <p>Eventually, the dumped data by <code>A</code> is not consistent, since <code>EmployeeHobby</code> contains the id of a employee that does not exist in <code>Employee</code>.</p> <p>The dumped data is broken, isn't it?</p> <p>What the doc says</p> <blockquote> <p>it dumps the consistent state of the database at the time when START TRANSACTION was issued</p> </blockquote> <p>seems not to be achievable by setting it to be a <code>REPEATABLE READ</code> transaction.</p>
[ { "answer_id": 74664377, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 2, "selected": true, "text": "for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']\"):\n txt= sv.find_emlement(By.XPATH, './/text').text\n print(txt)\n for sv in driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//text\"):\n txt= sv.text\n print(txt)\n \n \n" }, { "answer_id": 74668403, "author": "babsdoc", "author_id": 1592397, "author_profile": "https://Stackoverflow.com/users/1592397", "pm_score": 0, "selected": false, "text": "sv = driver.find_elements(By.XPATH,\"//*[local-name()='svg' and @class='rv-xy-plot__inner']//*[local-name()='g' and @class='rv-xy-plot__series rv-xy-plot__series--label typography-body-medium-xs text-primary']//*[name()='text']\")\n //*[name()='text']" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12639005/" ]
74,663,677
<p>How to change this SQL query to PL/SQL command line or code?</p> <pre><code>SELECT username, account_status FROM dba_users; </code></pre> <p>I tried</p> <pre><code>DECLARE user_name VARCHAR2(20) := 'username'; account_status VARCHAR2(20) := 'account_status'; BEGIN FOR user_name IN (SELECT username FROM dba_users) LOOP FOR account_status IN (SELECT account_status FROM dba_users) LOOP dbms_output.put_line(user_name.username || ' - ' || user_record.account_status); END LOOP; END LOOP; END; </code></pre> <p>it works but the output is repeating</p>
[ { "answer_id": 74664478, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 2, "selected": false, "text": "SQL> select username, account_status from dba_users where rownum <= 5;\n\nUSERNAME ACCOUNT_STATUS\n-------------------- --------------------\nSYS OPEN\nAUDSYS LOCKED\nSYSTEM OPEN\nSYSBACKUP LOCKED\nSYSDG LOCKED\n SQL> set serveroutput on\nSQL> begin\n 2 for cur_r in (select username, account_status from dba_users where rownum <= 5)\n 3 loop\n 4 dbms_output.put_line(cur_R.username ||' - '|| cur_r.account_status);\n 5 end loop;\n 6 end;\n 7 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n SQL> begin\n 2 for cur_user in (select username from dba_users where rownum <= 5) loop\n 3 for cur_acc in (select account_status from dba_users\n 4 where username = cur_user.username\n 5 )\n 6 loop\n 7 dbms_output.put_line(cur_user.username ||' - '|| cur_acc.account_status);\n 8 end loop;\n 9 end loop;\n 10 end;\n 11 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74665999, "author": "Reza Davoudian", "author_id": 19586497, "author_profile": "https://Stackoverflow.com/users/19586497", "pm_score": 0, "selected": false, "text": "cl scr\nset SERVEROUTPUT ON\n\nBEGIN\n FOR i IN (SELECT distinct username FROM dba_users order by username) LOOP\n FOR j IN (SELECT distinct account_status FROM dba_users where username=i.username order by account_status) LOOP\n dbms_output.put_line(i.username || ' - ' || j.account_status);\n END LOOP;\n END LOOP;\nEND;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18434476/" ]
74,663,708
<p>Let's say I have a c# project Foo and a classlibrary called Bar</p> <p>I'm wanting to develop Bar alongside Foo which will use Bar as a shared library. I'd like to keep these Foo and Bar in their own git repositories.</p> <p>When I debug Foo, I'd like to be able to step into Bar to see what it's doing under the hood. When I make changes to Bar, I'd like to be able to have my changes reflected in Foo. It's okay if I'd have to build Bar first for my changes to take effect.</p> <p>When I eventually deploy Foo, I'd like to import Bar as a nuget package, rather than including it as a part of the solution for Foo</p> <p>Is this possible in c#? I've been trying to develop a shared library and a repository that uses that library as a template for future projects. I've tried to publish Bar as a nuget package to my local filesystem but it's been giving me problems; I'm unable to step into functions that call into Bar from project Foo and when I make changes to Bar I have to build, pack, then publish the library again. If I don't bump the version number of bar when I do this, this results in errors where I have to go to the nuget package in my filesystem and delete it manually.</p> <h2>Aside</h2> <p>If you're interested Bar contains extension methods for setting up a connection to a message broker along with classes for configuration definition and &quot;contract&quot; classes that need to be shared among projects.</p>
[ { "answer_id": 74664478, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 2, "selected": false, "text": "SQL> select username, account_status from dba_users where rownum <= 5;\n\nUSERNAME ACCOUNT_STATUS\n-------------------- --------------------\nSYS OPEN\nAUDSYS LOCKED\nSYSTEM OPEN\nSYSBACKUP LOCKED\nSYSDG LOCKED\n SQL> set serveroutput on\nSQL> begin\n 2 for cur_r in (select username, account_status from dba_users where rownum <= 5)\n 3 loop\n 4 dbms_output.put_line(cur_R.username ||' - '|| cur_r.account_status);\n 5 end loop;\n 6 end;\n 7 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n SQL> begin\n 2 for cur_user in (select username from dba_users where rownum <= 5) loop\n 3 for cur_acc in (select account_status from dba_users\n 4 where username = cur_user.username\n 5 )\n 6 loop\n 7 dbms_output.put_line(cur_user.username ||' - '|| cur_acc.account_status);\n 8 end loop;\n 9 end loop;\n 10 end;\n 11 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74665999, "author": "Reza Davoudian", "author_id": 19586497, "author_profile": "https://Stackoverflow.com/users/19586497", "pm_score": 0, "selected": false, "text": "cl scr\nset SERVEROUTPUT ON\n\nBEGIN\n FOR i IN (SELECT distinct username FROM dba_users order by username) LOOP\n FOR j IN (SELECT distinct account_status FROM dba_users where username=i.username order by account_status) LOOP\n dbms_output.put_line(i.username || ' - ' || j.account_status);\n END LOOP;\n END LOOP;\nEND;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11438666/" ]
74,663,709
<p>I am having trouble getting multiple number vars from a read in line. For a single value I can do strtol(), but how can I get the float and long values of a sentence that is similar to as follows.</p> <blockquote> <p>Please aim 3.567 degrees at a height of 5 meters.</p> </blockquote> <p>I tried doing two different calls to my buffer sentence, however it got neither of my values. I have no issues with get single values, but with to, I get 0.000 from my strtof call and 0 from mmy strtol call.</p>
[ { "answer_id": 74664478, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 2, "selected": false, "text": "SQL> select username, account_status from dba_users where rownum <= 5;\n\nUSERNAME ACCOUNT_STATUS\n-------------------- --------------------\nSYS OPEN\nAUDSYS LOCKED\nSYSTEM OPEN\nSYSBACKUP LOCKED\nSYSDG LOCKED\n SQL> set serveroutput on\nSQL> begin\n 2 for cur_r in (select username, account_status from dba_users where rownum <= 5)\n 3 loop\n 4 dbms_output.put_line(cur_R.username ||' - '|| cur_r.account_status);\n 5 end loop;\n 6 end;\n 7 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n SQL> begin\n 2 for cur_user in (select username from dba_users where rownum <= 5) loop\n 3 for cur_acc in (select account_status from dba_users\n 4 where username = cur_user.username\n 5 )\n 6 loop\n 7 dbms_output.put_line(cur_user.username ||' - '|| cur_acc.account_status);\n 8 end loop;\n 9 end loop;\n 10 end;\n 11 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74665999, "author": "Reza Davoudian", "author_id": 19586497, "author_profile": "https://Stackoverflow.com/users/19586497", "pm_score": 0, "selected": false, "text": "cl scr\nset SERVEROUTPUT ON\n\nBEGIN\n FOR i IN (SELECT distinct username FROM dba_users order by username) LOOP\n FOR j IN (SELECT distinct account_status FROM dba_users where username=i.username order by account_status) LOOP\n dbms_output.put_line(i.username || ' - ' || j.account_status);\n END LOOP;\n END LOOP;\nEND;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16510301/" ]
74,663,750
<p>The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so?</p> <pre><code>extension = 'csv' all_filenames = [i for i in glob.glob('*.{}.format(extension))] combined)csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined)csv.to_csv(&quot;combined_csv.csv&quot;, index= False, encoding= 'utf-8-sig') </code></pre>
[ { "answer_id": 74664478, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 2, "selected": false, "text": "SQL> select username, account_status from dba_users where rownum <= 5;\n\nUSERNAME ACCOUNT_STATUS\n-------------------- --------------------\nSYS OPEN\nAUDSYS LOCKED\nSYSTEM OPEN\nSYSBACKUP LOCKED\nSYSDG LOCKED\n SQL> set serveroutput on\nSQL> begin\n 2 for cur_r in (select username, account_status from dba_users where rownum <= 5)\n 3 loop\n 4 dbms_output.put_line(cur_R.username ||' - '|| cur_r.account_status);\n 5 end loop;\n 6 end;\n 7 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n SQL> begin\n 2 for cur_user in (select username from dba_users where rownum <= 5) loop\n 3 for cur_acc in (select account_status from dba_users\n 4 where username = cur_user.username\n 5 )\n 6 loop\n 7 dbms_output.put_line(cur_user.username ||' - '|| cur_acc.account_status);\n 8 end loop;\n 9 end loop;\n 10 end;\n 11 /\nSYS - OPEN\nAUDSYS - LOCKED\nSYSTEM - OPEN\nSYSBACKUP - LOCKED\nSYSDG - LOCKED\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74665999, "author": "Reza Davoudian", "author_id": 19586497, "author_profile": "https://Stackoverflow.com/users/19586497", "pm_score": 0, "selected": false, "text": "cl scr\nset SERVEROUTPUT ON\n\nBEGIN\n FOR i IN (SELECT distinct username FROM dba_users order by username) LOOP\n FOR j IN (SELECT distinct account_status FROM dba_users where username=i.username order by account_status) LOOP\n dbms_output.put_line(i.username || ' - ' || j.account_status);\n END LOOP;\n END LOOP;\nEND;\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16768738/" ]
74,663,754
<p>I'm trying to add a remove method to my BST But I just can't figure out what is wrong. I have defined the <code>pointer</code> variable using <code>let</code> but it's still not working. It seems like it doesn't update the <code>root</code> object.</p> <pre><code>const Node = (data, left = null, right = null) =&gt; { return {data, left, right}; }; const Tree = array =&gt; { const remDupsAndSort = array =&gt; { const mergeSort = array =&gt; { if(array.length &lt;= 1) return array; let leftArr = array.slice(0, array.length / 2); let rightArr = array.slice(array.length / 2); return merge(mergeSort(rightArr), mergeSort(leftArr)) }; const merge = (leftArr, rightArr) =&gt; { let sorted = []; while(leftArr.length &amp;&amp; rightArr.length){ if(leftArr[0] &lt; rightArr[0]){ sorted.push(leftArr.shift()); }else{ sorted.push(rightArr.shift()); } }; return [...sorted, ...leftArr, ...rightArr] }; return mergeSort([... new Set(array)]) }; array = remDupsAndSort(array); const buildTree = (array, start, end) =&gt; { if(start &gt; end) return null; let mid = Math.floor((start + end) / 2); let node = Node(array[mid]); node.left = buildTree(array, start, mid - 1); node.right = buildTree(array, mid + 1, end); return node; }; const remove = value =&gt; { if(!root) return root; let pointer = root; while(pointer){ if(value &lt; pointer.data){ pointer = pointer.left } else if(value &gt; pointer.data){ pointer = pointer.right; }else{ if(!pointer.right &amp;&amp; !pointer.left){ return null; } if(!pointer.left){ return pointer.right; }else if(!pointer.right){ return pointer.left; }else{ let nextBiggest = pointer.right; while(nextBiggest.left){ nextBiggest = nextBiggest.left; } return pointer = nextBiggest; } } } }; let root = buildTree(array, 0, array.length - 1); return {root, remove} }; </code></pre> <p>When I run the code it doesn't remove anything from the tree. What am I missing?</p>
[ { "answer_id": 74663996, "author": "abney317", "author_id": 391715, "author_profile": "https://Stackoverflow.com/users/391715", "pm_score": 1, "selected": false, "text": "let pointer = root; root pointer pointer parent.left parent.right" }, { "answer_id": 74675626, "author": "Farzam", "author_id": 18305265, "author_profile": "https://Stackoverflow.com/users/18305265", "pm_score": 0, "selected": false, "text": "const remove = value => {\n if(!root) return root;\n let pointer = root;\n let parent = null;\n while(pointer){\n if(value < pointer.data){\n parent = pointer;\n pointer = pointer.left\n }\n else if(value > pointer.data){\n parent = pointer;\n pointer = pointer.right;\n }else{\n if(!pointer.right && !pointer.left){\n if(pointer === parent.left) return parent.left = null;\n if(pointer === parent.right) return parent.right = null;\n }\n if(!pointer.left){\n if(pointer === parent.left) return parent.left = pointer.right\n if(pointer === parent.right) return parent.right = pointer.right\n }else if(!pointer.right){\n if(pointer === parent.left) return parent.left = pointer.left\n if(pointer === parent.right) return parent.right = pointer.left\n }else{\n let replacingNode = pointer.right;\n let replacingParent = pointer;\n while(replacingNode.left){\n replacingParent = replacingNode;\n replacingNode = replacingNode.left;\n }\n if(pointer === root){\n replacingNode.right = root.right;\n replacingNode.left = root.left;\n root = replacingNode;\n if(replacingNode === replacingParent.left) return replacingParent.left = null;\n if(replacingNode === replacingParent.right) return replacingParent.right = null;\n\n }\n if(pointer === parent.left){\n if(replacingNode === pointer.left){\n replacingNode.left = null;\n }else{\n replacingNode.left = pointer.left;\n }\n if(replacingNode === pointer.right){\n replacingNode.right = null;\n }else{\n replacingNode.right = pointer.right;\n }\n parent.left = replacingNode;\n if(replacingNode === replacingParent.left) return replacingParent.left = null;\n if(replacingNode === replacingParent.right) return replacingParent.right = null;\n } \n if(pointer === parent.right){\n if(replacingNode === pointer.left){\n replacingNode.left = null;\n }else{\n replacingNode.left = pointer.left;\n }\n if(replacingNode === pointer.right){\n replacingNode.right = null;\n }else{\n replacingNode.right = pointer.right;\n }\n parent.right = replacingNode; \n if(replacingNode === replacingParent.left) return replacingParent.left = null;\n if(replacingNode === replacingParent.right) return replacingParent.right = null;\n } \n } \n }\n }\n };\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18305265/" ]
74,663,778
<pre><code>export class MyComponent { array_all: Array&lt;{ page: any }&gt; = []; array_page: Array&lt;{ id: number, name: string }&gt; = []; item: Array&lt;{ id: number, name: string }&gt; = [ { id: 1, name: 'Test name' } ] constructor(){ this.array_page.push({ id: this.item.id, name: this.item.name }); this.array_all.push({ page: this.array_page }); console.log(this.array_all.page.id); // error TS2339: Property 'page' does not exist on type '{ page: any; }[]'. } } </code></pre> <pre><code>&lt;div *ngFor=&quot;let page of array_all&quot;&gt; &lt;h1&gt;Id: {{page.id}}&lt;/h1&gt; &lt;!-- error TS2339: Property 'id' does not exist on type '{ page: any; }' --&gt; &lt;/div&gt; </code></pre> <p>What should I do here to access the property id or name? As I search for a solution I saw something related to convert the object to an array, then use a nested *ngFor. But I don't know how to do that.</p> <p>Full code in case you need it, here is the reason why I need to first push to an array and then to other:</p> <pre><code>export class AboutComponent { array_all: Array&lt;{ page: any }&gt; = []; array_page: Array&lt;{ id: number, name: string, link: string, image_url: string, image_alt: string }&gt; = []; constructor(){ let start_at: number = 0; let last_slice: number = 0; for(let i: number = start_at; i &lt; this.knowledge_items.length; i++){ if(i%2 === 0 &amp;&amp; i%3 === 0 &amp;&amp; i !== last_slice){ this.array_all.push({page: this.array_page}); this.array_page = []; this.array_page.push({ id: this.knowledge_items[i].id, name: this.knowledge_items[i].name, link: this.knowledge_items[i].link, image_url: this.knowledge_items[i].image_url, image_alt: this.knowledge_items[i].image_alt }); start_at = i; last_slice = i; } else{ this.array_page.push({ id: this.knowledge_items[i].id, name: this.knowledge_items[i].name, link: this.knowledge_items[i].link, image_url: this.knowledge_items[i].image_url, image_alt: this.knowledge_items[i].image_alt }); if(i === this.knowledge_items.length - 1){ this.array_all.push({page: this.array_page}); this.array_page = []; } } } console.log(this.array_all); } knowledge_items: Array&lt;{id: number, name: string, link: string, image_url: string, image_alt: string }&gt; = [ { id: 1, name: 'C++', link: 'https://es.wikipedia.org/wiki/C%2B%2B', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/ISO_C%2B%2B_Logo.svg/1200px-ISO_C%2B%2B_Logo.svg.png', image_alt: 'C++ programming language' }, { id: 2, name: 'Python', link: 'https://es.wikipedia.org/wiki/Python', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1869px-Python-logo-notext.svg.png', image_alt: 'Python programming language' }, { id: 3, name: 'C++', link: 'https://es.wikipedia.org/wiki/C%2B%2B', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/ISO_C%2B%2B_Logo.svg/1200px-ISO_C%2B%2B_Logo.svg.png', image_alt: 'C++ programming language' }, { id: 4, name: 'Python', link: 'https://es.wikipedia.org/wiki/Python', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1869px-Python-logo-notext.svg.png', image_alt: 'Python programming language' }, { id: 5, name: 'C++', link: 'https://es.wikipedia.org/wiki/C%2B%2B', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/ISO_C%2B%2B_Logo.svg/1200px-ISO_C%2B%2B_Logo.svg.png', image_alt: 'C++ programming language' }, { id: 6, name: 'Python', link: 'https://es.wikipedia.org/wiki/Python', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1869px-Python-logo-notext.svg.png', image_alt: 'Python programming language' }, { id: 7, name: 'C++', link: 'https://es.wikipedia.org/wiki/C%2B%2B', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/ISO_C%2B%2B_Logo.svg/1200px-ISO_C%2B%2B_Logo.svg.png', image_alt: 'C++ programming language' }, { id: 8, name: 'Python', link: 'https://es.wikipedia.org/wiki/Python', image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1869px-Python-logo-notext.svg.png', image_alt: 'Python programming language' } } </code></pre>
[ { "answer_id": 74664075, "author": "h.zare", "author_id": 9628852, "author_profile": "https://Stackoverflow.com/users/9628852", "pm_score": 0, "selected": false, "text": "export class MyComponent {\n\narray_all: Array<{ page: any }> = [];\narray_page: Array<{ id: number, name: string }> = [];\n\nitem: Array<{ id: number, name: string }> = [\n {\n id: 1,\n name: 'Test name'\n }\n]\n\nconstructor(){\n this.array_page.push({\n id: this.item[0].id,\n name: this.item[0].name\n });\n\n this.array_all.push({\n page: [...this.array_page]\n });\n\n console.log(this.array_all[0].page[0].id);\n}\n <div *ngFor=\"let page of array_all\">\n <h1>Id: {{page.page.id}}</h1>\n</div>\n" }, { "answer_id": 74664076, "author": "Devang Patel", "author_id": 10755112, "author_profile": "https://Stackoverflow.com/users/10755112", "pm_score": 2, "selected": true, "text": "array_all.page <div *ngFor=\"let arrayItem of array_all; let i = index\">\n <div *ngFor=\"let item of arrayItem.page\">\n <h1>Id: {{ item.id }}</h1>\n </div>\n</div>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18895342/" ]
74,663,785
<p>Given one element in a list, what is the most efficient way that I can find the other elements?</p> <p>(e.g. if a list is <code>l=[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;]</code> and you're given &quot;B&quot;, it outputs &quot;A&quot;, &quot;C&quot; and &quot;D&quot;)?</p>
[ { "answer_id": 74663864, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 2, "selected": true, "text": "def method1(test_list, item):\n #List Comprehension\n res = [i for i in test_list if i != item]\n return res\n\ndef method2(test_list,item):\n #Filter Function\n res = list(filter((item).__ne__, test_list))\n return res\n\ndef method3(test_list,item):\n #Remove Function\n c=test_list.count(item)\n for i in range(c):\n test_list.remove(item)\n return test_list\n \nprint(method1([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method2([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method3([\"A\",\"B\",\"C\",\"D\"],\"B\"))\n ['A', 'C', 'D']\n['A', 'C', 'D']\n['A', 'C', 'D']\n" }, { "answer_id": 74663880, "author": "animesh chaudhri", "author_id": 20166957, "author_profile": "https://Stackoverflow.com/users/20166957", "pm_score": 0, "selected": false, "text": "# a list\nl1 =[\"a\",\"b\",\"C\",\"d\"]\n#input of the value to exclude \njo = input()\nl2=[]\nfor i in range(len(l1)):\n if l1[i]!=jo:\n l2.append(l1[i])\nprint(l2) \n\n \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444093/" ]
74,663,827
<p>I am trying to create a table that scrolls horizontally after the first column inside, I have a for loop for each column to get data from an array. I know this isn't the correct way because of how many times i am looping the same array but i cant figure out a better solution of doing this.</p> <pre><code> struct SampleData: Identifiable { let id = UUID() let Entity: String let address1: String let address2: String let city: String let state: String let zip: Int let website: String let billToName: String let billable: Bool let hours: String let accountNo: Int let BillToEntity: String let email: String } let datas = [ SampleData( Entity: &quot;Entity 1&quot;, address1: &quot;1234 N. Main&quot;, address2: &quot;Suite 200&quot;, city: &quot;austin&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 1&quot;, billable: false, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 1&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 2&quot;, address1: &quot;5678 N. Main&quot;, address2: &quot;Suite 300&quot;, city: &quot;livingston&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 2&quot;, billable: false, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 2&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 3&quot;, address1: &quot;90025 N. Main&quot;, address2: &quot;Suite 400&quot;, city: &quot;houston&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 3&quot;, billable: true, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 3&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 4&quot;, address1: &quot;4456 N. Main&quot;, address2: &quot;Suite 500&quot;, city: &quot;spring&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 4&quot;, billable: true, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 4&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 5&quot;, address1: &quot;4456 N. Main&quot;, address2: &quot;Suite 500&quot;, city: &quot;spring&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 4&quot;, billable: true, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 4&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 6&quot;, address1: &quot;56 N. Main&quot;, address2: &quot;Suite 500&quot;, city: &quot;spring&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 4&quot;, billable: false, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 4&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 7&quot;, address1: &quot;4456 N&quot;, address2: &quot;Suite 500&quot;, city: &quot;spring&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 4&quot;, billable: true, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 4&quot;, email: &quot;test@test.com&quot;), SampleData( Entity: &quot;Entity 8&quot;, address1: &quot;44 Main&quot;, address2: &quot;Suite 500&quot;, city: &quot;spring&quot;, state: &quot;TX&quot;, zip: 12345, website: &quot;www.website.com&quot;, billToName: &quot;Test Name 4&quot;, billable: true, hours: &quot;8-5 M-F&quot;, accountNo: 123_456_789, BillToEntity: &quot;Bill To Entity 4&quot;, email: &quot;test@test.com&quot;), ] </code></pre> <pre><code> struct TablesView: View { @State var billable = false var body: some View { HStack (alignment: .top){ VStack { Text(&quot;Entity&quot;) HStack(spacing: 16) { VStack { ForEach(datas) { val in Text(val.Entity) } } } } ScrollView(.horizontal) { HStack(alignment: .top) { VStack { VStack { Text(&quot;Address1&quot;) ForEach(datas) { val in Text(val.address1) } } } VStack { VStack { Text(&quot;Address2&quot;) ForEach(datas) { val in Text(val.address2) } } } VStack { VStack { Text(&quot;City&quot;) ForEach(datas) { val in Text(val.city) } } } VStack { VStack { Text(&quot;State&quot;) ForEach(datas) { val in Text(val.state) } } } VStack { VStack { Text(&quot;Zip&quot;) ForEach(datas) { val in Text(String(val.zip)) } } } VStack { VStack { Text(&quot;Website&quot;) ForEach(datas) { val in Text(val.website) } } } VStack { VStack { Text(&quot;Bill To&quot;) ForEach(datas) { val in Text(val.billToName) } } } VStack { VStack { Text(&quot;Billable&quot;) ForEach(datas) { val in Image(systemName: val.billable ? &quot;checkmark.square.fill&quot; : &quot;square&quot;) .foregroundColor(val.billable ? Color(UIColor.systemBlue) : Color.secondary) .onTapGesture { self.billable.toggle() } } } } } } } } } </code></pre> <p><a href="https://i.stack.imgur.com/J84rj.gif" rel="nofollow noreferrer">List with horizontal scrolling</a></p>
[ { "answer_id": 74663864, "author": "Yash Mehta", "author_id": 20172954, "author_profile": "https://Stackoverflow.com/users/20172954", "pm_score": 2, "selected": true, "text": "def method1(test_list, item):\n #List Comprehension\n res = [i for i in test_list if i != item]\n return res\n\ndef method2(test_list,item):\n #Filter Function\n res = list(filter((item).__ne__, test_list))\n return res\n\ndef method3(test_list,item):\n #Remove Function\n c=test_list.count(item)\n for i in range(c):\n test_list.remove(item)\n return test_list\n \nprint(method1([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method2([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method3([\"A\",\"B\",\"C\",\"D\"],\"B\"))\n ['A', 'C', 'D']\n['A', 'C', 'D']\n['A', 'C', 'D']\n" }, { "answer_id": 74663880, "author": "animesh chaudhri", "author_id": 20166957, "author_profile": "https://Stackoverflow.com/users/20166957", "pm_score": 0, "selected": false, "text": "# a list\nl1 =[\"a\",\"b\",\"C\",\"d\"]\n#input of the value to exclude \njo = input()\nl2=[]\nfor i in range(len(l1)):\n if l1[i]!=jo:\n l2.append(l1[i])\nprint(l2) \n\n \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10271922/" ]
74,663,829
<p>I have an array of objects as follows:</p> <pre><code>[ { &quot;type&quot;: &quot;Feature&quot;, &quot;geometry&quot;: { &quot;type&quot;: &quot;Point&quot;, &quot;coordinates&quot;: [ 137.89094924926758, 36.93143814715343 ] }, &quot;properties&quot;: { &quot;@geometry&quot;: &quot;center&quot;, &quot;@id&quot;: &quot;way/323049815&quot;, &quot;id&quot;: &quot;way/323049815&quot;, &quot;landuse&quot;: &quot;winter_sports&quot;, &quot;name&quot;: &quot;糸魚川シーサイドバレースキー場&quot;, &quot;name:en&quot;: &quot;Itoigawa Seaside Valley Ski Resort&quot;, &quot;name:ja&quot;: &quot;糸魚川シーサイドバレースキー場&quot;, &quot;source&quot;: &quot;Bing&quot;, &quot;sport&quot;: &quot;skiing&quot;, &quot;website&quot;: &quot;https://www.seasidevalley.com/&quot;, &quot;wikidata&quot;: &quot;Q11604871&quot;, &quot;wikipedia&quot;: &quot;ja:糸魚川シーサイドバレースキー場&quot; }, [snip] </code></pre> <p>I want to add the above array into a data object in javascript as follows.</p> <pre><code>{ &quot;data&quot;: [ //my data here. ] } </code></pre> <p>I have tried this;</p> <pre><code> let mydata = { &quot;data&quot;: skidata } </code></pre> <p>but is places back slashed a lot like this snippet;</p> <pre><code>{ &quot;data&quot;: &quot;[{\&quot;type\&quot;:\&quot;Feature\&quot;,\&quot;geometry\&quot;:{\&quot;type\&quot;:\&quot;Point\&quot;,\&quot;coordinates\&quot;... </code></pre> <p>How do I remove the back slashes in javascript please?</p> <p>This is the specific code;</p> <pre><code> let skidata = JSON.stringify(uniqueFeatures); let mydata = { &quot;data&quot;: skidata } console.log((mydata)); </code></pre> <p>When I console.log skidata, there are no backslashes. When I console.log mydata, back slashes are added, I think. This is a pict of console.log(mydata)</p> <p><a href="https://i.stack.imgur.com/YKCPX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YKCPX.png" alt="screen shot of console for my data" /></a></p>
[ { "answer_id": 74663865, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": "replace const json = '\"data\": \"[{\\\"type\\\":\\\"Feature\\\",\\\"geometry\\\":{\\\"type\\\":\\\"Point\\\",\\\"coordinates\\\"...';\n\nconst jsonWithoutBackslashes = json.replace(/\\\\/g, '');\n" }, { "answer_id": 74667400, "author": "andrewJames", "author_id": 12567365, "author_profile": "https://Stackoverflow.com/users/12567365", "pm_score": 2, "selected": true, "text": "JSON.stringify(uniqueFeatures) let mydata1 = { \"data\": uniqueFeatures }; let uniqueFeatures = [{\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n 137.89094924926758,\n 36.93143814715343\n ]\n },\n \"properties\": {\n \"@geometry\": \"center\",\n \"@id\": \"way/323049815\",\n \"id\": \"way/323049815\",\n \"landuse\": \"winter_sports\",\n \"name\": \"糸魚川シーサイドバレースキー場\",\n \"name:en\": \"Itoigawa Seaside Valley Ski Resort\",\n \"name:ja\": \"糸魚川シーサイドバレースキー場\",\n \"source\": \"Bing\",\n \"sport\": \"skiing\",\n \"website\": \"https://www.seasidevalley.com/\",\n \"wikidata\": \"Q11604871\",\n \"wikipedia\": \"ja:糸魚川シーサイドバレースキー場\"\n }\n}];\n\nlet skidata = JSON.stringify(uniqueFeatures);\n\nlet mydata1 = {\n \"data\": uniqueFeatures\n};\n\nlet mydata2 = {\n \"data\": skidata\n};\n\nconsole.log(\"What you get if you stringify your object:\");\nconsole.log(mydata2);\n\nconsole.log(\"What you want, instead:\");\nconsole.log(mydata1); <!doctype html>\n<html>\n\n<head>\n <meta charset=\"UTF-8\">\n <title>Demo</title>\n</head>\n\n<body>\n\n</body>\n\n</html> JSON.stringify()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3264461/" ]
74,663,841
<p>Both <code>.</code> and <code>::</code> can be used to call class methods, but, in my experience, <code>.</code> is by far the most commonly used of the two. So I am accustomed to using that form in documentation and RSpec describe/context/expect strings.</p> <p>However, the Ruby API documentation uses <code>::</code> (e.g. at <a href="https://rubyapi.org/3.1/o/string" rel="nofollow noreferrer">https://rubyapi.org/3.1/o/string</a>). Is that intended to mean that that form is preferred for the cases I described?</p> <p><a href="https://i.stack.imgur.com/nUBac.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nUBac.png" alt="enter image description here" /></a></p> <p>Note: This is <em>not</em> a duplicate of <a href="https://stackoverflow.com/questions/43134/is-there-a-difference-between-and-when-calling-class-methods-in-ruby">Is there a difference between :: and . when calling class methods in Ruby?</a>. That question refers to the use of the two alternate notations in Ruby source code, whereas this question refers to documentation and other textual descriptions (e.g. in rspec strings). There may be reasons to make different choices in code vs. documentation, for example, that using <code>.</code> in code more clearly indicates a message call vs. a constant access, whereas in documentation <code>::</code> might be preferred to more dramatically distinguish class methods from instance methods.</p>
[ { "answer_id": 74663871, "author": "Mehmet Masa", "author_id": 20671270, "author_profile": "https://Stackoverflow.com/users/20671270", "pm_score": 0, "selected": false, "text": "For example, consider the following class and method:\n\nclass MyClass\n # This is a class method\n def self.my_method\n # Method implementation goes here\n end\nend\n class MyClass\n # This is a class method\n def self.my_method\n # Method implementation goes here\n end\n\n # This is the documentation for the MyClass::my_method class method\n # @return [String] The result of the method\n def self.my_method_documentation\n # Documentation goes here\n end\nend\n class MyClass\n # This is a class method\n def self.my_method\n # Method implementation goes here\n end\n\n # This is the documentation for the MyClass.my_method class method\n # @return [String] The result of the method\n def self.my_method_documentation\n # Documentation goes here\n end\nend\n" }, { "answer_id": 74666741, "author": "Lorenzo Zabot", "author_id": 17791373, "author_profile": "https://Stackoverflow.com/users/17791373", "pm_score": 1, "selected": false, "text": ". String . :: :: #" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501266/" ]
74,663,859
<p>I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code.</p> <pre><code>def printFun(test): if (test &lt; 1): return else: print(test, end=&quot;a &quot;) printFun(test-1) # statement 2 print(test, end=&quot;n &quot;) return # Driver Code test = 3 printFun(test) </code></pre> <p>This outputs</p> <pre><code>3a 2a 1a 1n 2n 3n </code></pre> <p>I can make sense of the first 4 outputs. test = 3, which not less than 1, so print test(1a), then re-call the printFun function with test-1 being 2, which is not less than 1, so print test (2a), then (1a) then 0, which IS less than 1 so return. I assume this brings you back to the</p> <pre><code>print(test, end='n') </code></pre> <p>line? which now prints 1n.</p> <p>This is where I am left perplexed... what is happening beyond this??? How does it start ascending and then stop again at 3? What is the flow and logic of this? Sorry if this is a ridiculous question and I am overlooking something blatantly obvious.</p> <p>But I cannot wrap my mind around this... Anyone?</p> <p>Thanks!</p>
[ { "answer_id": 74663929, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": false, "text": "call printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n return\n (test still = 1 in this frame)\n print 1n\n return\n (test still = 2 in this frame)\n print 2n\n return\n (test still = 3 in this frame)\n print 3n\n return\n printFun" }, { "answer_id": 74663937, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 0, "selected": false, "text": "printFun def foo():\n print(\"before\")\n other_foo()\n print(\"after\")\n other_foo def printFun1():\n print(\"1a\")\n print(\"1n\")\n\n\ndef printFun2():\n print(\"2a\")\n printFun1() # it prints \"1a\" and \"1n\" between \"2a\" and \"2n\"\n print(\"2n\")\n\n\ndef printFun3():\n print(\"3a\")\n printFun2()\n print(\"3n\")\n\nprintFun3()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12561894/" ]
74,663,867
<pre><code>favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f&quot;I dont agree with your favorite food {name.title()}.&quot;) for food in (favorite_foods.values()): print(f&quot;{food.title()} is delicious, but not that good!&quot;) if food in (favorite_foods.values() endswith(s) print(f&quot;{food.title()} are delicous, but not that good!&quot;) </code></pre> <p>How do I loop through this dictionary correctly?</p> <p>I want it to say</p> <p>I dont agree with your favorite food Bill. Cake is delicious but not that good!</p> <p>I dont agree with your favorite food Alex. Patacones are delicious, but not that good!</p> <p>I appreciate all the help. Thank you.</p> <p>The code cycles through all of the values instead of stopping after one. I googled the endswith function to see if I could get the code to print something different if the value ended in 's' but it didnt work. Before I added that line it printed the following.</p> <p>I dont agree with your favorite food Bill. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I dont agree with your favorite food Alex. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good!</p> <p>I wanted to find a way to trigger &quot;are&quot; when the value was plural and &quot;is&quot; if the value was singular.</p>
[ { "answer_id": 74663929, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": false, "text": "call printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n return\n (test still = 1 in this frame)\n print 1n\n return\n (test still = 2 in this frame)\n print 2n\n return\n (test still = 3 in this frame)\n print 3n\n return\n printFun" }, { "answer_id": 74663937, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 0, "selected": false, "text": "printFun def foo():\n print(\"before\")\n other_foo()\n print(\"after\")\n other_foo def printFun1():\n print(\"1a\")\n print(\"1n\")\n\n\ndef printFun2():\n print(\"2a\")\n printFun1() # it prints \"1a\" and \"1n\" between \"2a\" and \"2n\"\n print(\"2n\")\n\n\ndef printFun3():\n print(\"3a\")\n printFun2()\n print(\"3n\")\n\nprintFun3()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19747142/" ]
74,663,887
<p>I have an event in my discord bot that sends an embed to welcome a member when the join the guild. No errors are produced but the event does not seem to work for me.</p> <p>Here is the code for the event:</p> <pre><code>@bot.event async def on_member_join(member): &quot;&quot;&quot; The code in this event is executed every time a member joins the server &quot;&quot;&quot; embed = discord.embed(title=f'Welcome to {member.guild.name}', description=f'{member.mention}, welcome to the server! \nMake sure to checkout the rules first. Enjoy your stay &lt;3', color=0x0061ff) if member.guild.icon is not None: embed.set_thumbnail( url=member.guild.icon.url ) await bot.get_channel(1047615507995562014).send(embed=embed) </code></pre> <p>I'm also using the following intents as well and have enabled them properly so I know that is not the issue with my code.</p> <pre><code>intents = discord.Intents.all() intents.members = True </code></pre>
[ { "answer_id": 74663929, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": false, "text": "call printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n return\n (test still = 1 in this frame)\n print 1n\n return\n (test still = 2 in this frame)\n print 2n\n return\n (test still = 3 in this frame)\n print 3n\n return\n printFun" }, { "answer_id": 74663937, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 0, "selected": false, "text": "printFun def foo():\n print(\"before\")\n other_foo()\n print(\"after\")\n other_foo def printFun1():\n print(\"1a\")\n print(\"1n\")\n\n\ndef printFun2():\n print(\"2a\")\n printFun1() # it prints \"1a\" and \"1n\" between \"2a\" and \"2n\"\n print(\"2n\")\n\n\ndef printFun3():\n print(\"3a\")\n printFun2()\n print(\"3n\")\n\nprintFun3()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20541671/" ]
74,663,905
<p>I'm trying to make a game which is spawning an object and after the object is destroyed, another object spawns right away. But right now I'm trying to destroy an instantiate object in a different function, and it is not working.</p> <p>`</p> <pre><code> public GameObject[] food; public Vector3Int spawnPosition; public void Start() { SpawnFood(); } //Spawning food public void SpawnFood() { int random = Random.Range(0, food.Length); GameObject clone = (GameObject)Instantiate(food[random], this.spawnPosition, Quaternion.identity); } private void Update() { if(Input.GetKeyDown(KeyCode.C)) { Destroy(this.gameObject); } } </code></pre> <p>`</p> <p>I have tried to do some research on this and still, I can only find the solution for destroying an object inside the same function as the Instantiate.</p>
[ { "answer_id": 74663929, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 2, "selected": false, "text": "call printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n return\n (test still = 1 in this frame)\n print 1n\n return\n (test still = 2 in this frame)\n print 2n\n return\n (test still = 3 in this frame)\n print 3n\n return\n printFun" }, { "answer_id": 74663937, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 0, "selected": false, "text": "printFun def foo():\n print(\"before\")\n other_foo()\n print(\"after\")\n other_foo def printFun1():\n print(\"1a\")\n print(\"1n\")\n\n\ndef printFun2():\n print(\"2a\")\n printFun1() # it prints \"1a\" and \"1n\" between \"2a\" and \"2n\"\n print(\"2n\")\n\n\ndef printFun3():\n print(\"3a\")\n printFun2()\n print(\"3n\")\n\nprintFun3()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866421/" ]
74,663,909
<p><a href="https://i.stack.imgur.com/EUqnd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EUqnd.png" alt="Example Pic:" /></a></p> <p>Hi, I got the solution with helper column. Can I get answer without helper column as shown in the picture. Thanks in advance..</p>
[ { "answer_id": 74664016, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "E2 LET =LET(teams, A2:A5, names, B2:B5, dropDownValue, D2,\n helper, SCAN(\"\", teams, LAMBDA(acc,tt, IF(acc=\"\", tt, IF(tt=\"\", acc, tt)))),\n FILTER(names, helper=dropDownValue)\n)\n =FILTER(B2:B5,SCAN(\"\",A2:A5,LAMBDA(acc,tt,IF(acc=\"\",tt,IF(tt=\"\",acc,tt))))=D2)\n SCAN FILTER D2 teams" }, { "answer_id": 74664155, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 2, "selected": false, "text": "SCAN() FILTER() =FILTER(D6:D17,SCAN(\"\",C6:C17,LAMBDA(a,b,IF(b=\"\",a&b,b)))=G6)\n SCAN()" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18605254/" ]
74,663,927
<p>I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples with each row in the original list, and then transform the tuples into a dictionary. Can I have some help filling out the blank parts of this code?</p> <p>mailing_list.csv:</p> <pre class="lang-none prettyprint-override"><code>uuid,username,email,subscribe_status 307919e9-d6f0-4ecf-9bef-c1320db8941a,afarrimond0,thartus0@reuters.com,opt-out 8743d75d-c62a-4bae-8990-3390fefbe5c7,tdelicate1,skinmond1@ca.gov,opt-out 68a32cae-847a-47c5-a77c-0d14ccf11e70,edelahuntyk,fglossup2@gmail.com,OPT-OUT a50bd76f-bc4d-4141-9b5d-3bfb9cb4c65d,tdelicate10,hpatel3@springer.com,active 26edd0b3-0040-4ba9-8c19-9b69d565df36,ogelder2,bissett4@mozilla.org,unsubscribed 5c96189f-95fe-4638-9753-081a6e1a82e8,bnornable3,aerrett5@over-blog.com,opt-out 480fb04a-d7cd-47c5-8079-b580cb14b4d9,csheraton4,pgatherell6@1.com,active d08649ee-62ae-4d1a-b578-fdde309bb721,tstodart5,schasmoor7@gmail.com,active 5772c293-c2a9-41ff-a8d3-6c666fc19d9a,mbaudino6,hpatel3@springer.com,unsubscribed 9e8fb253-d80d-47b5-8e1d-9a89b5bcc41b,paspling7,dandersen9@mozilla.org,active 055dff79-7d09-4194-95f2-48dd586b8bd7,mknapton8,vlewndenh@spiegel.de,active 5216dc65-05bb-4aba-a516-3c1317091471,ajelf9,kmacpaikei@purevolume.com,unsubscribed 41c30786-aa84-4d60-9879-0c53f8fad970,cgoodleyh,ccowlinj@hp.com,active 3fd55224-dbff-4c89-baec-629a3442d8f7,smcgonnelli,dcarragherk@gmail.com,opt-out 2ac17a63-a64b-42fc-8780-02c5549f23a7,mmayoralj,bparsissonl@domainmarket.com,unsubscribed </code></pre> <pre class="lang-py prettyprint-override"><code>import csv base_url = '../dataset/' def read_mailing_list_file(): with open('mailing_list.csv', 'r') as csv_file: hdr = csv.Sniffer().has_header(csv_file.read()) csv_file.seek(0) file_reader = csv.reader(csv_file) line_count = 0 mailing_list = [] if hdr: next(file_reader) for row in file_reader: mailing_list.append(row) line_count += 1 mailing_list_buffer = # Create another list variable that will be used as a temporary buffer to transform # our previous list into a dictionary, which is the data structure expected from the `update_mailing_list_extended` # function # Looping through the mailing list object for item in mailing_list: # Creating tuples with each row in the original list mailing_dict = # Transforming the list of tuples into a python dictionary </code></pre> <p>I am trying to transform a list of tuples into a dictionary.</p>
[ { "answer_id": 74664013, "author": "tdelaney", "author_id": 642070, "author_profile": "https://Stackoverflow.com/users/642070", "pm_score": 0, "selected": false, "text": "with open(\"mailing_list.csv\") as infile:\n with open(\"mailing_list_filtered.csv\", \"w\") as outfile:\n csv.writer(outfile).writerows(row for row in csv.reader(infile)\n if row[0] != \"unsubscribed\")\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20628914/" ]
74,663,930
<p>I'm trying to use a loop or an apply family solution for the next problem. I have few dataframes such as:</p> <pre><code>df1 &lt;- data.frame(a = c(1,2,3,NA,NA,NA,NA,NA,9,NA),b = c(1,2,3,4,NA,NA,NA,8,9,10),c = c(1,2,3,NA,NA,NA,7,8,NA,NA)) df2 &lt;- data.frame(a = c(1,2,3,4,5,6,NA,NA,NA,10),b = c(1,2,3,4,NA,NA,NA,8,9,10),c = c(1,2,3,NA,NA,NA,7,8,NA,NA)) df5 &lt;- data.frame(a = c(1,2,3,4,5,6,NA,NA,9,10),b = c(1,2,3,4,5,6,NA,8,9,10),c = c(1,2,3,NA,NA,NA,7,8,9,NA)) </code></pre> <p>where Im trying to use na.approx to fill in some NA gaps. What I had in mind is:</p> <pre><code>l &lt;- c(1,2,5) for (i in l){ df[[i]] &lt;- df[[i]] %&gt;% mutate(a = na.approx(a, na.rm = FALSE)) df[[i]] &lt;- df[[i]] %&gt;% mutate(b = na.approx(b, na.rm = FALSE)) df[[i]] &lt;- df[[i]] %&gt;% mutate(c = na.approx(c, na.rm = FALSE)) } </code></pre> <p>with this example Im getting the following error:</p> <pre><code>Error in UseMethod(&quot;mutate&quot;) : no applicable method for 'mutate' applied to an object of class &quot;c('double', 'numeric')&quot; </code></pre> <p>and with my actual data Im getting this error:</p> <pre><code>Error in `vectbl_as_col_location2()`: ! Can't extract columns past the end. i Location 13101 doesn't exist. i There are only 16 columns. </code></pre> <p>where &quot;13101&quot; would be part of a dataframe named &quot;df13101&quot;.</p> <p>When I check class of dataframes, I get</p> <pre><code>[1] &quot;data.frame&quot; </code></pre> <p>for the example but my actual dataframe I get</p> <pre><code>[1] &quot;grouped_df&quot; &quot;tbl_df&quot; &quot;tbl&quot; &quot;data.frame&quot; </code></pre> <p>and when I check the type of each variable I want to mutate all are numeric (example and real ones).</p> <p>I need to understand how to properly call these dataframes and what problems I could face because of the data class or the usage of mutate. I've tried using mapply but I'm very new to R and I'm barely learning about the whole apply family.</p> <p>Any help would be great, thanks for reading!</p>
[ { "answer_id": 74663965, "author": "Ronak Shah", "author_id": 3962914, "author_profile": "https://Stackoverflow.com/users/3962914", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(zoo)\n\nl <- c(1,2,5)\nlist_of_data <- mget(paste0('df', l))\n\nlist_of_data <- purrr::map(list_of_data, ~.x %>%\n mutate(across(where(is.numeric), \n ~na.approx(.x, na.rm = FALSE))))\n\nlist_of_data\n#$df1\n# a b c\n#1 1 1 1\n#2 2 2 2\n#3 3 3 3\n#4 4 4 4\n#5 5 5 5\n#6 6 6 6\n#7 7 7 7\n#8 8 8 8\n#9 9 9 NA\n#10 NA 10 NA\n\n#$df2\n# a b c\n#1 1 1 1\n#2 2 2 2\n#3 3 3 3\n#4 4 4 4\n#...\n#...\n list2env list2env(list_of_data, .GlobalEnv)\n" }, { "answer_id": 74666684, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "df[[1]] df1 df e df1 df1 e[[\"df1\"]] \"df1\" na.approx na.approx df1 df1 e <- ... e <- environment() e[[nm]] e nm na.approx na.approx library(zoo)\n\ne <- .GlobalEnv\nnms <- paste0(\"df\", l)\nfor (nm in nms) e[[nm]][] <- na.approx(e[[nm]], na.rm = FALSE)\n L L <- mget(nms) # nms defined above\nfor (nm in nms) L[[nm]][] <- na.approx(L[[nm]], na.rm = FALSE) \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7470388/" ]
74,663,961
<p>I am working on a module (scheduler). If I add scheduler and I select 2 or many tuesdays from current date to schedule my task. And It will show my task on scheduler for coming 2 or many tuesdays. How can I code this.</p> <p>To get 2 or many tuesdays from current date. C# or jquery</p> <p>I have seen many codes but these are not fulfilling my condition.</p> <p><code>Var date = new date()</code></p>
[ { "answer_id": 74663965, "author": "Ronak Shah", "author_id": 3962914, "author_profile": "https://Stackoverflow.com/users/3962914", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(zoo)\n\nl <- c(1,2,5)\nlist_of_data <- mget(paste0('df', l))\n\nlist_of_data <- purrr::map(list_of_data, ~.x %>%\n mutate(across(where(is.numeric), \n ~na.approx(.x, na.rm = FALSE))))\n\nlist_of_data\n#$df1\n# a b c\n#1 1 1 1\n#2 2 2 2\n#3 3 3 3\n#4 4 4 4\n#5 5 5 5\n#6 6 6 6\n#7 7 7 7\n#8 8 8 8\n#9 9 9 NA\n#10 NA 10 NA\n\n#$df2\n# a b c\n#1 1 1 1\n#2 2 2 2\n#3 3 3 3\n#4 4 4 4\n#...\n#...\n list2env list2env(list_of_data, .GlobalEnv)\n" }, { "answer_id": 74666684, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "df[[1]] df1 df e df1 df1 e[[\"df1\"]] \"df1\" na.approx na.approx df1 df1 e <- ... e <- environment() e[[nm]] e nm na.approx na.approx library(zoo)\n\ne <- .GlobalEnv\nnms <- paste0(\"df\", l)\nfor (nm in nms) e[[nm]][] <- na.approx(e[[nm]], na.rm = FALSE)\n L L <- mget(nms) # nms defined above\nfor (nm in nms) L[[nm]][] <- na.approx(L[[nm]], na.rm = FALSE) \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671762/" ]
74,663,990
<p>I have the following structure:</p> <pre><code>-- project/ | |-- Cargo.toml |-- Cargo.lock |-- src/ | |-- main.rs |-- crate1/ |-- lib.rs |-- Cargo.toml |-- tests |-- Cargo.toml |-- test.rs </code></pre> <p>and this are the content of the Cargo.toml</p> <pre class="lang-ini prettyprint-override"><code># Cargo.toml ... [workspace] members = [ &quot;crate1&quot;, &quot;tests&quot; ] ... </code></pre> <pre class="lang-ini prettyprint-override"><code># crate1/Cargo.toml [package] name = &quot;crate1&quot; ... [lib] path = &quot;lib.rs&quot; ... </code></pre> <p>here I'm using another lib for my tests, I don't think the problem is here, because I already used this way to do my tests several times, and it worked perfectly, but for some reason, now this is happening to me, I don't know if everything is a typo error of my self or not, but I already checked it a lot of times</p> <pre class="lang-ini prettyprint-override"><code># tests/Cargo.tom [package] name = &quot;tests&quot; version = &quot;0.1.0&quot; edition = &quot;2021&quot; publish = false [dev-dependencies] crate1 = { path = &quot;../crate1&quot; } [[test]] name = &quot;crate1_test&quot; path = &quot;crate1_test.rs&quot; [[test]] name = &quot;other_crate1_test&quot; path = &quot;other_crate1_test.rs&quot; </code></pre> <p>this is how one of the tests looks like</p> <pre class="lang-rs prettyprint-override"><code>// tests/crate1_test.rs use crate1::random_func; [test] fn random_func_test() { assert!(random_func()); } </code></pre> <p>And for some reason cargo don't recognize the &quot;crate1&quot; crate and throws me this error each time I import the crate:</p> <pre><code>error[E0433]: failed to resolve: use of undeclared crate or module `crate1` --&gt; tests/crate1_test.rs:1:5 | 1 | use crate1::random_func; | ^^^^^^ use of undeclared crate or module `crate1` For more information about this error, try `rustc --explain E0433`. error: could not compile `project-manager` due to previous error </code></pre>
[ { "answer_id": 74665352, "author": "user20673258", "author_id": 20673258, "author_profile": "https://Stackoverflow.com/users/20673258", "pm_score": -1, "selected": false, "text": "mod crate1; mod tests;" }, { "answer_id": 74669229, "author": "FRostri", "author_id": 13821672, "author_profile": "https://Stackoverflow.com/users/13821672", "pm_score": 0, "selected": false, "text": "crate1 Cargo.toml [package]\nname = \"project\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\nmembers = [\n \"crate1\",\n\n \"tests\"\n]\n\n[dependencies]\ncrate1 = { path = \"crate1\" }\nreqwest = \"0.11.13\"\ntokio = { version = \"1\", features = [\"full\"] }\n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13821672/" ]
74,663,995
<p>I am doing my first Python program and its Hangman game. I managed to make it work but as a part of the task I need to write &quot;best results -hall of fame&quot; table as json file. Each entry in the table should consist of name of the person and the result they achieved (number of tries before guessing a word). My idea is to use dictionary for that purpose and to append the result of each game to that same dictionary.</p> <p>My code goes like this:</p> <pre><code>with open(&quot;hall.json&quot;,&quot;a&quot;) as django: json.dump(hall_of_fame, django) </code></pre> <p>hall_of_fame is a dictionary where after playing a game the result is saved in the form of <code>{john:5}</code></p> <p>The problem I have is that after playing several games my .json file looks like this:</p> <pre><code>{john:5}{ana:7}{mary:3}{jim:1}{willie:6} </code></pre> <p>instead I want to get .json file to look like this:</p> <pre><code>{john:5,ana:7,mary:3,jim:1,willie:6} </code></pre> <p>What am I doing wrong? Can someone please take a look?</p>
[ { "answer_id": 74664069, "author": "nariman zaeim", "author_id": 15414112, "author_profile": "https://Stackoverflow.com/users/15414112", "pm_score": 2, "selected": true, "text": "with open (\"hall.json\") as f:\n dct=json.load(f)\n\n#add new item to dct\ndct.update(hall_of_fame)\n\n#write new dct to json file\nwith open(\"hall.json\",\"w\") as f:\n json.dump(dct,f)\n" }, { "answer_id": 74664563, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django)\n json.dump() import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74663995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671681/" ]
74,664,000
<p>I am trying to set up audit properties for each of my Entities with an abstract Base class</p> <pre><code>public abstract class Base { public bool IsActive { get; set; } public bool IsDeleted { get; set; } public int CreatedByUserId { get; set; } [ForeignKey(&quot;CreatedByUserId&quot;)] public virtual User CreatedBy { get; set; } public int ModifiedByUserId { get; set; } [ForeignKey(&quot;ModifiedByUserId&quot;)] public virtual User ModifiedBy { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } } </code></pre> <p>Somehow the Data Annotations doesn't work in EF Core but was working in my EF 6 Project I am now receiving this error:</p> <pre><code>Unable to determine the relationship represented by navigation 'Address.CreatedBy' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. </code></pre> <p>These are my models:</p> <pre><code>public class Address : Base { public int Id { get; set; } public string StringAddress { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } public int UserId { get; set; } public User User { get; set; } } public class User : Base { public int Id { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public string Email { get; set; } public string ContactNumber { get; set; } public string SecondaryContactNumber { get; set; } public int RoleId { get; set; } public Role Role { get; set; } public HashSet&lt;Address&gt; Addresses { get; set; } } </code></pre> <p>What's weird is when I remove the Base inheritance from my other entities apart from User, EF Core is able to set the FK without any errors.</p> <p>How do I configure it manually with Fluent API? I already have a BaseConfig class as starting point to be inherited by my other entity config classes:</p> <pre><code>public class BaseConfig&lt;TEntity&gt; : IEntityTypeConfiguration&lt;TEntity&gt; where TEntity : Base { public virtual void Configure(EntityTypeBuilder&lt;TEntity&gt; builder) { builder.Property(x =&gt; x.DateCreated).HasDefaultValueSql(&quot;GETDATE()&quot;); builder.Property(x =&gt; x.DateModified).HasDefaultValueSql(&quot;GETDATE()&quot;); // Am I setting this correctly? builder .HasOne(b =&gt; b.CreatedBy) .WithMany() .HasForeignKey(p =&gt; p.CreatedByUserId); } } </code></pre>
[ { "answer_id": 74664069, "author": "nariman zaeim", "author_id": 15414112, "author_profile": "https://Stackoverflow.com/users/15414112", "pm_score": 2, "selected": true, "text": "with open (\"hall.json\") as f:\n dct=json.load(f)\n\n#add new item to dct\ndct.update(hall_of_fame)\n\n#write new dct to json file\nwith open(\"hall.json\",\"w\") as f:\n json.dump(dct,f)\n" }, { "answer_id": 74664563, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django)\n json.dump() import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671332/" ]
74,664,001
<p>I'm working with the following table where you can get activity from customer purchases.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>DateOfActivity</th> <th>CustomerReference</th> <th>Reference Line</th> <th>Description</th> <th>Receivable Amount</th> </tr> </thead> <tbody> <tr> <td>24/10/2022</td> <td>CUST567</td> <td>1</td> <td>Credit Purchase</td> <td>20,000</td> </tr> <tr> <td>24/10/2022</td> <td>CUST567</td> <td>4</td> <td>Credit Purchase</td> <td>10,000</td> </tr> <tr> <td>24/10/2022</td> <td>CUST555</td> <td>2</td> <td>Credit Purchase</td> <td>50,000</td> </tr> <tr> <td>27/10/2022</td> <td>CUST555</td> <td>2</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>27/10/2022</td> <td>CUST567</td> <td>4</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>27/10/2022</td> <td>CUST567</td> <td>1</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>27/10/2022</td> <td>CUST567</td> <td>4</td> <td>Repayment</td> <td>-3,500</td> </tr> <tr> <td>27/10/2022</td> <td>CUST567</td> <td>4</td> <td>Repayment</td> <td>-6,500</td> </tr> <tr> <td>13/11/2022</td> <td>CUST567</td> <td>1</td> <td>Repayment</td> <td>-10,000</td> </tr> <tr> <td>13/11/2022</td> <td>CUST567</td> <td>1</td> <td>Repayment</td> <td>-2,000</td> </tr> <tr> <td>18/11/2022</td> <td>CUST567</td> <td>1</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>18/11/2022</td> <td>CUST567</td> <td>1</td> <td>Repayment</td> <td>-3,000</td> </tr> </tbody> </table> </div> <p>I'm using the following query to extract the above table:</p> <pre><code>Select DateOfActivity, CustomerReferencce, ReferenceLine, Description, ReceivableAmount From 'Table A' Where DateOfActivity &gt;= '2022-09-01' Group by DateOfActivity </code></pre> <p>As you can see that the table will only get bigger because more customer activity is being added. How can I change my query so the customers who have fully paid their receivable amount don't show up in this table?</p> <p>The result from above script change that I am expecting is as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>DateOfActivity</th> <th>CustomerReference</th> <th>Reference Line</th> <th>Description</th> <th>Receivable Amount</th> </tr> </thead> <tbody> <tr> <td>24/10/2022</td> <td>CUST567</td> <td>1</td> <td>Credit Purchase</td> <td>20,000</td> </tr> <tr> <td>24/10/2022</td> <td>CUST555</td> <td>2</td> <td>Credit Purchase</td> <td>50,000</td> </tr> <tr> <td>27/10/2022</td> <td>CUST555</td> <td>2</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>27/10/2022</td> <td>CUST567</td> <td>1</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>13/11/2022</td> <td>CUST567</td> <td>1</td> <td>Repayment</td> <td>-10,000</td> </tr> <tr> <td>13/11/2022</td> <td>CUST567</td> <td>1</td> <td>Repayment</td> <td>-2,000</td> </tr> <tr> <td>18/11/2022</td> <td>CUST567</td> <td>1</td> <td>Contract Sign</td> <td>0</td> </tr> <tr> <td>18/11/2022</td> <td>CUST567</td> <td>1</td> <td>Repayment</td> <td>-3,000</td> </tr> </tbody> </table> </div> <p><strong>CUST567 Reference Line 4</strong> has been removed because the sum of his Credit Purchase + Contract Sign + Repayment = $0. All other Customers rows are still showing up.</p> <p>How can edit the query so this is done automatically for Large data? Please note the following assumptions:</p> <ul> <li><p>Customer Reference for multiple customers can be same or different (for example in above example, CUST567 has two Reference Line 1 &amp; 4. However, CUST555 only has one reference Line 2.</p> </li> <li><p>The data is removed for Customers based on Receivable amount coming down to Nil (so all rows for that CustomerReference &amp; Reference Line are removed)</p> </li> </ul> <p>Thanks in Advance</p>
[ { "answer_id": 74664069, "author": "nariman zaeim", "author_id": 15414112, "author_profile": "https://Stackoverflow.com/users/15414112", "pm_score": 2, "selected": true, "text": "with open (\"hall.json\") as f:\n dct=json.load(f)\n\n#add new item to dct\ndct.update(hall_of_fame)\n\n#write new dct to json file\nwith open(\"hall.json\",\"w\") as f:\n json.dump(dct,f)\n" }, { "answer_id": 74664563, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django)\n json.dump() import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20578634/" ]
74,664,014
<p>I have a table or data like this</p> <p><a href="https://i.stack.imgur.com/ZHn0G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHn0G.png" alt="enter image description here" /></a></p> <p>This data has a same invoice number, so I want to show table only one column using case or pivot. The result that I want is like this</p> <p><a href="https://i.stack.imgur.com/0z3yO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0z3yO.png" alt="enter image description here" /></a></p> <p>Can you help me about this ?</p>
[ { "answer_id": 74664069, "author": "nariman zaeim", "author_id": 15414112, "author_profile": "https://Stackoverflow.com/users/15414112", "pm_score": 2, "selected": true, "text": "with open (\"hall.json\") as f:\n dct=json.load(f)\n\n#add new item to dct\ndct.update(hall_of_fame)\n\n#write new dct to json file\nwith open(\"hall.json\",\"w\") as f:\n json.dump(dct,f)\n" }, { "answer_id": 74664563, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django)\n json.dump() import json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20328169/" ]
74,664,018
<p>In Rust, we can create a Vector with macro <code>vec![]</code>.</p> <pre><code>let numbers = vec![1, 2, 3]; </code></pre> <p>Is there any similar macro that allow us to create a <code>HashSet</code>?</p> <p>From the doc <a href="https://doc.rust-lang.org/std/collections/struct.HashSet.html" rel="nofollow noreferrer">https://doc.rust-lang.org/std/collections/struct.HashSet.html</a>, I notice that we have <code>HashSet::from</code>:</p> <pre><code>let viking_names = HashSet::from([&quot;Einar&quot;, &quot;Olaf&quot;, &quot;Harald&quot;]); </code></pre> <p>However, that requires us to create an array first, which seems a bit wasteful.</p>
[ { "answer_id": 74666214, "author": "Caesar", "author_id": 401059, "author_profile": "https://Stackoverflow.com/users/401059", "pm_score": 1, "selected": false, "text": "HashSet static" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1035008/" ]
74,664,022
<p>I am passing a decimal value from C# to a SQL Server stored procedure.</p> <p>The parameter in the stored procedure is defined as <code>@latitude decimal</code>. Right before going into the stored procedure, the value is 25.631230</p> <p>When running the profiler I can see that SQL Server sees the value as: 25.631229999999999</p> <p>This is obviously a much different value when you are dealing with longitude/latitude.</p> <pre><code>SqlParameter lat = new SqlParameter { SqlDbType = System.Data.SqlDbType.Decimal, Value = 25.631230, ParameterName = &quot;@latitude&quot; }; cmd.Parameters.Add(lat); cmd.CommandText = storedProcName; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.ExecuteReader() </code></pre> <p>Hope it's just a setting somewhere ;)</p>
[ { "answer_id": 74664721, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": -1, "selected": false, "text": "decimal(38, 18)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2125182/" ]
74,664,085
<p>Im using a TMDB API to search for movies and add them to a watchlist.</p> <p>In this javascript function im getting movie details based on user input and rendering the results to html using bootstrap.</p> <pre><code>const searchMovie = async (searchInput) =&gt; { try { axios.get(`https://api.themoviedb.org/3/search/movie?api_key={API_KEY}&amp;language=en-US&amp;query=${searchInput}&amp;page=1&amp;include_adult=false `) .then((response) =&gt; { console.log(response); let movies = response.data.results; let displayMovies = ''; $.each(movies, (index, movie) =&gt; { displayMovies += ` &lt;div class=&quot;col-md-3&quot;&gt; &lt;div class=&quot;well text-center&quot;&gt; &lt;a href=&quot;https://www.themoviedb.org/movie/${movie.movie_id} target=&quot;_blank&quot;&gt;&lt;img src=&quot;https://image.tmdb.org/t/p/original${movie.poster_path}&quot;&gt;&lt;/a&gt; &lt;h5&gt;${movie.title}&lt;/h5&gt; &lt;h4&gt;${movie.release_date}&lt;h4&gt; &lt;a class=&quot;btn btn-primary&quot; href=&quot;#&quot;&gt;Add to watchlist&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; `; }); $('#movies').html(displayMovies); }) }catch(error) { console.log(error) } } </code></pre> <p>I have another html file called <strong>watchlist.html</strong> that i want to send the movie selected from the search results to that file and build a watchlist.</p>
[ { "answer_id": 74664721, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": -1, "selected": false, "text": "decimal(38, 18)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18881995/" ]
74,664,098
<p>I am trying to make a call to an API and then grab event_ids from the data. I then want to use those event ids as variables in another request, then parse that data. Then loop back and make another request using the next event id in the event_id variable for all the IDs.</p> <p>so far i have the following</p> <pre><code>def nba_odds(): url = &quot;https://xxxxx.com.au/sports/summary/basketball?api_key=xxxxx&quot; response = requests.get(url) data = response.json() event_ids = [] for event in data['Events']: if event['Country'] == 'USA' and event['League'] == 'NBA': event_ids.append(event['EventID']) # print(event_ids) game_url = f'https://xxxxx.com.au/sports/detail/{event_ids}?api_key=xxxxx' game_response = requests.get(game_url) game_data = game_response.json() print(game_url) </code></pre> <p>that gives me the result below in the terminal.</p> <blockquote> <p><a href="https://xxxxx.com.au/sports/detail/%5B%27dbx-1425135%27" rel="nofollow noreferrer">https://xxxxx.com.au/sports/detail/['dbx-1425135'</a>, 'dbx-1425133', 'dbx-1425134', 'dbx-1425136', 'dbx-1425137', 'dbx-1425138', 'dbx-1425139', 'dbx-1425140', 'anyvsany-nba01-1670043600000000000', 'dbx-1425141', 'dbx-1425142', 'dbx-1425143', 'dbx-1425144', 'dbx-1425145', 'dbx-1425148', 'dbx-1425149', 'dbx-1425147', 'dbx-1425146', 'dbx-1425150', 'e95270f6-661b-46dc-80b9-cd1af75d38fb', '0c989be7-0802-4683-8bb2-d26569e6dcf9']?api_key=779ac51a-2fff-4ad6-8a3e-6a245a0a4cbb</p> </blockquote> <p>the URL above format should look like</p> <blockquote> <p><a href="https://xxxx.com.au/sports/detail/dbx-1425135" rel="nofollow noreferrer">https://xxxx.com.au/sports/detail/dbx-1425135</a></p> </blockquote> <p>If anyone can point me in the right direction it would be appreciated.</p> <p>thanks.</p>
[ { "answer_id": 74664721, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": -1, "selected": false, "text": "decimal(38, 18)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19124338/" ]
74,664,129
<p>So far I am not able to properly integrate xterm.js with reactjs due to which my code breaks in production but works while development. i need a proper way of importing xterm.js in component.</p> <p>HELP !!!</p> <pre><code>import React, {useEffect} from 'react'; import {Terminal} from 'xterm'; import {FitAddon} from 'xterm-addon-fit'; const UITerminal = () =&gt; { const term = new Terminal(); const fitAddon = new FitAddon(); term.loadAddon(fitAddon); useEffect(() =&gt; { let termDocument = document.getElementById('terminal') if (termDocument) { term.open(termDocument) fitaddon.fit(); } window.addEventListener('resize', () =&gt; { fitaddon.fit(); }) }, []) return (&lt;div id=&quot;terminal&quot;&gt;&lt;/div&gt;) } </code></pre> <p>Below is the error response from production code. clearly it fails to import xterm</p> <pre><code>react_devtools_backend.js:4012 ReferenceError: Cannot access 'r' before initialization at new m (96209.72626fc1cc862aea477a.bundle.js:1:165467) at new b (96209.72626fc1cc862aea477a.bundle.js:1:159758) at new M (96209.72626fc1cc862aea477a.bundle.js:1:57572) at new r.exports.i.Terminal (96209.72626fc1cc862aea477a.bundle.js:1:294972) at w (96209.72626fc1cc862aea477a.bundle.js:1:15994) at zo (main.71e827eabc798023c129.bundle.js:1:1260000) at Ws (main.71e827eabc798023c129.bundle.js:1:1333492) at Wi (main.71e827eabc798023c129.bundle.js:1:1294411) at Ui (main.71e827eabc798023c129.bundle.js:1:1294336) at Pi (main.71e827eabc798023c129.bundle.js:1:1291367) </code></pre>
[ { "answer_id": 74664721, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": -1, "selected": false, "text": "decimal(38, 18)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18295651/" ]
74,664,150
<p>I'm creating a clone array from an array that contain some empty slots. But after cloning it is being replaced with <code>undefined</code>. If the source array contain some empty slots then clone array should also contain same number and at exact same position empty slots. I don't get the reason. I'm using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="nofollow noreferrer"><code>spread syntax</code></a> to clone array as:</p> <pre><code>const arr = [1, &quot;&quot;, , null, undefined, false, , 0]; console.log('arr =&gt; ', arr); const clone = [...arr]; console.log('clone =&gt; ', clone) </code></pre> <p>Output is as below in chrome console</p> <p><a href="https://i.stack.imgur.com/86CDP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/86CDP.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74664171, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 3, "selected": true, "text": "a. Let index be 0.\nb. Repeat\n Let len be ? LengthOfArrayLike(array).\n iii. If index ≥ len, return NormalCompletion(undefined).\n (...)\n 1. Let elementKey be ! ToString((index)).\n 2. Let elementValue be ? Get(array, elementKey).\n (yield elementValue)\n vi. Set index to index + 1.\n const arr = [];\narr[5] = 'a';\nconsole.log(arr.length); arr[0]\narr[1]\narr[2]\n// ...\narr[arr.length - 1]\n arr.length - 1 const arr = [1, \"\", , null, undefined, false, , 0];\nconsole.log('arr => ', arr);\n\nconst clone = [];\nfor (let i = 0; i < arr.length; i++) {\n if (arr.hasOwnProperty(i)) {\n clone[i] = arr[i];\n }\n}\nconsole.log('clone => ', clone)" }, { "answer_id": 74664201, "author": "busaud", "author_id": 5326642, "author_profile": "https://Stackoverflow.com/users/5326642", "pm_score": 1, "selected": false, "text": "let x;\nconsole.log(x); // undefined\nconsole.log(typeof x); // undefined\n let x = [,]; // even [] would work but I thought this one is clearer for some\nconsole.log(x[0]); // undefined\nconsole.log(typeof x[0]); //undefined\n" }, { "answer_id": 74664757, "author": "Suhail Qureshi", "author_id": 20308649, "author_profile": "https://Stackoverflow.com/users/20308649", "pm_score": 0, "selected": false, "text": "arr[2] undefined arr[2] undefiend" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9153448/" ]
74,664,156
<p>I'm trying to build a basic terminal that performs basic operations in python. I have made all the main functions, but the cd function isn't working to change my current directory.</p> <p>I suspect that the problem is in the way I store my current directory file. Perhaps I need to store it as variable instead of using function.</p> <p>This is the code.</p> <pre><code>##################################### # import modules. # pwd - view the current folder function. # ls - list files in a folder function. # touch (filename) - create new empty file function. # rm (filename) - delete a file function. # cd - go to another folder function. # cat (filename) - display the contents of a file function. ###################################### import os import pathlib from os.path import join path = os.getcwd() # DONE def ls(): os.listdir(path) print(os.listdir(path)) def pwd(): print(os.getcwd()) def touch(file_name): fp = open(join(path, file_name), 'a') fp.close() def rm(file_name): file = pathlib.Path(join(path, file_name)) file.unlink() def cd(file_name): os.chdir(join(path, file_name)) while True &lt; 100: dirName = input() cmd = dirName.split(&quot; &quot;)[0] if cmd == &quot;ls&quot;: ls() elif cmd == &quot;pwd&quot;: pwd() elif cmd == &quot;cd&quot;: file_name = dirName.split(&quot; &quot;)[1] cd(file_name) print(os.getcwd()) elif cmd == &quot;touch&quot;: file_name = dirName.split(&quot; &quot;)[1] touch(file_name) elif cmd == &quot;rm&quot;: file_name = dirName.split(&quot; &quot;)[1] rm(file_name) elif cmd == 'cd': # file_name = dirName.split(&quot; &quot;)[1] cd(file_name) print(pwd(file_name)) else: print(&quot;Command not found!&quot;) </code></pre> <p>I tired to change directory using the cd function in my custom terminal, but it's not working. It is expected that cd function to work correctly.</p>
[ { "answer_id": 74664171, "author": "CertainPerformance", "author_id": 9515207, "author_profile": "https://Stackoverflow.com/users/9515207", "pm_score": 3, "selected": true, "text": "a. Let index be 0.\nb. Repeat\n Let len be ? LengthOfArrayLike(array).\n iii. If index ≥ len, return NormalCompletion(undefined).\n (...)\n 1. Let elementKey be ! ToString((index)).\n 2. Let elementValue be ? Get(array, elementKey).\n (yield elementValue)\n vi. Set index to index + 1.\n const arr = [];\narr[5] = 'a';\nconsole.log(arr.length); arr[0]\narr[1]\narr[2]\n// ...\narr[arr.length - 1]\n arr.length - 1 const arr = [1, \"\", , null, undefined, false, , 0];\nconsole.log('arr => ', arr);\n\nconst clone = [];\nfor (let i = 0; i < arr.length; i++) {\n if (arr.hasOwnProperty(i)) {\n clone[i] = arr[i];\n }\n}\nconsole.log('clone => ', clone)" }, { "answer_id": 74664201, "author": "busaud", "author_id": 5326642, "author_profile": "https://Stackoverflow.com/users/5326642", "pm_score": 1, "selected": false, "text": "let x;\nconsole.log(x); // undefined\nconsole.log(typeof x); // undefined\n let x = [,]; // even [] would work but I thought this one is clearer for some\nconsole.log(x[0]); // undefined\nconsole.log(typeof x[0]); //undefined\n" }, { "answer_id": 74664757, "author": "Suhail Qureshi", "author_id": 20308649, "author_profile": "https://Stackoverflow.com/users/20308649", "pm_score": 0, "selected": false, "text": "arr[2] undefined arr[2] undefiend" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19522375/" ]
74,664,167
<p>I have a piece of code that contains two functions <code>reverse()</code> that reverses an input list and <code>rotate()</code> that puts the last element to the start of the first.</p> <p>Now I am given another list, in the function <code>public int minimumOps(List&lt;Integer&gt; a, List&lt;Integer&gt; b)</code> which contains the same elements as the original list but in different order. I am trying to find how many times <code>reverse()</code> and/or <code>rotate()</code> must be called for the new list to be converted back into the original list. For instance, consider <code>S = [1, 2, 3, 4]</code> and <code>T = [2, 1, 4, 3]</code>, we can see that</p> <pre><code>T = rotate(rotate(reverse(S))) gives us the output </code></pre> <p>But this is not the only way to transform S to T. To illustrate, here are some other sequence of operations:</p> <pre><code>T = reverse(rotate(rotate(S))) T = rotate(rotate(rotate(reverse(rotate(S))))) T = reverse(rotate(rotate(reverse(reverse(S)))))) </code></pre> <p>Our goal in this problem is to find the smallest number of operations to achieve this transformation.</p> <p>I cannot figure out how to solve this problem. Here is what I have so far:</p> <pre><code>public int minimumOps(List&lt;Integer&gt; a, List&lt;Integer&gt; b) { int count = 0; for (int x = 0; x &lt; a.size(); x++){ if (Objects.equals(a.get(x), b.get(x))){ count += 0; } else{ while(!Objects.equals(a.get(x),b.get(x))){ reverse(b); rotate(b); count++; } } } return count; } public static List&lt;Integer&gt; rotate(List&lt;Integer&gt; l) { List&lt;Integer&gt; li = new ArrayList&lt;Integer&gt;(); li.add(l.get(l.size() - 1)); for (int i = 0; i &lt; l.size() - 1; i++) { li.add(l.get(i)); } return li; } public static List&lt;Integer&gt; reverse(List&lt;Integer&gt; l) { List&lt;Integer&gt; li = new ArrayList&lt;Integer&gt;(); for (int i = l.size() - 1; i &gt;= 0; i--) { li.add(l.get(i)); } return li; } </code></pre> <p>Any ideas on how to approach or solve the <code>minimumOps(a,b)</code> and find the number of <code>rotate()</code> and/or <code>reverse()</code> needed to turn list b into list a would be greatly appreciated</p>
[ { "answer_id": 74664197, "author": "Mason", "author_id": 10941378, "author_profile": "https://Stackoverflow.com/users/10941378", "pm_score": -1, "selected": false, "text": "public int minimumOps(List<Integer> a, List<Integer> b) {\n// Check if the lists are already equal\nif (a.equals(b)) {\n return 0;\n}\n\n// Perform the reverse operation on b\nList<Integer> reversedB = reverse(b);\nif (a.equals(reversedB)) {\n // If the reverse operation produces a matching list, return 1\n return 1;\n}\n\n// If the reverse operation did not produce a matching list, perform the rotate operation repeatedly\nint count = 0;\nwhile (!a.equals(b)) {\n b = rotate(b);\n count++;\n}\n\n// Return the number of rotate operations needed\nreturn count;\n}\n" }, { "answer_id": 74666204, "author": "Mr.Typo", "author_id": 14790684, "author_profile": "https://Stackoverflow.com/users/14790684", "pm_score": 3, "selected": true, "text": "import java.util.*;\n\nclass Main {\n public static void main(String[] args) {\n var a = new ArrayList<>(List.of(1, 2, 3, 4));\n var b = new ArrayList<>(List.of(2, 1, 4, 3));\n var output = minimumOps(a, b);\n if (output == Integer.MAX_VALUE) System.out.println(\"Can't be solved\");\n else System.out.println(\"Min transforms: \"+output); \n }\n\n /*\n let's draw operations tree, that is, for each list we can either reverse (rev) or rotate (rot)\n a\n |\n / \\\n rev rot\n / \\ / \\\n rev rot rev rot\n / \\ / \\ / \\ / \\\n ⋮ ⋮ ⋮ ⋮\n\n we know that reverse(reverse(list)) == list, so we can prune rev if its parent is rev.\n\n a\n |\n / \\\n rev rot\n | / \\\n rot rev rot\n / \\ | / \\\n ⋮ ⋮ ⋮\n\n now let's apply this 'blindly'.\n */\n public static int minimumOps(List<Integer> a, List<Integer> b) {\n if (Objects.equals(a, b)) return 0;\n\n // minimumOpsRec is a helper method that will be called recursively\n int revCount = minimumOpsRec(reverse(a), b, 1, OP.REV);\n int rotCount = minimumOpsRec(rotate(a), b, 1, OP.ROT);\n\n return Math.min(revCount, rotCount);\n }\n\n // a and b are lists that we are transforming,\n // count is our counter that will be incremented by each transform\n // parentOP is the previous operation from parent, i.e., rev or rot, see enum\n public static int minimumOpsRec(List<Integer> a, List<Integer> b, int count, OP parentOP) {\n if (Objects.equals(a, b)) return count; // base condition, return if a == b\n\n // however not all lists can be sorted using this algorithm, generally speaking,\n // if the output of this method greater than the list size then it's not sortable.\n // for example try to solve this using this algorithm by yourself (hint: you cannot): a = [1, 2, 3, 4], b = [4, 2, 1, 3]\n if (count > a.size()) return Integer.MAX_VALUE;\n\n count++;\n\n int rev = Integer.MAX_VALUE, rot;\n\n if (parentOP == OP.ROT) rev = minimumOpsRec(reverse(a), b, count, OP.REV);\n\n rot = minimumOpsRec(rotate(a), b, count, OP.ROT);\n\n return Math.min(rev, rot);\n }\n\n // don't mutate input\n private static List<Integer> rotate(List<Integer> list) {\n var newList = new ArrayList<>(list);\n Collections.rotate(newList, 1); // try using util methods as much as possible\n return newList;\n }\n\n // don't mutate input\n private static List<Integer> reverse(List<Integer> list) {\n var newList = new ArrayList<>(list);\n Collections.reverse(newList); // try using util methods as much as possible\n return newList;\n }\n\n enum OP {\n REV,\n ROT\n }\n}\n import java.util.*;\n\nclass Test2 {\n\n public static void main(String[] args) {\n var a = new ArrayList<>(List.of(1, 2, 3, 4));\n var b = new ArrayList<>(List.of(2, 1, 4, 3));\n System.out.println(minimumOps(a, b));\n }\n\n public static Map.Entry<Integer, List<OP>> minimumOps(List<Integer> a, List<Integer> b) {\n if (Objects.equals(a, b)) return new AbstractMap.SimpleEntry<>(0, new ArrayList<>());\n\n var rev = minimumOpsRec(reverse(a), b, 1, OP.REV);\n var rot = minimumOpsRec(rotate(a), b, 1, OP.ROT);\n\n return rot.getKey() >= rev.getKey() ? rev : rot;\n }\n\n public static Map.Entry<Integer, List<OP>> minimumOpsRec(List<Integer> a, List<Integer> b, int count, OP parent) {\n if (Objects.equals(a, b) || count > a.size())\n return new AbstractMap.SimpleEntry<>(count, new ArrayList<>(List.of(parent)));\n\n count++;\n \n Map.Entry<Integer, List<OP>> rev = null;\n Map.Entry<Integer, List<OP>> rot;\n \n if (parent == OP.ROT) rev = minimumOpsRec(reverse(a), b, count, OP.REV);\n \n rot = minimumOpsRec(rotate(a), b, count, OP.ROT);\n\n if (rev != null && rot.getKey() >= rev.getKey()) {\n rev.getValue().add(parent);\n return rev;\n }\n rot.getValue().add(parent);\n return rot;\n }\n\n // don't mutate input\n private static List<Integer> rotate(List<Integer> list) {\n var newList = new ArrayList<>(list);\n Collections.rotate(newList, 1); // try using util methods as much as possible\n return newList;\n }\n\n // don't mutate input\n private static List<Integer> reverse(List<Integer> list) {\n var newList = new ArrayList<>(list);\n Collections.reverse(newList); // try using util methods as much as possible\n return newList;\n }\n\n enum OP {\n REV,\n ROT\n }\n\n}\n class Test {\n public static void main(String[] args) {\n var a = new ArrayList<>(List.of(1, 2, 3, 4));\n var b = new ArrayList<>(List.of(2, 1, 4, 3));\n var output = minimumOps(a, b);\n if (output == Integer.MAX_VALUE) System.out.println(\"Can't be solved\");\n else System.out.println(\"Min transforms: \" + output);\n }\n\n public static int minimumOps(List<Integer> a, List<Integer> b) {\n return minimumOpsRec(a, b, 0);\n }\n\n public static int minimumOpsRec(List<Integer> a, List<Integer> b, int count) {\n if (Objects.equals(a, b)) return count;\n if (count > a.size()) return Integer.MAX_VALUE;\n count++;\n return Math.min(minimumOpsRec(reverse(a), b, count), minimumOpsRec(rotate(a), b, count));\n }\n\n private static List<Integer> rotate(List<Integer> list) {\n var newList = new ArrayList<>(list);\n Collections.rotate(newList, 1);\n return newList;\n }\n\n private static List<Integer> reverse(List<Integer> list) {\n var newList = new ArrayList<>(list);\n Collections.reverse(newList);\n return newList;\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18984687/" ]
74,664,203
<p>I installed python but didn't work. Then all of the following but when, I was supposed to import the following it didn't work.</p> <pre class="lang-html prettyprint-override"><code>!pip install -U pip !pip install tensorflow from tensorflow import keras from tensorflow.keras import layers </code></pre>
[ { "answer_id": 74664550, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "pip freeze pip install tensorflow" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16366732/" ]