qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,588,468
|
<p><a href="https://i.stack.imgur.com/gwSbH.png" rel="nofollow noreferrer">Image of code</a></p>
<p>With this i am not able to convert a string which cointains symbols like (+ , - , / , *) to double or integer .</p>
<p>I am expecting to get the answer as integer and all with all solving inputed in the string.</p>
<p>Your every effort is greatly appreciated , Thank you</p>
|
[
{
"answer_id": 74588711,
"author": "Hatem Darwish",
"author_id": 13634409,
"author_profile": "https://Stackoverflow.com/users/13634409",
"pm_score": -1,
"selected": false,
"text": "implementation 'io.apisense:rhino-android:1.1.1' \n Object result = null;\n\nScriptEngine engine = new ScriptEngineManager().getEngineByName(\"rhino\");\n\nif (engine == null) {\n throw new UnsupportedOperationException(\"JavaScript scripting engine not found\");\n}\ntry {\n result = engine.eval(\"5+5\"); // <- you can use mathematics operations\n} catch (Exception e) {\n Log.i(\"e\",e.toString());\n}\nLog.i(\"ResultData\" , result.toString()); // will be print (10)\ndouble val = Double.parseDouble(result.toString());\n"
},
{
"answer_id": 74588912,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": true,
"text": "public class Main {\n public static void main(String[] args) {\n String a = \"112 + 221\";\n double y = computeString(a);\n System.out.println(y);\n }\n\n public static double computeString(String a) {\n double y = 0;\n for (int i = 0; i < a.length(); i++) {\n // if the character is an operator\n if (a.charAt(i) == '+') {\n // get the first number before the operator and convert it to a double value\n // then assign it to the total value y\n // then get the second number after the operator and convert it to a double value\n // then add it to the total value y\n y = Double.parseDouble(a.substring(0, i)) + Double.parseDouble(a.substring(i + 2, a.length()));\n // first substring(0, i) gets the first number before the operator\n // second substring(i + 2) gets the second number after the operator\n }\n }\n return y;\n }\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20612557/"
] |
74,588,470
|
<p>I have data like this,</p>
<p><a href="https://i.stack.imgur.com/iZY6y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iZY6y.png" alt="enter image description here" /></a></p>
<p>and I need output like this</p>
<p><a href="https://i.stack.imgur.com/5OaKo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5OaKo.png" alt="enter image description here" /></a></p>
<p>How do I achieve this in Pyspark?</p>
|
[
{
"answer_id": 74588711,
"author": "Hatem Darwish",
"author_id": 13634409,
"author_profile": "https://Stackoverflow.com/users/13634409",
"pm_score": -1,
"selected": false,
"text": "implementation 'io.apisense:rhino-android:1.1.1' \n Object result = null;\n\nScriptEngine engine = new ScriptEngineManager().getEngineByName(\"rhino\");\n\nif (engine == null) {\n throw new UnsupportedOperationException(\"JavaScript scripting engine not found\");\n}\ntry {\n result = engine.eval(\"5+5\"); // <- you can use mathematics operations\n} catch (Exception e) {\n Log.i(\"e\",e.toString());\n}\nLog.i(\"ResultData\" , result.toString()); // will be print (10)\ndouble val = Double.parseDouble(result.toString());\n"
},
{
"answer_id": 74588912,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": true,
"text": "public class Main {\n public static void main(String[] args) {\n String a = \"112 + 221\";\n double y = computeString(a);\n System.out.println(y);\n }\n\n public static double computeString(String a) {\n double y = 0;\n for (int i = 0; i < a.length(); i++) {\n // if the character is an operator\n if (a.charAt(i) == '+') {\n // get the first number before the operator and convert it to a double value\n // then assign it to the total value y\n // then get the second number after the operator and convert it to a double value\n // then add it to the total value y\n y = Double.parseDouble(a.substring(0, i)) + Double.parseDouble(a.substring(i + 2, a.length()));\n // first substring(0, i) gets the first number before the operator\n // second substring(i + 2) gets the second number after the operator\n }\n }\n return y;\n }\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057692/"
] |
74,588,491
|
<p>I got stuck in my code ,
I am creating a dynamic form on age and put unobtrusive client-side validation.
validation is working but not working row-wise, its working like when I change first-row validation then
it removes other rows validation.</p>
<p>This is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function dob_police(){
var age = document.getElementById('p_age').value;
if(age < 20){
document.getElementById('wrong_dob_alert').style.color = 'red';
document.getElementById('wrong_dob_alert').innerHTML = 'Age must be 20 above';
}
else{
document.getElementById('wrong_dob_alert').style.color = 'green';
document.getElementById('wrong_dob_alert').innerHTML = '✓';
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
<label>Age</label>
<input type="number" class="form-control form-control-sm" id="p_age" name="age" required onkeyup="dob_police()" value="<?php echo $row['age']; ?>">
<small id="wrong_dob_alert"></small>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74588711,
"author": "Hatem Darwish",
"author_id": 13634409,
"author_profile": "https://Stackoverflow.com/users/13634409",
"pm_score": -1,
"selected": false,
"text": "implementation 'io.apisense:rhino-android:1.1.1' \n Object result = null;\n\nScriptEngine engine = new ScriptEngineManager().getEngineByName(\"rhino\");\n\nif (engine == null) {\n throw new UnsupportedOperationException(\"JavaScript scripting engine not found\");\n}\ntry {\n result = engine.eval(\"5+5\"); // <- you can use mathematics operations\n} catch (Exception e) {\n Log.i(\"e\",e.toString());\n}\nLog.i(\"ResultData\" , result.toString()); // will be print (10)\ndouble val = Double.parseDouble(result.toString());\n"
},
{
"answer_id": 74588912,
"author": "Yato",
"author_id": 11946373,
"author_profile": "https://Stackoverflow.com/users/11946373",
"pm_score": -1,
"selected": true,
"text": "public class Main {\n public static void main(String[] args) {\n String a = \"112 + 221\";\n double y = computeString(a);\n System.out.println(y);\n }\n\n public static double computeString(String a) {\n double y = 0;\n for (int i = 0; i < a.length(); i++) {\n // if the character is an operator\n if (a.charAt(i) == '+') {\n // get the first number before the operator and convert it to a double value\n // then assign it to the total value y\n // then get the second number after the operator and convert it to a double value\n // then add it to the total value y\n y = Double.parseDouble(a.substring(0, i)) + Double.parseDouble(a.substring(i + 2, a.length()));\n // first substring(0, i) gets the first number before the operator\n // second substring(i + 2) gets the second number after the operator\n }\n }\n return y;\n }\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598752/"
] |
74,588,498
|
<p>I have a string like "Hello world!".</p>
<p>At the finish I want to see like this: H e l l o w o r l d !</p>
<p>And <strong>ref</strong> element for every letter 1 2 3 4 5 6 7 8 9 10 11</p>
<pre><code> {"Hello world!".split(" ").map((word, index) => {
return (
<div
key={index}
className="
mr-4
flex
">
{word.split("").map((letter, i) => {
return (
<div
className="inline-block"
key={i}
ref={(el) => {
itemsRef.current[i] = el;
}}>
{letter}
</div>
);
})}
</div>
);
})}
</code></pre>
<p>Everything is working now, but the ref for letters looks like this: 1 2 3 4 5 1 2 3 4 5 6</p>
|
[
{
"answer_id": 74588539,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "itemsRef.current[index * word.length + i] = el;"
},
{
"answer_id": 74588558,
"author": "Alex Shtromberg",
"author_id": 4952402,
"author_profile": "https://Stackoverflow.com/users/4952402",
"pm_score": 0,
"selected": false,
"text": "itemsRef.current[itemsRef.current.length] = el\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3178479/"
] |
74,588,501
|
<p>There is a rather typical task of sorting two arrays simultaneously, assuming that same indexed elements of the arrays form virtual pairs, which are sorted. Such questions appear at least 10 years ago: <a href="https://stackoverflow.com/questions/9343846/boost-zip-iterator-and-stdsort">boost zip_iterator and std::sort</a></p>
<p>Now this task can be solved using <a href="https://github.com/ericniebler/range-v3" rel="noreferrer">range-v3</a> library:</p>
<pre><code>#include <array>
#include <range/v3/all.hpp>
int main() {
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
ranges::sort( ranges::views::zip( x, y ) );
// here x = {1,2,3,4}, y={'D','B','A','C'}
}
</code></pre>
<p>Online demo: <a href="https://gcc.godbolt.org/z/WGo4vGsx5" rel="noreferrer">https://gcc.godbolt.org/z/WGo4vGsx5</a></p>
<p>In C++23 <a href="https://en.cppreference.com/w/cpp/ranges/zip_view" rel="noreferrer">std::ranges::zip_view</a> appears, and my expectation was that the same program can be written using the standard library only:</p>
<pre><code>#include <array>
#include <ranges>
#include <algorithm>
int main() {
auto x = std::array{ 3, 2, 4, 1 };
auto y = std::array{'A', 'B', 'C', 'D'};
std::ranges::sort( std::views::zip( x, y ) );
}
</code></pre>
<p>Unfortunately, it results in long compilation errors. E.g. in GCC:</p>
<pre><code>...
/opt/compiler-explorer/gcc-trunk-20221127/include/c++/13.0.0/bits/ranges_algo.h:54:31: error: no matching function for call to '__invoke(std::ranges::less&, std::pair<int, char>&, std::pair<int&, char&>)'
54 | return std::__invoke(__comp,
| ~~~~~~~~~~~~~^~~~~~~~
55 | std::__invoke(__proj, std::forward<_TL>(__lhs)),
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56 | std::__invoke(__proj, std::forward<_TR>(__rhs)));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
</code></pre>
<p>Online demo: <a href="https://gcc.godbolt.org/z/47xrzM6ch" rel="noreferrer">https://gcc.godbolt.org/z/47xrzM6ch</a></p>
<p>Is it just because the implementations are not mature enough yet, or <code>zip</code> view in <code>C++23</code> will not help to sort two array?</p>
|
[
{
"answer_id": 74588733,
"author": "Ted Lyngmo",
"author_id": 7582247,
"author_profile": "https://Stackoverflow.com/users/7582247",
"pm_score": 4,
"selected": true,
"text": "std::ranges::sort(std::views::zip(x, y), [](auto&& a, auto&& b) {\n return std::tie(std::get<0>(a), std::get<1>(a)) < \n std::tie(std::get<0>(b), std::get<1>(b));\n});\n auto x = std::array{ 3, 2, 4, 1 };\nauto y = std::array{'A', 'B', 'C', 'D'};\nauto z = std::array{\"Z\", \"Y\", \"X\", \"W\"};\n\nstd::ranges::sort(std::views::zip(x, y, z));\n"
},
{
"answer_id": 74589292,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 1,
"selected": false,
"text": "std::ranges::sort( zipped_xy, []<typename T, typename U>(T a, U b) {\n std::cout << __PRETTY_FUNCTION__ << '\\t' << std::get<0>(a) << ':' << std::get<0>(b) << '\\n';\n return std::tuple{a} < std::tuple{b};\n});\n <lambda(T, U)> [with T = std::pair<int&, char&>; U = std::pair<int&, char&>] 2:3\n<lambda(T, U)> [with T = std::pair<int&, char&>; U = std::pair<int&, char&>] 4:2\n<lambda(T, U)> [with T = std::pair<int, char>; U = std::pair<int&, char&>] 4:3\n<lambda(T, U)> [with T = std::pair<int&, char&>; U = std::pair<int&, char&>] 7:2\n ⋮\n pair<int&, char&> pair<int, char> pair<int&, char&> zip_view tuple<Ts&...> tuple<Ts...> tuple<Ts&...> sort"
},
{
"answer_id": 74590636,
"author": "康桓瑋",
"author_id": 11638718,
"author_profile": "https://Stackoverflow.com/users/11638718",
"pm_score": 1,
"selected": false,
"text": "pair tuple ranges::sort(views::zip(x, y), {}, [](auto p) { return std::tuple(p); });\n pair<int&, char&> tuple<int&, char&> ranges::less value_type zip_view tuple zip_view pair value_type 2"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7325599/"
] |
74,588,520
|
<p>So i have written this code where i want the computer to open a file and write in it what the user have answered to the question i asked him but when ever i open the txt file its empty.</p>
<pre><code>import os
Welcome = input("Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO ")
def register():
name = input("First name: ")
last_name = input("Last name: ")
Email = input("Email: ")
ussername = input("Username: ")
password = input("Password: ")
def login():
ussername = input("Username: ")
password = input("Password: ")
if Welcome == "yes":
login()
else:
register()
if Welcome == "no" or "No":
with open("userinfo.txt", "w") as file:
file.write(register())
</code></pre>
|
[
{
"answer_id": 74588554,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 0,
"selected": false,
"text": "register() return f\"{name} {last_name}\"\n register() if Welcome == \"no\" or \"No\": if Welcome.lower() == \"no\":\n if Welcome == \"no\" or Welcome == \"No\":\n"
},
{
"answer_id": 74588582,
"author": "vignesh kanakavalli",
"author_id": 19092053,
"author_profile": "https://Stackoverflow.com/users/19092053",
"pm_score": 2,
"selected": true,
"text": "welcome = input(\"Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO \")\n\n\ndef register():\n first_name = input(\"First name: \")\n last_name = input(\"Last name: \")\n email = input(\"Email: \")\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n with open(\"userinfo.txt\", \"w\") as file:\n file.write(f\"{first_name}\\n{last_name}\\n{email}\\n{username}\\n{password}\")\n\n\ndef login():\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n\nif welcome.upper() == \"YES\":\n login()\n print(\"LOGGED IN!\")\nelif welcome.upper() == \"NO\":\n register()\n print(\"REGISTRATION SUCCESFULL!\")\nelse:\n print(\"WRONG INPUT!\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560156/"
] |
74,588,534
|
<p>I want to push my data (in <code>key:value</code> pair) into my Realtime Database. This is my code:</p>
<pre><code>DatabaseReference pay_details = database.getReference("pay/0/0/");
pay_details.push(
{
"Actual amount":arr.get(i).get(9),
"Current reading":arr.get(i).get(5),
"Employee":arr.get(i).get(1),
"Expected amount":arr.get(i).get(9),
"Installment":arr.get(i).get(10),
"Meter current date":arr.get(i).get(3),
"Meter previous date":arr.get(i).get(2),
"Previous reading":arr.get(i).get(4),
"Start from":arr.get(i).get(8),
"Total charge":arr.get(i).get(7),
"Type":arr.get(i).get(0),
"Unit consumed":arr.get(i).get(6)
}
);
</code></pre>
<p>This is my table structure:</p>
<p><img src="https://i.stack.imgur.com/X77uF.png" alt="Click here to view" /></p>
<p>I keep getting multiple syntax errors in the <code>push</code> section. Where am I going wrong?</p>
|
[
{
"answer_id": 74588554,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 0,
"selected": false,
"text": "register() return f\"{name} {last_name}\"\n register() if Welcome == \"no\" or \"No\": if Welcome.lower() == \"no\":\n if Welcome == \"no\" or Welcome == \"No\":\n"
},
{
"answer_id": 74588582,
"author": "vignesh kanakavalli",
"author_id": 19092053,
"author_profile": "https://Stackoverflow.com/users/19092053",
"pm_score": 2,
"selected": true,
"text": "welcome = input(\"Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO \")\n\n\ndef register():\n first_name = input(\"First name: \")\n last_name = input(\"Last name: \")\n email = input(\"Email: \")\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n with open(\"userinfo.txt\", \"w\") as file:\n file.write(f\"{first_name}\\n{last_name}\\n{email}\\n{username}\\n{password}\")\n\n\ndef login():\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n\nif welcome.upper() == \"YES\":\n login()\n print(\"LOGGED IN!\")\nelif welcome.upper() == \"NO\":\n register()\n print(\"REGISTRATION SUCCESFULL!\")\nelse:\n print(\"WRONG INPUT!\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,588,544
|
<p>I want to make my character jump by drawing lines.</p>
<p>But while my code is going towards the x-axis direction in 2D, when I switch to 3D, it always turns upwards regardless of the direction of the line. There is no change in the X-axis. My code is as follows:</p>
<pre class="lang-cs prettyprint-override"><code>if (other.gameObject.CompareTag("Line"))
{
rb.AddForce(Vector3.up * speed * Time.deltaTime, ForceMode.Impulse);
/ / Destroy(other.gameObject);
}
</code></pre>
<p>Could someone suggest how to correct my code?</p>
|
[
{
"answer_id": 74588554,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 0,
"selected": false,
"text": "register() return f\"{name} {last_name}\"\n register() if Welcome == \"no\" or \"No\": if Welcome.lower() == \"no\":\n if Welcome == \"no\" or Welcome == \"No\":\n"
},
{
"answer_id": 74588582,
"author": "vignesh kanakavalli",
"author_id": 19092053,
"author_profile": "https://Stackoverflow.com/users/19092053",
"pm_score": 2,
"selected": true,
"text": "welcome = input(\"Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO \")\n\n\ndef register():\n first_name = input(\"First name: \")\n last_name = input(\"Last name: \")\n email = input(\"Email: \")\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n with open(\"userinfo.txt\", \"w\") as file:\n file.write(f\"{first_name}\\n{last_name}\\n{email}\\n{username}\\n{password}\")\n\n\ndef login():\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n\nif welcome.upper() == \"YES\":\n login()\n print(\"LOGGED IN!\")\nelif welcome.upper() == \"NO\":\n register()\n print(\"REGISTRATION SUCCESFULL!\")\nelse:\n print(\"WRONG INPUT!\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198876/"
] |
74,588,595
|
<p>So I have the following table:</p>
<pre><code>Name Value
A 10
ABC 5
A 8
ABC 3
AB 2
</code></pre>
<p>And I want this result:</p>
<pre><code>Name Value
A 28
AB 10
ABC 8
</code></pre>
<p>So I don't want to group by exact match with Name, but by the starting characters. Is it possible?</p>
|
[
{
"answer_id": 74589011,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": -1,
"selected": false,
"text": "SELECT LEFT(\"Name\", \"value\") AS STRING, SUM(\"Value\") AS TOTAL\nFROM SoIHaveTheFollowingTable\n CROSS APPLY GENERATE_SERIES(1, CASE WHEN LEN(\"Name\") > 3 THEN 3 ELSE LEN(\"Name\") END)\nGROUP BY LEFT(\"Name\", \"value\")\nORDER BY STRING;\n"
},
{
"answer_id": 74589113,
"author": "Michael Krikorev",
"author_id": 1363190,
"author_profile": "https://Stackoverflow.com/users/1363190",
"pm_score": 0,
"selected": false,
"text": "UNION SELECT cat, SUM(val) num FROM (\n SELECT SUBSTRING(Name,1,1) cat, SUM(Value) val FROM table GROUP BY cat\n UNION ALL\n SELECT SUBSTRING(Name,1,2) cat, IF(LENGTH(Name)>1, SUM(Value), 0) val FROM table GROUP BY cat\n UNION ALL\n SELECT SUBSTRING(Name,1,3) cat, IF(LENGTH(Name)>2, SUM(Value), 0) val FROM table GROUP BY cat\n) a\nGROUP BY cat\nORDER BY cat\n IF +──────+─────+\n| cat | num |\n+──────+─────+\n| A | 28 |\n| AB | 10 |\n| ABC | 8 |\n+──────+─────+\n"
},
{
"answer_id": 74589446,
"author": "etsuhisa",
"author_id": 13841016,
"author_profile": "https://Stackoverflow.com/users/13841016",
"pm_score": 1,
"selected": true,
"text": "non-existent character data non-existent character data WITH cte as (\n SELECT SUBSTRING(Name,1,3) Name, SUM(Value) Value FROM Table1\n GROUP BY SUBSTRING(Name,1,3)\n UNION ALL\n SELECT SUBSTRING(Name,1,LEN(Name)-1), Value FROM cte\n WHERE LEN(Name)>1\n)\nSELECT Name, SUM(Value) FROM cte\nGROUP BY Name\nORDER BY Name\n non-existent character data WITH cte as (\n SELECT SUBSTRING(Name,1,3) Name, SUM(Value) Value FROM Table1\n GROUP BY SUBSTRING(Name,1,3)\n)\nSELECT\n t1.Name,\n SUM(t2.Value)\nFROM cte t1 JOIN cte t2\n ON t1.Name=SUBSTRING(t2.Name,1,LEN(t1.Name))\nGROUP BY t1.Name\nORDER BY t1.Name\n Name SUBSTRING(Name,1,3) Name"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11651728/"
] |
74,588,605
|
<p>I have eight screens. The first 7 screen has data to be sent to the last screen how do I go arouund this??</p>
<p>I tried passinng it through from one parent to another but that is too much work</p>
|
[
{
"answer_id": 74588750,
"author": "Amirali_Eric_J",
"author_id": 8388842,
"author_profile": "https://Stackoverflow.com/users/8388842",
"pm_score": 2,
"selected": false,
"text": "provider class ExpampleClass extends ChangeNotifier {\n\nString? _yourData;\n\nvoid setYourData(String? newData){\n_yourData = newData;\n notifyListeners();\n}\n\nString? get yourData => _yourData;\n\n}\n _yourData ExpampleClass Provider.of<ExpampleClass>(context, listen: false).yourData;\n Consumer Consumer<ExpampleClass>(\n builder: (context, exampleClassProvider ,snapshot) {\n return Text(exampleClassProvider!.yourData);\n }\n )\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13866959/"
] |
74,588,632
|
<p>I started writing web security in my application without WebSecurityConfigurerAdapter, I have used springboot3 internally which uses spring 6 with this set up I am getting errors like Cannot resolve method 'antMatchers' in 'ExpressionInterceptUrlRegistry' from the below code</p>
<pre><code>.authorizeRequests()
.antMatchers("/register").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
</code></pre>
<p><strong>Complete method</strong></p>
<pre><code> @Bean
protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/register").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
}
</code></pre>
|
[
{
"answer_id": 74610835,
"author": "Andreas Roither",
"author_id": 20631046,
"author_profile": "https://Stackoverflow.com/users/20631046",
"pm_score": 0,
"selected": false,
"text": ".antMatchers AuthorizationManagerRequestMatcherRegistry .requestMatchers(\"/register\") http.authorizeHttpRequests( auth ->\n auth\n .requestMatchers(.....)\n .anyRequest().authenticated()\n )\n"
},
{
"answer_id": 74618099,
"author": "Ali Habibian",
"author_id": 15199291,
"author_profile": "https://Stackoverflow.com/users/15199291",
"pm_score": 1,
"selected": false,
"text": ".antMatchers @Bean\nprotected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {\n http\n .cors()\n .and()\n .csrf()\n .disable()\n\n .authorizeHttpRequests( (auth) -> auth\n .requestMatchers(\"/register\").permitAll()\n .anyRequest().authenticated()\n )\n .httpBasic().and()\n .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354724/"
] |
74,588,655
|
<p>I am haviing issue in including file in php</p>
<pre><code>`<?php
include "../../db/db_connection.php";`
</code></pre>
<p>Error</p>
<pre><code>Warning: include(../../db/db_connection.php): Failed to open stream: No such file or directory in /var/www/html/practice/Blogs/actions/accounts/general.php on line 2
</code></pre>
<p>Here is my directories</p>
<p><img src="https://i.stack.imgur.com/TYqNz.png" alt="Image for my directories" /></p>
<p>I try to check it in terminal and the file is opened normally but giving error on the localhost</p>
|
[
{
"answer_id": 74610835,
"author": "Andreas Roither",
"author_id": 20631046,
"author_profile": "https://Stackoverflow.com/users/20631046",
"pm_score": 0,
"selected": false,
"text": ".antMatchers AuthorizationManagerRequestMatcherRegistry .requestMatchers(\"/register\") http.authorizeHttpRequests( auth ->\n auth\n .requestMatchers(.....)\n .anyRequest().authenticated()\n )\n"
},
{
"answer_id": 74618099,
"author": "Ali Habibian",
"author_id": 15199291,
"author_profile": "https://Stackoverflow.com/users/15199291",
"pm_score": 1,
"selected": false,
"text": ".antMatchers @Bean\nprotected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {\n http\n .cors()\n .and()\n .csrf()\n .disable()\n\n .authorizeHttpRequests( (auth) -> auth\n .requestMatchers(\"/register\").permitAll()\n .anyRequest().authenticated()\n )\n .httpBasic().and()\n .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18799908/"
] |
74,588,657
|
<p>Getting error in title whilst trying to make a table in Lua, as such:</p>
<pre><code>MyTable = {}
table.insert(MyTable, function MyFunction() end)
</code></pre>
<p>Any ideas on what is going on?</p>
<p>Thanks,
MakePrint0</p>
|
[
{
"answer_id": 74610835,
"author": "Andreas Roither",
"author_id": 20631046,
"author_profile": "https://Stackoverflow.com/users/20631046",
"pm_score": 0,
"selected": false,
"text": ".antMatchers AuthorizationManagerRequestMatcherRegistry .requestMatchers(\"/register\") http.authorizeHttpRequests( auth ->\n auth\n .requestMatchers(.....)\n .anyRequest().authenticated()\n )\n"
},
{
"answer_id": 74618099,
"author": "Ali Habibian",
"author_id": 15199291,
"author_profile": "https://Stackoverflow.com/users/15199291",
"pm_score": 1,
"selected": false,
"text": ".antMatchers @Bean\nprotected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {\n http\n .cors()\n .and()\n .csrf()\n .disable()\n\n .authorizeHttpRequests( (auth) -> auth\n .requestMatchers(\"/register\").permitAll()\n .anyRequest().authenticated()\n )\n .httpBasic().and()\n .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20612818/"
] |
74,588,659
|
<p>I want to only get complete words from acronyms with ( ) around them.</p>
<p>For example, there is a sentence
'Lung cancer screening (LCS) reduces NSCLC mortality';
->I want to get 'Lung cancer screening' as a result.</p>
<p>How can I do it with regex?</p>
<hr />
<p>original question:
I want to remove repeated upper alphabets :
"HIV acquired immunodeficiency syndrome are at a particularly high risk of cervical cancer" => " acquired immunodeficiency syndrome are at a particularly high risk of cervical cancer"</p>
|
[
{
"answer_id": 74610835,
"author": "Andreas Roither",
"author_id": 20631046,
"author_profile": "https://Stackoverflow.com/users/20631046",
"pm_score": 0,
"selected": false,
"text": ".antMatchers AuthorizationManagerRequestMatcherRegistry .requestMatchers(\"/register\") http.authorizeHttpRequests( auth ->\n auth\n .requestMatchers(.....)\n .anyRequest().authenticated()\n )\n"
},
{
"answer_id": 74618099,
"author": "Ali Habibian",
"author_id": 15199291,
"author_profile": "https://Stackoverflow.com/users/15199291",
"pm_score": 1,
"selected": false,
"text": ".antMatchers @Bean\nprotected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {\n http\n .cors()\n .and()\n .csrf()\n .disable()\n\n .authorizeHttpRequests( (auth) -> auth\n .requestMatchers(\"/register\").permitAll()\n .anyRequest().authenticated()\n )\n .httpBasic().and()\n .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)\n .and()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS);\n\n return http.build();\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19152563/"
] |
74,588,661
|
<p>I want to have a function that grabs something from an object; one of the function arguments is used as a key for that object. It seems like when an object has a dynamic property, keyof will not limit what a key is based on that property, but accepts all strings.</p>
<p>For example (a very simple one), this makes an object extractor that lets a user extract a value from an internal object by passing in a key of that object:</p>
<pre><code>function makeObjectExtractor(
keyA: string,
) {
const toExtractFrom = {
// keyA is dynamic; as a result, keyof allows for any string or number
[keyA]: 4,
keyB: 5
} satisfies Record<string, number>;
function getIncrementedVal(param: keyof typeof toExtractFrom) {
return toExtractFrom[param] + 1;
}
return getIncrementedVal;
}
const extractor = makeObjectExtractor('g');
// this should be flagged as a typescript error, but it isn't because keyA is dynamic
extractor('asdfasdf');
</code></pre>
<p>Is there a way for typescript to know here that only <code>g</code> and <code>keyB</code> are the allowed keys?</p>
<p>If I make all the keys hardcoded, this issue goes away, and keyof can only be a key of that object:</p>
<pre><code>function makeObjectExtractor(
) {
const toExtractFrom = {
// keyA is dynamic; as a result, keyof allows for any string or number
b: 4,
keyB: 5
} satisfies Record<string, number>;
function getIncrementedVal(param: keyof typeof toExtractFrom) {
return toExtractFrom[param] + 1;
}
return getIncrementedVal;
}
const extractor = makeObjectExtractor();
// this now properly raises an error:
extractor('asdfasdf');
// this does not raise an error, which is expected:
extractor('b');
</code></pre>
<p>Now keyof correctly limits to the values <code>"keyA" | "keyB"</code></p>
<p>Is there a way to get <code>keyof</code> to work with dynamic keys?</p>
|
[
{
"answer_id": 74588757,
"author": "line88",
"author_id": 1816407,
"author_profile": "https://Stackoverflow.com/users/1816407",
"pm_score": 0,
"selected": false,
"text": " function makeObjectExtractor(\n ) {\n const toExtractFrom = {\n // keyA is no longer dynamic; keyof works as expected now\n keyA: 'b',\n keyB: 'c'\n }\n\n type ExtractType = typeof toExtractFrom;\n\n function extract(a: keyof ExtractType | number): string {\n return toExtractFrom[a];\n }\n\n return extract;\n }\n | string a string"
},
{
"answer_id": 74589103,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "as as function recordFromEntries<K extends PropertyKey, V>(entries: [K, V][]): Record<K, V> {\n return Object.fromEntries(entries) as Record<K, V>;\n}\nlet x = recordFromEntries\n\nfunction makeObjectExtractor<KeyA extends string>(\n keyA: KeyA,\n) {\n const toExtractFrom = {\n keyB: 5,\n ...recordFromEntries([\n [keyA, 4]\n ]),\n } satisfies Record<string, number>;\n\n function getIncrementedVal(param: keyof typeof toExtractFrom): number {\n return toExtractFrom[param] + 1;\n }\n\n return getIncrementedVal;\n}\n\nconst extractor = makeObjectExtractor('g');\n\n// this should be flagged as a typescript error, but it isn't because keyA is dynamic\nextractor('asdfasdf');\n"
},
{
"answer_id": 74591272,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 2,
"selected": true,
"text": "keyA keyA string function makeObjectExtractor<KeyA extends string>(\n keyA: KeyA,\n) {\n const toExtractFrom = {\n ...{ [keyA]: 4 } as Record<KeyA, number>,\n keyB: 5\n } satisfies Record<string, number>\n\n function getIncrementedVal(param: keyof typeof toExtractFrom) {\n return toExtractFrom[param] + 1;\n }\n\n return getIncrementedVal;\n}\n keyA toExtractFrom Record<KeyA, number> const extractor = makeObjectExtractor('g');\n\n// valid\nextractor(\"keyB\")\nextractor(\"g\")\n\n// invalid\nextractor('asdfasdf');\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/773210/"
] |
74,588,674
|
<p>This problem that I'm facing is common for me and I want to learn for about best practices.</p>
<p>My problem is:</p>
<p>I have to wait a text which has an attribute of ".title" class and the text involves the statement of: "Hello". Before triggering this element to come to surface, we have an element already have attributes of ".title" which have a text of "StatementX" as well (At the end of the process, I have 2 ".title" class items on screen).</p>
<p>When I tried to wait for the element "Hello", I write:</p>
<pre><code>`cy.get('.title').contains('Hello').should('be.visible')
`
</code></pre>
<p>Since "StatementX" is already on the screen, Cypress finds ".title" class and does not check "contains" part. What is the best practice to handle such cases?</p>
<p>Thank you so much</p>
|
[
{
"answer_id": 74594074,
"author": "Chloe",
"author_id": 20617867,
"author_profile": "https://Stackoverflow.com/users/20617867",
"pm_score": 3,
"selected": true,
"text": ".title .contains() cy.contains('.title', 'Hello').should('be.visible')\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14560201/"
] |
74,588,678
|
<p>I am a newbie programmer, so there are some problems. The program displays only 3 positive elements in a one-dimensional array, although there may be many more in a two-dimensional array.</p>
<p>here is my code</p>
<pre><code>using System;
namespace task_2
{
class arrays
{
public int[,] A = new int[3, 3];
public int[] B = new int[9];
public void two_dimensional_array()
{
Random rand = new Random();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
A[i, j] = rand.Next(-100, 100);
}
}
Console.WriteLine("Two-dimensional array: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("{0}\t", A[i, j]);
}
Console.WriteLine();
}
}
public void one_dimensional_array()
{
Console.WriteLine("\nA one-dimensional array with only positive elements: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (A[i, j] > 0)
B[i] = A[i, j];
}
}
for (int i = 0; i < 9; i++)
{
Console.WriteLine(B[i]);
}
}
}
class Program
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.Default;
arrays a;
a = new arrays();
a.two_dimensional_array();
a.one_dimensional_array();
}
}
}
</code></pre>
<p>I have attached a photo of the result below, where only three positive elements are displayed:
<a href="https://i.stack.imgur.com/4Qnjg.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74589729,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 2,
"selected": true,
"text": "zero to be displayed instead of negative //B[i] = A[i, j];\n B[i*3+j] = A[i, j];\n negative numbers not to be displayed int index=0;\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n if (A[i, j] > 0)\n B[index++] = A[i, j];\n }\n\n }\n\n for (int i = 0; i < index; i++)\n {\n Console.WriteLine(B[i]);\n }\n"
},
{
"answer_id": 74589760,
"author": "Astrid E.",
"author_id": 17213526,
"author_profile": "https://Stackoverflow.com/users/17213526",
"pm_score": 0,
"selected": false,
"text": "one_dimensional_array() for A B for (int i = 0; i < 3; i++)\n{\n for (int j = 0; j < 3; j++)\n {\n if (A[i, j] > 0)\n B[i] = A[i, j];\n }\n}\n i j A i B B i for if (A[i, j] > 0) i j A[i, j] B[i] | i | j | A[i, j] | B[i] |\n|-----|-----|-----------|--------|\n| 0 | 0 | A[0, 0] | B[0] |\n| 0 | 1 | A[0, 1] | B[0] |\n| 0 | 2 | A[0, 2] | B[0] |\n|-----|-----|-----------|--------|\n| 1 | 0 | A[1, 0] | B[1] |\n| 1 | 1 | A[1, 1] | B[1] |\n| 1 | 2 | A[1, 2] | B[1] |\n|-----|-----|-----------|--------|\n| 2 | 0 | A[2, 0] | B[2] |\n| 2 | 1 | A[2, 1] | B[2] |\n| 2 | 2 | A[2, 2] | B[2] |\n B[0] A B[1] A B[2] A B 0 8 i j B[k] = A[i, j];\n k"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20575717/"
] |
74,588,720
|
<p>When I was learning C# generics, some articles mentioned using generics is type-safe during execution by preventing the usage of data whose type is different from the one used in the declaration.
<a href="https://www.techopedia.com/definition/25616/generics-c-sharp" rel="nofollow noreferrer">Link</a>
I dont get why this should be an issue, if type is wrong shouldn't it crashed when build?</p>
<p>I'm curious about when and how this kind of problem could happen.</p>
|
[
{
"answer_id": 74588838,
"author": "Link",
"author_id": 1892523,
"author_profile": "https://Stackoverflow.com/users/1892523",
"pm_score": 1,
"selected": false,
"text": "void DoSomething<T>(T foo) where T : FooBase { }\n var myBar = new Bar(); // Does not inherit from FooBase\nDoSomething(myBar);\n void DomSomething<T>(T foo);\n DoSomething(object obj) object"
},
{
"answer_id": 74588852,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "ArrayList List<T> ArrayList.Add object var people = new ArrayList();\npeople.Add(new Person(\"Jon\"));\n\n// ... later in the code\nforeach (string name in people)\n{\n Console.WriteLine(name);\n}\n ClassCastException Person string List<Person> List<string>"
},
{
"answer_id": 74588872,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 0,
"selected": false,
"text": "public interface IHaveId { int Id {get;}}\n\npublic T GetOrAddById<T>(IList<T> col, int id, T val) where T : class, IHaveId\n{\n var item = col.FirstOrDefault(x => x.Id == id);\n if (item == null)\n {\n item = val;\n col.Add(item);\n }\n return item;\n}\n ArrayList List<object>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15891918/"
] |
74,588,746
|
<p>I'm relatively new to bash and I have tried multiples solutions that I could find here but none of them seem to be working in my case. It's pretty simple, I have a folder that looks like this:</p>
<pre><code>- images/
- 0_image_1.jpg
- 0_image_2.jpg
- 0_image_3.jpg
- 1_image_1.jpg
- 1_image_2.jpg
- 1_image_3.jpg
</code></pre>
<p>and I would like to move these jpg files into subfolders based on the prefix number like so:</p>
<pre><code>- images_0/
- 0_image_1.jpg
- 0_image_2.jpg
- 0_image_3.jpg
- images_1/
- 1_image_1.jpg
- 1_image_2.jpg
- 1_image_3.jpg
</code></pre>
<p>Is there a bash command that could do that in a simple way ?
Thank you</p>
|
[
{
"answer_id": 74589030,
"author": "oguz ismail",
"author_id": 10248678,
"author_profile": "https://Stackoverflow.com/users/10248678",
"pm_score": 2,
"selected": false,
"text": "for src in *_*.jpg; do\n dest=images_${src%%_*}/\n echo mkdir -p \"$dest\"\n echo mv -- \"$src\" \"$dest\"\ndone\n echo"
},
{
"answer_id": 74589673,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "rename Perl rename rename --dry-run -p '$_=\"images_\" . substr($_,0,1) . \"/\" . $_' ?_*jpg\n --dry-run -p $_ $_ images_ '0_image_1.jpg' would be renamed to 'images_0/0_image_1.jpg'\n'0_image_2.jpg' would be renamed to 'images_0/0_image_2.jpg'\n'1_image_3.jpg' would be renamed to 'images_1/1_image_3.jpg'\n rename rename brew install rename\n rename prename Perl rename"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624157/"
] |
74,588,784
|
<p>I have two python programs which one of them connects to a bluetooth device(socket package), it receives and saves data from device, and another one read the stored data and draw a real time plot. I should make one application from these two programs.</p>
<p>I tried to mix these two python programs, but since bluetooth should wait to receive data (through a while loop), the other parts of program does not work. I tried to solve this problem using Clock.schedule_interval, but the program will hang after a period of time. So I decided to run these two programs simultaneously. I read, we can run some python programs at a same time using <a href="https://stackoverflow.com/questions/53404043/make-a-python-script-that-can-run-two-python-scripts-concurrently">a python script</a>. Is there any trick to join these two programs and build one application?
Any help would be greatly appreciated.</p>
|
[
{
"answer_id": 74589030,
"author": "oguz ismail",
"author_id": 10248678,
"author_profile": "https://Stackoverflow.com/users/10248678",
"pm_score": 2,
"selected": false,
"text": "for src in *_*.jpg; do\n dest=images_${src%%_*}/\n echo mkdir -p \"$dest\"\n echo mv -- \"$src\" \"$dest\"\ndone\n echo"
},
{
"answer_id": 74589673,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "rename Perl rename rename --dry-run -p '$_=\"images_\" . substr($_,0,1) . \"/\" . $_' ?_*jpg\n --dry-run -p $_ $_ images_ '0_image_1.jpg' would be renamed to 'images_0/0_image_1.jpg'\n'0_image_2.jpg' would be renamed to 'images_0/0_image_2.jpg'\n'1_image_3.jpg' would be renamed to 'images_1/1_image_3.jpg'\n rename rename brew install rename\n rename prename Perl rename"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4806877/"
] |
74,588,792
|
<p>My problem is to count words having alphabet 'a' at second position in a string
Eg : banana in a bag
o/p banana bag</p>
<pre><code>for i in re:
if i[1]== 'a':
print(i)
</code></pre>
<p>It was showing index out of range error due to word "a" in a sentence
I want output without error can anyone solve it?</p>
|
[
{
"answer_id": 74589030,
"author": "oguz ismail",
"author_id": 10248678,
"author_profile": "https://Stackoverflow.com/users/10248678",
"pm_score": 2,
"selected": false,
"text": "for src in *_*.jpg; do\n dest=images_${src%%_*}/\n echo mkdir -p \"$dest\"\n echo mv -- \"$src\" \"$dest\"\ndone\n echo"
},
{
"answer_id": 74589673,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "rename Perl rename rename --dry-run -p '$_=\"images_\" . substr($_,0,1) . \"/\" . $_' ?_*jpg\n --dry-run -p $_ $_ images_ '0_image_1.jpg' would be renamed to 'images_0/0_image_1.jpg'\n'0_image_2.jpg' would be renamed to 'images_0/0_image_2.jpg'\n'1_image_3.jpg' would be renamed to 'images_1/1_image_3.jpg'\n rename rename brew install rename\n rename prename Perl rename"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20612927/"
] |
74,588,837
|
<p>I have a method (shown below) which works fine. The purpose of this method is to confirm if a specific item is available in a shop, with a return value of true or false.</p>
<p>I have a second method, which returns a description, but I can't see to work out how to get this method to pull through the first method response with 'true' showing as 'Yes' or 'false' showing as 'No'. I'm assuming it is something to do with method calling and string concatenation.</p>
<p>My overall problem pulls through 2 methods, but I wanted to just try and understand how to pull one method first and then I'll hopefully work out the rest!</p>
<p>Method 1</p>
<pre><code>public void isFree()
{
if (sweet.isEmpty()){
System.out.println("True");
}
else {
System.out.println("False");
}
}`
</code></pre>
<p>Method 2</p>
<pre><code>public void information()
{
System.out.println (isFree+ " this item is available for purchase.");
}
</code></pre>
|
[
{
"answer_id": 74588866,
"author": "M_S",
"author_id": 19915660,
"author_profile": "https://Stackoverflow.com/users/19915660",
"pm_score": 1,
"selected": false,
"text": "public String isFree(){\n return sweet.isEmpty() ? \"True\" : \"False\";\n}`\n\npublic void information(){\n System.out.println (isFree() + \" this item is available for purchase.\");\n}\n public boolean isFree() {\n return sweet.isEmpty();\n}\n"
},
{
"answer_id": 74588891,
"author": "thmasker",
"author_id": 9601720,
"author_profile": "https://Stackoverflow.com/users/9601720",
"pm_score": -1,
"selected": false,
"text": "isFree information println public void isFree() {\n sweet.isEmpty() ? System.out.printf(\"True\") : System.out.printf(\"False\");\n}\n\npublic void information() {\n isFree();\n System.out.printf(\" this item is available for purchase.\\n\");\n}\n isFree String public String isFree() {\n sweet.isEmpty() ? \"True\" : \"False\";\n}\n\npublic void information() {\n System.out.println(isFree() + \" this item is available for purchase.\");\n}\n"
},
{
"answer_id": 74589848,
"author": "vimlesh kumar pandey",
"author_id": 20613235,
"author_profile": "https://Stackoverflow.com/users/20613235",
"pm_score": 0,
"selected": false,
"text": "public void information() {\n String customText=\", this item is available for purchase.\";\n System.out.println (sweet.isEmpty() ? \"YES\"+customText : \"NO\"+customText);}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17273353/"
] |
74,588,871
|
<p>`</p>
<pre><code>gcc *.c
In file included from get_next_line.h:16,
from get_next_line.c:13:
/usr/local/Cellar/gcc/12.2.0/lib/gcc/current/gcc/x86_64-apple-darwin20/12/include-fixed/stdio.h:78:10: fatal error: _stdio.h: No such file or directory
78 | #include <_stdio.h>
| ^~~~~~~~~~
compilation terminated.
</code></pre>
<p>`</p>
<p>Hello, i got an issue when i try to compile on MAC os (i've just updated it to Ventura), it s like the path to my libraries are not the good one any more, any help on this please ?</p>
|
[
{
"answer_id": 74595483,
"author": "abu_bua",
"author_id": 9008235,
"author_profile": "https://Stackoverflow.com/users/9008235",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n _stdio.h #ifndef _STDIO_H_\n #error error \"Never use <secure/_stdio.h> directly; include <stdio.h> instead.\"\n#endif\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20323391/"
] |
74,588,877
|
<p>I have a variable in the component:</p>
<p><code>showModal: boolean</code></p>
<p>And this in the template:</p>
<pre><code><div (mouseover)="handleHover('hover')">
</code></pre>
<p><code>handleHover()</code> changes the value of <code>showModal</code>.</p>
<p>Should I use a <code>handleHover()</code> type func and point <code>(mouseover)</code> to it or is it fine to do something like this?</p>
<pre><code><div (mouseover)="this.showModal = true"">
</code></pre>
|
[
{
"answer_id": 74588948,
"author": "Selaka Nanayakkara",
"author_id": 4672460,
"author_profile": "https://Stackoverflow.com/users/4672460",
"pm_score": 2,
"selected": false,
"text": "template-driven-forms handleHover() (mouseover)"
},
{
"answer_id": 74588982,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 0,
"selected": false,
"text": "showModal handleHover() showModal .ts handleHover() handlePrimaryBtnHover() handleSecondaryBtnHover() handleSecondaryBtnClick() handleHover() handleHover() handleHover() {\n this.showModal = true;\n this.showModalSubject.next(this.showModal)\n}\n showModal = true showModal this <div (mouseover)=\"showModal = true\">\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315323/"
] |
74,588,893
|
<p>`I'm trying to write code that starts with a question asking the user if they want to encode or decode to/from morse. Based on their response (1 or 2), it runs through an if statement, and will call the required function(s).</p>
<p>It will take a user's input via user_input() and either return it in morse code, or return it in English, based on their choice to encode or decode. The encoding aspect works, but I cannot get the decode_morse() function to work within the entire program.</p>
<p>I'm getting an error on the calling of function encode_or_decode() at the bottom, and also 'TypeError: decode_morse() missing 1 required positional argument: 'data''</p>
<pre><code>
# Dictionary representing English to morse code chart
ENG_TO_MORSE_DICT = {'a':'.-', 'b':'-...', 'c':'-.-.',
'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....',
'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--',
'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.',
's':'...', 't':'-', 'u':'..-', 'v':'...-', 'w':'.--',
'x':'-..-', 'y':'-.--', 'z':'--..', ' ':'/', 'A':'.-',
'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.',
'G':'--.','H':'....', 'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.',
'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-',
'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..'
}
# Dictionary representing morse code to English
MORSE_TO_ENG_DICT = {
".-": "A", "-...": "B", "-.-.": "C", "-..": "D",
".": "E", "..-.": "F", "--.": "G", "....": "H",
"..": "I", ".---": "J", "-.-": "K", ".-..": "L",
"--": "M", "-.": "N", "---": "O", ".--.": "P",
" --.-": "Q", ".-.": "R", "...": "S", "-": "T",
"..-": "U", "...-": "V", ".--": "W", "-..-": "X",
"-.--": "Y", "--..": "Z", "/":' '
}
def encode_or_decode():
choice = int(input("Please select 1 to encode to morse, or 2 to decode from morse "))
if choice == 1:
message_to_encode()
elif choice == 2:
decode_morse()
else:
print("Please select option 1 or option 2")
# Defining a global variable for user's input to be used within multiple functions
def user_input():
global data
data = str(input("What message do you want to translate using the Morse cipher? "))
def morse_encrypt(data):
for letter in data:
print(ENG_TO_MORSE_DICT[letter], end = ' ')
# Defining a function for user-inputted data, using isalpha method to mandate only alphabet letters & spaces as input
def message_to_encode():
user_input()
if data.replace(' ', '').isalpha():
morse_encrypt(data)
else:
print("Only text allowed in message")
def decode_morse():
results = []
for item in data.split(' '):
results.append(MORSE_TO_ENG_DICT.get(item))
results = ''.join(results)
return results.lower()
def decode_morse(data):
results = []
for item in data.split(' '):
results.append(MORSE_TO_ENG_DICT.get(item))
results = ''.join(results)
return results.lower()
encode_or_decode()
</code></pre>
<p>I've tried running a similar decode function in isolation with its own user input and this works fine... but I don't want to duplicate the user input function in the main program, so have tried to use the data variable from the user_input(_) function, which throws up errors.</p>
<pre><code>MORSE_TO_ENG_DICT = {
".-": "A", "-...": "B", "-.-.": "C", "-..": "D",
".": "E", "..-.": "F", "--.": "G", "....": "H",
"..": "I", ".---": "J", "-.-": "K", ".-..": "L",
"--": "M", "-.": "N", "---": "O", ".--.": "P",
" --.-": "Q", ".-.": "R", "...": "S", "-": "T",
"..-": "U", "...-": "V", ".--": "W", "-..-": "X",
"-.--": "Y", "--..": "Z", "/":' '
}
def decode_morse(morse_data):
results = []
for item in morse_data.split(' '):
results.append(MORSE_TO_ENG_DICT.get(item))
results = ''.join(results)
return results.lower()
morse_data = str(input("What morse message do you want to decode using the Morse cipher? "))
print(decode_morse(morse_data))
</code></pre>
|
[
{
"answer_id": 74588948,
"author": "Selaka Nanayakkara",
"author_id": 4672460,
"author_profile": "https://Stackoverflow.com/users/4672460",
"pm_score": 2,
"selected": false,
"text": "template-driven-forms handleHover() (mouseover)"
},
{
"answer_id": 74588982,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 0,
"selected": false,
"text": "showModal handleHover() showModal .ts handleHover() handlePrimaryBtnHover() handleSecondaryBtnHover() handleSecondaryBtnClick() handleHover() handleHover() handleHover() {\n this.showModal = true;\n this.showModalSubject.next(this.showModal)\n}\n showModal = true showModal this <div (mouseover)=\"showModal = true\">\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20612961/"
] |
74,588,927
|
<p>I'm trying to create a python script that prints a different statement on every day of December leading up to Christmas.</p>
<p>Below is what I've tried so far as a test but it doesn't work :/</p>
<pre><code>from datetime import date
today = date.today()
nov_27 = 2022-11-27
nov_28 = 2022-11-28
if today == nov_27:
print("words")
elif today == nov_28:
print("no words")
</code></pre>
|
[
{
"answer_id": 74588948,
"author": "Selaka Nanayakkara",
"author_id": 4672460,
"author_profile": "https://Stackoverflow.com/users/4672460",
"pm_score": 2,
"selected": false,
"text": "template-driven-forms handleHover() (mouseover)"
},
{
"answer_id": 74588982,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 0,
"selected": false,
"text": "showModal handleHover() showModal .ts handleHover() handlePrimaryBtnHover() handleSecondaryBtnHover() handleSecondaryBtnClick() handleHover() handleHover() handleHover() {\n this.showModal = true;\n this.showModalSubject.next(this.showModal)\n}\n showModal = true showModal this <div (mouseover)=\"showModal = true\">\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613120/"
] |
74,588,932
|
<p>I was using ffmpeg to convert Line sticker from apng file to webm file.
And the result is weird, some of them was converted successed and some of them failed.
not sure what happend with these failed convert.</p>
<p>Here is my c# code to convert Line sticker to webm,
and I use CliWrap to run ffmpeg command line.</p>
<pre><code>async Task Main()
{
var downloadUrl = @"http://dl.stickershop.LINE.naver.jp/products/0/0/1/23303/iphone/stickerpack@2x.zip";
var arg = @$"-i pipe:.png -vf scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos -pix_fmt yuva420p -c:v libvpx-vp9 -cpu-used 5 -minrate 50k -b:v 350k -maxrate 450k -to 00:00:02.900 -an -y -f webm pipe:1";
var errorCount = 0;
try
{
using (var hc = new HttpClient())
{
var imgsZip = await hc.GetStreamAsync(downloadUrl);
using (ZipArchive zipFile = new ZipArchive(imgsZip))
{
var files = zipFile.Entries.Where(entry => Regex.IsMatch(entry.FullName, @"animation@2x\/\d+\@2x.png"));
foreach (var entry in files)
{
try
{
using (var fileStream = File.Create(Path.Combine("D:", "Projects", "ffmpeg", "Temp", $"{Path.GetFileNameWithoutExtension(entry.Name)}.webm")))
using (var pngFileStream = File.Create(Path.Combine("D:", "Projects", "ffmpeg", "Temp", $"{entry.Name}")))
using (var entryStream = entry.Open())
using (MemoryStream ms = new MemoryStream())
{
entry.Open().CopyTo(pngFileStream);
var result = await Cli.Wrap("ffmpeg")
.WithArguments(arg)
.WithStandardInputPipe(PipeSource.FromStream(entryStream))
.WithStandardOutputPipe(PipeTarget.ToStream(ms))
.WithStandardErrorPipe(PipeTarget.ToFile(Path.Combine("D:", "Projects", "ffmpeg", "Temp", $"{Path.GetFileNameWithoutExtension(entry.Name)}Info.txt")))
.WithValidation(CommandResultValidation.ZeroExitCode)
.ExecuteAsync();
ms.Seek(0, SeekOrigin.Begin);
ms.WriteTo(fileStream);
}
}
catch (Exception ex)
{
entry.FullName.Dump();
ex.Dump();
errorCount++;
}
}
}
}
}
catch (Exception ex)
{
ex.Dump();
}
$"Error Count:{errorCount.Dump()}".Dump();
}
</code></pre>
<p>This is the failed convert file's error information from ffmpeg:</p>
<p><a href="https://i.stack.imgur.com/XX0EI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XX0EI.png" alt="enter image description here" /></a></p>
<p>And the successed convert file from ffmpeg infromation:
<a href="https://i.stack.imgur.com/diYbW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/diYbW.png" alt="enter image description here" /></a></p>
<p>It's strange when I was manually converted these failed convert file from command line, and it will be converted successed.
<a href="https://i.stack.imgur.com/0vxc9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0vxc9.png" alt="enter image description here" /></a></p>
<p>The question is the resource of images are all the same apng file,
so I just can't understan why some of files will convert failed from my c# code
but also when I manually use command line will be converted successed?</p>
<hr />
<p>I have written same exampe from C# to Python...
and here is python code:</p>
<pre><code>from io import BytesIO
import os
import re
import subprocess
import zipfile
import requests
downloadUrl = "http://dl.stickershop.LINE.naver.jp/products/0/0/1/23303/iphone/stickerpack@2x.zip"
args = [
'ffmpeg',
'-i', 'pipe:',
'-vf', 'scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos',
'-pix_fmt', 'yuva420p',
'-c:v', 'libvpx-vp9',
'-cpu-used', '5',
'-minrate', '50k',
'-b:v', '350k',
'-maxrate', '450k', '-to', '00:00:02.900', '-an', '-y', '-f', 'webm', 'pipe:1'
]
imgsZip = requests.get(downloadUrl)
with zipfile.ZipFile(BytesIO(imgsZip.content)) as archive:
files = [file for file in archive.infolist() if re.match(
"animation@2x\/\d+\@2x.png", file.filename)]
for entry in files:
fileName = entry.filename.replace(
"animation@2x/", "").replace(".png", "")
rootPath = 'D:\\' + os.path.join("Projects", "ffmpeg", "Temp")
# original file
apngFile = os.path.join(rootPath, fileName+'.png')
# output file
webmFile = os.path.join(rootPath, fileName+'.webm')
# output info
infoFile = os.path.join(rootPath, fileName+'info.txt')
with archive.open(entry) as file, open(apngFile, 'wb') as output_apng, open(webmFile, 'wb') as output_webm, open(infoFile, 'wb') as output_info:
p = subprocess.Popen(args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=output_info)
outputBytes = p.communicate(input=file.read())[0]
output_webm.write(outputBytes)
file.seek(0)
output_apng.write(file.read())
</code></pre>
<p>And you can try it,the result will be the as same as C#.</p>
|
[
{
"answer_id": 74612794,
"author": "Rotem",
"author_id": 4926757,
"author_profile": "https://Stackoverflow.com/users/4926757",
"pm_score": 2,
"selected": true,
"text": "apng_pipe type 397189868@2x.png | ffmpeg.exe -i pipe: -pix_fmt yuva420p -c:v libvpx-vp9 -y test.webm os.mkfifo apng_pipe.apng apng_pipe = \"apng_pipe.apng\"\n os.mkfifo(apng_pipe)\n def writer(data_buf, pipe_name, chunk_size):\n # Open the pipe as opening files (open for \"open for writing only\").\n fd_pipe = os.open(pipe_name, os.O_WRONLY) # fd_pipe is a file descriptor (an integer)\n \n for i in range(0, len(data_buf), chunk_size):\n # Write to named pipe as writing to a file (but write the data in small chunks).\n os.write(fd_pipe, data_buf[i:min(chunk_size+i, len(data_buf))]) # Write 1024 bytes of data to fd_pipe\n \n # Closing the pipes as closing files.\n os.close(fd_pipe)\n -i apng_pipe.apng pipe: p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=output_info)\n p.communicate()[0] writer_thread = Thread(target=writer, args=(data, apng_pipe, 1024))\n writer_thread.start()\n writer_thread.join()\n\n outputBytes = p.communicate()[0] # Read the output from stdout, and ends FFmpeg sub-process\n os.unlink(apng_pipe)\n from io import BytesIO\nimport os\nimport re\nimport subprocess\nimport zipfile\nfrom threading import Thread\nimport requests\n\n# Name of the \"Named pipe\"\napng_pipe = \"apng_pipe.apng\"\n\ndownloadUrl = \"http://dl.stickershop.LINE.naver.jp/products/0/0/1/23303/iphone/stickerpack@2x.zip\"\nargs = [\n 'ffmpeg',\n '-i', apng_pipe, #'-i', 'pipe:',\n '-vf', 'scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos',\n '-pix_fmt', 'yuva420p',\n '-c:v', 'libvpx-vp9',\n '-cpu-used', '5',\n '-minrate', '50k',\n '-b:v', '350k',\n '-maxrate', '450k', '-to', '00:00:02.900', '-an', '-y', '-f', 'webm', 'pipe:1'\n]\n\n\ndef writer(data_buf, pipe_name, chunk_size):\n # Open the pipe as opening files (open for \"open for writing only\").\n fd_pipe = os.open(pipe_name, os.O_WRONLY) # fd_pipe is a file descriptor (an integer)\n\n for i in range(0, len(data_buf), chunk_size):\n # Write to named pipe as writing to a file (but write the data in small chunks).\n os.write(fd_pipe, data_buf[i:min(chunk_size+i, len(data_buf))]) # Write 1024 bytes of data to fd_pipe\n\n # Closing the pipes as closing files.\n os.close(fd_pipe)\n\n\n# Create \"named pipe\" (not supported by Windows).\nos.mkfifo(apng_pipe)\n\n\n#imgsZip = requests.get(downloadUrl)\nrootPath = './'\n\nimgsZip = requests.get(downloadUrl)\nwith zipfile.ZipFile(BytesIO(imgsZip.content)) as archive:\n files = [file for file in archive.infolist() if re.match(\n \"animation@2x\\/\\d+\\@2x.png\", file.filename)]\n for entry in files:\n fileName = entry.filename.replace(\n \"animation@2x/\", \"\").replace(\".png\", \"\")\n # original file\n apngFile = os.path.join(rootPath, fileName+'.png')\n # output file\n webmFile = os.path.join(rootPath, fileName+'.webm')\n # output info\n infoFile = os.path.join(rootPath, fileName+'info.txt')\n\n with archive.open(entry) as file, open(apngFile, 'wb') as output_apng, open(webmFile, 'wb') as output_webm, open(infoFile, 'wb') as output_info:\n data = file.read()\n\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=output_info) # Don't use stdin=subprocess.PIPE\n\n # Initialize \"writer\" thread (the writer writes data to named pipe in chunks of 1024 bytes).\n # We have to use a thread because writing to named pipe is a \"blocking\" operation.\n # Write in small chunks, because the default buffer size of a named pipe is relatively small\n writer_thread = Thread(target=writer, args=(data, apng_pipe, 1024)) # writer_thread writes data to apng_pipe\n\n # Start the thread\n writer_thread.start()\n\n # Wait for the writer thread to finish\n writer_thread.join()\n\n outputBytes = p.communicate()[0]\n\n output_webm.write(outputBytes)\n file.seek(0)\n output_apng.write(file.read())\n\n# Remove the \"named pipe\".\nos.unlink(apng_pipe)\n"
},
{
"answer_id": 74622234,
"author": "martin wang",
"author_id": 5511771,
"author_profile": "https://Stackoverflow.com/users/5511771",
"pm_score": 0,
"selected": false,
"text": "async Task Main()\n{\n\n var downloadUrl = @\"http://dl.stickershop.LINE.naver.jp/products/0/0/1/23303/iphone/stickerpack@2x.zip\";\n var arg = @$\"-i \\\\.\\pipe\\apng_pipe -vf scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos -pix_fmt yuva420p -c:v libvpx-vp9 -cpu-used 5 -minrate 50k -b:v 350k -maxrate 450k -to 00:00:02.900 -an -y -f webm pipe:1\";\n\n var errorCount = 0;\n try\n {\n using (var hc = new HttpClient())\n {\n var imgsZip = await hc.GetStreamAsync(downloadUrl);\n\n using (ZipArchive zipFile = new ZipArchive(imgsZip))\n {\n var files = zipFile.Entries.Where(entry => Regex.IsMatch(entry.FullName, @\"animation@2x\\/\\d+\\@2x.png\"));\n foreach (var entry in files)\n {\n try\n {\n // apng output\n using (var pngFileStream = File.Create(Path.Combine(\"D:\", \"Projects\", \"ffmpeg\", \"Temp\", $\"{entry.Name}\")))\n {\n entry.Open().CopyTo(pngFileStream);\n }\n\n // convert to webm output\n using (var fileStream = File.Create(Path.Combine(\"D:\", \"Projects\", \"ffmpeg\", \"Temp\", $\"{Path.GetFileNameWithoutExtension(entry.Name)}.webm\")))\n using (var entryStream = entry.Open())\n using (MemoryStream ms = new MemoryStream())\n {\n StartNamePipedServer(entryStream);\n var result = await Cli.Wrap(\"ffmpeg\")\n .WithArguments(arg)\n .WithStandardOutputPipe(PipeTarget.ToStream(ms))\n .WithStandardErrorPipe(PipeTarget.ToFile(Path.Combine(\"D:\", \"Projects\", \"ffmpeg\", \"Temp\", $\"{Path.GetFileNameWithoutExtension(entry.Name)}Info.txt\")))\n .WithValidation(CommandResultValidation.ZeroExitCode)\n .ExecuteAsync();\n\n ms.Seek(0, SeekOrigin.Begin);\n ms.WriteTo(fileStream);\n }\n }\n catch (Exception ex)\n {\n entry.FullName.Dump();\n ex.Dump();\n errorCount++;\n }\n }\n }\n\n }\n }\n catch (Exception ex)\n {\n ex.Dump();\n }\n $\"Error Count:{errorCount.Dump()}\".Dump();\n\n}\n\npublic void StartNamePipedServer(Stream data)\n{\n Task.Factory.StartNew(() =>\n {\n using (var server = new NamedPipeServerStream(\"apng_pipe\"))\n {\n server.WaitForConnection();\n CopyStream(data, server);\n }\n });\n}\n\npublic static void CopyStream(Stream input, Stream output)\n{\n int read;\n byte[] buffer = new byte[0x1024];\n while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n {\n output.Write(buffer, 0, read);\n }\n}\n\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5511771/"
] |
74,588,940
|
<p>I'm on Postgres 13 and have a table like this</p>
<pre><code>| key | from | to
-------------------------------------------
| A | 2022-11-27T08:00 | 2022-11-27T09:00
| B | 2022-11-27T09:00 | 2022-11-27T10:00
| C | 2022-11-27T08:30 | 2022-11-27T10:30
</code></pre>
<p>I want to calculate the duration of each record, but without overlaps. So the desired result would be</p>
<pre><code>| key | from | to | duration
----------------------------------------------------------
| A | 2022-11-27T08:00 | 2022-11-27T09:00 | '1 hour'
| B | 2022-11-27T09:00 | 2022-11-27T09:45 | '45 minutes'
| C | 2022-11-27T08:30 | 2022-11-27T10:00 | '15 minutes'
</code></pre>
<p>I <em>guess</em>, I need a subquery and subtract the overlap somehow, but how would I factor in multiple overlaps? In the example above <code>C</code> overlaps <code>A</code> and <code>B</code>, so I must subtract 30 minutes from <code>A</code> and then 45 minute from <code>B</code>... But I'm stuck here:</p>
<pre><code>SELECT key, (("to" - "from")::interval - s.overlap) as duration
FROM time_entries, (
SELECT (???) as overlap
) s
</code></pre>
|
[
{
"answer_id": 74589293,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 3,
"selected": true,
"text": "select \n key,\n fromDT,\n toDT,\n (toDT-fromDT)::interval -\n COALESCE((SELECT SUM(LEAST(te2.toDT,te1.toDT)-GREATEST(te2.fromDT,te1.fromDT))::interval \n FROM time_entries te2 \n WHERE (te2.fromDT<te1.toDT or te2.toDT>te1.fromDT)\n AND te2.key<te1.key),'0 minutes') as duration\nfrom time_entries te1;\n from to fromDT toDT"
},
{
"answer_id": 74591946,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 0,
"selected": false,
"text": "WITH DATA AS\n (SELECT KEY,\n FROMDT,\n TODT,\n MIN(FROMDT) OVER(PARTITION BY FROMDT::DATE\n ORDER BY KEY) AS START_DATE,\n MAX(TODT) OVER(PARTITION BY FROMDT::DATE\n ORDER BY KEY) AS END_DATE\n FROM TIME_ENTRIES\n ORDER BY KEY) ,STAGING_DATA AS\n (SELECT KEY,\n FROMDT,\n TODT,\n COALESCE(LAG(START_DATE) OVER (PARTITION BY FROMDT::DATE\n ORDER BY KEY),FROMDT) AS T1_DATE,\n COALESCE(LAG(END_DATE) OVER (PARTITION BY FROMDT::DATE\n ORDER BY KEY),TODT) AS T2_DATE\n FROM DATA)\nSELECT KEY,\n FROMDT,\n TODT,\n CASE\n WHEN FROMDT = T1_DATE\n AND TODT = T2_DATE THEN (TODT - FROMDT) ::Interval\n WHEN T2_DATE < TODT THEN (TODT - T2_DATE)::Interval\n ELSE (T2_DATE - TODT)::interval\n END\nFROM STAGING_DATA;\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/228370/"
] |
74,588,945
|
<p>i have an action inside of users and i want that action to return the user to another action in another controller but not in the router parameter, Here is a sample</p>
<pre><code> public IActionResult LoginCheck(UserForm user)
{
AuthUser auth = new AuthUser(_context);
var result = auth.IsLoggedIn(user.Email, user.Password);
if(result.isfound==false)
{
return NotFound();
}
result.User.IsAuth = true;
return RedirectToAction("Home","Index",result.User);
}
</code></pre>
<pre><code> public async Task<IActionResult> Index(User user)
{
if(user.IsAuth == false)
{
return Unauthorized();
}
just part of the code
</code></pre>
<p>Home index did not use the incoming user as it was sent as router parameters i think</p>
|
[
{
"answer_id": 74589293,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 3,
"selected": true,
"text": "select \n key,\n fromDT,\n toDT,\n (toDT-fromDT)::interval -\n COALESCE((SELECT SUM(LEAST(te2.toDT,te1.toDT)-GREATEST(te2.fromDT,te1.fromDT))::interval \n FROM time_entries te2 \n WHERE (te2.fromDT<te1.toDT or te2.toDT>te1.fromDT)\n AND te2.key<te1.key),'0 minutes') as duration\nfrom time_entries te1;\n from to fromDT toDT"
},
{
"answer_id": 74591946,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 0,
"selected": false,
"text": "WITH DATA AS\n (SELECT KEY,\n FROMDT,\n TODT,\n MIN(FROMDT) OVER(PARTITION BY FROMDT::DATE\n ORDER BY KEY) AS START_DATE,\n MAX(TODT) OVER(PARTITION BY FROMDT::DATE\n ORDER BY KEY) AS END_DATE\n FROM TIME_ENTRIES\n ORDER BY KEY) ,STAGING_DATA AS\n (SELECT KEY,\n FROMDT,\n TODT,\n COALESCE(LAG(START_DATE) OVER (PARTITION BY FROMDT::DATE\n ORDER BY KEY),FROMDT) AS T1_DATE,\n COALESCE(LAG(END_DATE) OVER (PARTITION BY FROMDT::DATE\n ORDER BY KEY),TODT) AS T2_DATE\n FROM DATA)\nSELECT KEY,\n FROMDT,\n TODT,\n CASE\n WHEN FROMDT = T1_DATE\n AND TODT = T2_DATE THEN (TODT - FROMDT) ::Interval\n WHEN T2_DATE < TODT THEN (TODT - T2_DATE)::Interval\n ELSE (T2_DATE - TODT)::interval\n END\nFROM STAGING_DATA;\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613156/"
] |
74,588,958
|
<p>Im working on a big project and I have a lot of errno macros.<br />
I want to write a helper functions for the logger that stringify each of these errno to a string. i decided to use x-macros but Im getting compilation errors</p>
<p>in the first place the code was like this:</p>
<pre><code>// project_errno.h
#define PROJECT_ERR_KEY_FAILURE 12222
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
#define PROJECT_ERR_FAILED_TO_SETUP_ENC_KEY 14004
</code></pre>
<p>the way i sort it out is as the following:</p>
<ul>
<li>In a different file i places the x-macros:</li>
</ul>
<pre><code>// project_errno.hx
PROJECT_ERR_FUNC(PROJECT_ERR_KEY_FAILURE) 12222
PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING) 12345
PROJECT_ERR_FUNC(PROJECT_ERR_FAILED_TO_SETUP_ENC_KEY) 14004
</code></pre>
<ul>
<li>then I turned it into an enum:</li>
</ul>
<pre><code>// project_errno.h
enum {
#define PROJECT_ERR_FUNC(name, value) name=value,
#include "project_errno.hx"
#undef PROJECT_ERR_FUNC
};
</code></pre>
<ul>
<li>then i added a function that will be used by the logger:</li>
</ul>
<pre><code>// logging.h (declaration) and (definition) logging.c
const char* stringify_errno(int errno) {
switch (errno) {
#define PROJECT_ERR_FUNC(name, value) case name: return #value ;
#include "project_errno.hx"
#undef PROJECT_ERR_FUNC
}
}
</code></pre>
<p>So, looks pretty good, but i can't get it to compile, Im getting the following compilation errros:</p>
<pre><code>project_errno.h:8:53: error: error: expected identifier before numeric constant
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
project_errno.h:8:53: error: error: expected ‘}’ before numeric constant
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
project_errno.h:8:53: error: expected unqualified-id before numeric constant
#define PROJECT_ERR_CIPHER_ZERO_PADDING 12345
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
^~~~~~~~~~~~~~~~~~~~~~~
In file included from ......../project_errno.h:20:1: error: expected declaration before ‘}’ token
};
^
..../project_errno.h:17:30: note: in definition of macro ‘PROJECT_ERR_FUNC’
#define PROJECT_ERR_FUNC(name, value) name=value,
^~~~
..../project_errno.hx:47:14: note: in expansion of macro ‘PROJECT_ERR_CIPHER_ZERO_PADDING ’PROJECT_ERR_FUNC(PROJECT_ERR_CIPHER_ZERO_PADDING, 12345)
^~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>I can't understand why im getting those errors (im getting the same error message multiple time in the same compilation session), and i hope you guys could help me.
Also, if you have any other solution to solve the problem i intended to solve in the first place (using the errno macros and add a functions to stringify those errnos whenever Im adding an errno to the project [in only one place]), i'd love to hear about it Thanks</p>
|
[
{
"answer_id": 74589293,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 3,
"selected": true,
"text": "select \n key,\n fromDT,\n toDT,\n (toDT-fromDT)::interval -\n COALESCE((SELECT SUM(LEAST(te2.toDT,te1.toDT)-GREATEST(te2.fromDT,te1.fromDT))::interval \n FROM time_entries te2 \n WHERE (te2.fromDT<te1.toDT or te2.toDT>te1.fromDT)\n AND te2.key<te1.key),'0 minutes') as duration\nfrom time_entries te1;\n from to fromDT toDT"
},
{
"answer_id": 74591946,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 0,
"selected": false,
"text": "WITH DATA AS\n (SELECT KEY,\n FROMDT,\n TODT,\n MIN(FROMDT) OVER(PARTITION BY FROMDT::DATE\n ORDER BY KEY) AS START_DATE,\n MAX(TODT) OVER(PARTITION BY FROMDT::DATE\n ORDER BY KEY) AS END_DATE\n FROM TIME_ENTRIES\n ORDER BY KEY) ,STAGING_DATA AS\n (SELECT KEY,\n FROMDT,\n TODT,\n COALESCE(LAG(START_DATE) OVER (PARTITION BY FROMDT::DATE\n ORDER BY KEY),FROMDT) AS T1_DATE,\n COALESCE(LAG(END_DATE) OVER (PARTITION BY FROMDT::DATE\n ORDER BY KEY),TODT) AS T2_DATE\n FROM DATA)\nSELECT KEY,\n FROMDT,\n TODT,\n CASE\n WHEN FROMDT = T1_DATE\n AND TODT = T2_DATE THEN (TODT - FROMDT) ::Interval\n WHEN T2_DATE < TODT THEN (TODT - T2_DATE)::Interval\n ELSE (T2_DATE - TODT)::interval\n END\nFROM STAGING_DATA;\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20612285/"
] |
74,588,972
|
<p>I have a function on my views.py file that connects to a mail server and then appends to my Django model the email addresses of the recipients. The script works good.</p>
<p>In Django, I'm displaying the model with a table, and I'd like to include a button that says Get Emails and runs this function and it then reloads the page with the new data in the model / table.</p>
<p>This is my views.py:</p>
<pre><code>class SubscriberListView(LoginRequiredMixin, SingleTableView):
model = EmailMarketing
table_class = EmailMarketingTable
template_name = 'marketing/subscribers.html'
# Get emails from email server
# Connection settings
HOST = 'xXxxxxXxXx'
USERNAME = 'xXxxxxXxXx'
PASSWORD = "xXxxxxXxXx"
m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')
def get_emails():
result, data = m.uid('search', None, "ALL")
if result == 'OK':
for num in data[0].split():
result, data = m.uid('fetch', num, '(RFC822)')
if result == 'OK':
email_message_raw = email.message_from_bytes(data[0][1])
email_from = str(make_header(decode_header(email_message_raw['From'])))
email_addr = email_from.replace('<', '>').split('>')
if len(email_addr) > 1:
new_entry = EmailMarketing(email_address=email_addr[1])
new_entry.save()
else:
new_entry = EmailMarketing(email_address=email_addr[0])
new_entry.save()
# Close server connection
m.close()
m.logout()
</code></pre>
<p>My main <code>urls.py</code>:</p>
<pre><code>urlpatterns = [
path('marketing/', SubscriberListView.as_view(), name='marketing')
]
</code></pre>
<p>And this is what I tried on the app <code>urls.py</code>:</p>
<pre><code>from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.marketing, name='marketing'),
path('/getemails', views.get_emails, name='getemails'),
]
</code></pre>
<p>And then on my subscribers.html I tried this:</p>
<pre><code> <button type="submit" onclick="location.href='{% url 'getemails' %}'" class="btn btn-primary">Get Emails</button>
</code></pre>
<p>But I get an error:</p>
<pre><code>Reverse for 'getemails' not found. 'getemails' is not a valid view function or pattern name.
</code></pre>
<p>How can I call this function defined on my views.py inside my template?</p>
|
[
{
"answer_id": 74589007,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 0,
"selected": false,
"text": "{% url 'getemails' %} <button type=\"submit\" onclick=\"location.href='{% url 'getemails' %}'\" class=\"btn btn-primary\">Get Emails</button>\n / path('getemails/'...) <form> action <form method='POST' action=\"{% url 'getemails' %}\">\n"
},
{
"answer_id": 74589206,
"author": "Selcuk",
"author_id": 2011147,
"author_profile": "https://Stackoverflow.com/users/2011147",
"pm_score": 2,
"selected": true,
"text": "urls.py include urls.py from django.urls import include, path\n\nurlpatterns = [\n path('marketing/', SubscriberListView.as_view(), name='marketing'),\n path('myapp/', include('myapp.urls')),\n ...\n]\n myapp"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13887772/"
] |
74,588,983
|
<p>I typed this program from Boris Allen's book C programming: principles & practice on pg18 using Dev-C++ 5.11, its supposed to produce the following output text:</p>
<pre><code>Size of whoCount is 2
Size of newCount is 2
Size of Printf() is 2
</code></pre>
<p>I don't know how to fix this error.</p>
<pre><code>error: too few arguments to function 'printf'.
</code></pre>
<p>(The compiler also mentions something with a function in 'main.)</p>
<p>Here is the program:</p>
<pre><code>#include <stdio.h>
main()
{
int whoCount, newCount;
printf("Size of whoCount is %d\n",
sizeof(whoCount));
printf("Size of newCount is %d\n",
sizeof(newCount));
printf("Size of printf() is %d\n",
sizeof(printf()));
}
</code></pre>
<p>It's supposed to work but I don't know why it does not. It's an example program from the book C programming: principles & practice on pg18. The previous examples worked flawlessly but I'm stuck with this one giving me an error: too few arguments to function 'printf'. I am new to programming and I don't know how to fix it so any help will be greatly appreciated.</p>
|
[
{
"answer_id": 74589027,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 2,
"selected": false,
"text": "printf() sizeof(&printf) sizeof(printf(\"hello\")) sizeof(printf) size_t main main int int main(void)\n{\n int whoCount, newCount;\n printf(\"Size of whoCount is %zu\\n\",\n sizeof(whoCount));\n printf(\"Size of newCount is %zu\\n\",\n sizeof(newCount));\n printf(\"Size of printf is %zu\\n\",\n sizeof(printf));\n printf(\"Size of &printf is %zu\\n\",\n sizeof(&printf));\n printf(\"Size of printf(\\\"hello\\\") is %zu\\n\",\n sizeof(printf(\"hello\")));\n}\n printf sizeof(printf(\"hello\")) sizeof printf sizeof"
},
{
"answer_id": 74589028,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 0,
"selected": false,
"text": "main int main( void )\n int main(void) { /* ... */ }\n sizeof size_t zu d printf(\"Size of whoCount is %zu\\n\",\n sizeof(whoCount));\n printf printf printf(\"Size of printf() is %zu\\n\",\n sizeof(printf( \"Hello World!\")));\n int printf(const char * restrict format, ...);\n printf(\"Size of printf() is %zu\\n\",\n sizeof(printf( \"Hello World!\")));\n sizeof( int ) printf int \"Hello World!\" sizeof(printf( \"Hello World!\")) sizeof sizeof( printf )"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20612556/"
] |
74,588,985
|
<p>We are looking for a user in the database by <code>'_id'</code></p>
<pre class="lang-json prettyprint-override"><code> "_id": "6381e7c6bf8892cf05c7c798",
"username": "Teacher",
"email": "teacher@gmail.com",
"role": "teacher",
"avatar": "fixtures/teacher.jpg",
"token": "KNuSF7sscU3EJsMetUFKi",
"authentication": true,
"myCourses"
</code></pre>
<p>and</p>
<p>It is necessary to get a suitable object from the array using <code>'aggregate'</code>, which we find by the <code>'course'</code> field and change the <code>'status'</code> in it</p>
<pre class="lang-json prettyprint-override"><code> "myCourses": [
{
"course": "6381e7c6bf8892cf05c7c7b3",
"status": true,
"_id": "6381e80f12d633b2e6c35fbd"
},
{
"course": "6381edab4f212193837ab575",
"status": true,
"_id": "6381edc54f212193837ab57c"
}
],
</code></pre>
<p>I have tried the following methods</p>
<pre><code>const test = await User.find({ _id: userId, myCourses: {$elemMatch: {course: courseId}} })
</code></pre>
<pre class="lang-js prettyprint-override"><code>const test = await User.find(userId, { courseId: {$in : myCourses} })
</code></pre>
<pre class="lang-js prettyprint-override"><code>const updateCourseStatus = user.myCourses.find(elem => elem.course.toString() === courseId)
</code></pre>
<p>the last method works but I don't think it's correct</p>
|
[
{
"answer_id": 74598761,
"author": "kumol",
"author_id": 13299299,
"author_profile": "https://Stackoverflow.com/users/13299299",
"pm_score": 1,
"selected": false,
"text": "_id courseId $ User.update({\n _id: userId,\n \"myCourses.course\": courseId\n},\n{\n $set: {\n \"myCourses.$.status\": newStatus\n }\n})\n"
},
{
"answer_id": 74603688,
"author": "rickhg12hs",
"author_id": 1409374,
"author_profile": "https://Stackoverflow.com/users/1409374",
"pm_score": 0,
"selected": false,
"text": "\"status\" \"myCourses.course\" \"arrayFilters\" db.user.update({\n \"_id\": userId\n},\n{\n \"$set\": {\n \"myCourses.$[elem].status\": newStatus\n }\n},\n{\n \"arrayFilters\": [\n {\n \"elem.course\": courseId\n }\n ]\n})\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74588985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613106/"
] |
74,589,008
|
<p>Say I have two tables:</p>
<p>tb1:</p>
<pre><code>id name date
1 John 01/01/2012
1 John 01/02/2012
2 James 02/02/2020
</code></pre>
<p>tb2:</p>
<pre><code>id name date
1 John 01/01/2013
1 John 01/01/2012
</code></pre>
<p>The uniqueness of both <code>tb1</code> and <code>tb2</code> comes from the combination of <code>(id, name,date)</code> columns. Therefore I would like to insert only values from <code>tb2</code> that are new to <code>tb1</code>. In this case only <code>(1,John,01/01/2013)</code> would be inserted since the other row is already present in <code>tb1</code>.</p>
<p>My try is:</p>
<pre><code>INSERT INTO tb1 (date) SELECT * FROM tb2 ON CONFLICT (id,name,date) DO NOTHING;
</code></pre>
|
[
{
"answer_id": 74589071,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO tb1 (id,name,date) \nSELECT * \nFROM tb2 \nWHERE NOT EXISTS(SELECT * \n FROM tb1 INNER JOIN tb2 \n ON ROW (tb1.id, tb1.name, tb1.date) = \n ROW (tb2.id, tb2.name, tb2.date));\n"
},
{
"answer_id": 74589102,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO tb1 (id,name,date) \nSELECT id,name,date \nFROM tb2 ON CONFLICT (id,name,date) DO NOTHING;\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8176763/"
] |
74,589,026
|
<p>Require to write a Python function to perform the subtraction operation on multiple numbers (left to right direction) given as arguments.</p>
<p>User should be able to give a variable number of arguments to that function.</p>
<p>For eg, subt(a, b, c…) must return the value of a-b-c-… where a, b, c are the numbers given as arguments to the function</p>
<p>Initially I wrote a function to perform subtraction operation on two numbers as below:</p>
<pre><code>def subt(a, b):
return a-b
</code></pre>
<p>later, I extended it for three numbers as below:</p>
<pre><code>def subt(a, b, c):
return a-b-c
</code></pre>
<p>Now I want to extend the above function for variable number of arguments but do not know how to proceed from below:</p>
<pre><code>def subt(…):
diff =
for i in range(…,len(…)):
diff = diff - […]
return diff
</code></pre>
|
[
{
"answer_id": 74589173,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "*args def subt(*num):\n diff = num[0]\n for i in range(1,len(num)):\n diff = diff - num[i]\n return diff\n diff(1,2,3) #=> *num = [1,2,3]\n *args **kwargs"
},
{
"answer_id": 74589212,
"author": "Naveen Kaulwar",
"author_id": 20549546,
"author_profile": "https://Stackoverflow.com/users/20549546",
"pm_score": -1,
"selected": true,
"text": "def subt1(*numbers): # defining a function subt1 and using a non-keyword argument *numbers so that variable number of arguments can be provided by user. All these arguments will be stored as a tuple.\n\ntry: # using try-except to handle the errors. If numbers are given as arguments, then the statements in the try block will get executed.\n\n diff = numbers[0] # assigning the first element/number to the variable diff\n \n for i in range(1,len(numbers)): # iterating through all the given elements/ numbers of a tuple using a for loop\n diff = diff - numbers[i] # performing the subtraction operation for multiple numbers from left to right, for eg, a-b-c = (a-b)-c\n return diff # returning the final value of the above operation\n\nexcept: # if no arguments OR more than one non-numbers are passed, then the statement in the except block will get executed\n return 'please enter numbers as arguments'\n def subt2(*numbers):\n\ntry:\n add = 0 # initializing a variable add with 0\n \n for i in range(1,len(numbers)):\n add = add+ numbers[i] # performing the addition operation for the numbers starting from the index 1\n return numbers[0]-add # returning the final value of subtraction of given numbers, logic : a-b-c = a-(b+c) = a-add(b,c)\n\nexcept:\n return 'please enter numbers as arguments'\n"
},
{
"answer_id": 74589232,
"author": "Someone193",
"author_id": 18256963,
"author_profile": "https://Stackoverflow.com/users/18256963",
"pm_score": 0,
"selected": false,
"text": "def subt(*nums):\n first_num = nums[0] # The first number\n for num in nums[1:]: # index 1 to the last number\n first_num -= num\n return first_num\n\nprint(subt(33, 2, 3, 4, 7)) # -> 17\nprint(subt(13, 7)) # -> 6\n def subt(*nums):\n first_num = nums[0] # The first number\n sum_of_rest = sum(nums[1:]) # The sum of all the number except the first number\n # Or you can say, sum of numbers from index 1 to the last\n\n return first_num - sum_of_rest\n\nprint(subt(33, 2, 3, 4, 7)) # -> 17\nprint(subt(13, 7)) # -> 6\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20549546/"
] |
74,589,043
|
<p>I just compiled <strong>Ruby</strong> from source and it is located into <code>/usr/local/ruby</code></p>
<p>In order to access Ruby's executables I edited <code>~/.zshenv</code> adding <code>/usr/local/ruby/bin</code> to the <code>export PATH</code> directive:</p>
<pre><code>export PATH=/usr/local/ruby/bin:/usr/local/mysql/bin:/usr/local/sbin:/usr/local/bin:$PATH
^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>However restarting the terminal and running <code>which ruby</code> still returns macOS's default <code>/usr/bin/ruby</code></p>
<p>In fact inspecting <code>PATH</code> reveals:</p>
<pre><code>% echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/usr/local/ruby/bin:/usr/local/mysql/bin:/usr/local/sbin:
</code></pre>
<p>So <strong>after</strong> my <code>~/.zshenv</code> is excecuted another configuration file prepends <code>/usr/bin</code> to <code>PATH</code>.</p>
<p>Where does this happen?</p>
<p>I would expect to find <code>/usr/bin</code> already in <code>PATH</code> when <code>.zshenv</code> is processed (resulting in having this path at the end of the environment variable).</p>
<p>What I am missing?</p>
<hr />
<p>I checked and there are no other <strong>zsh</strong> configuration files in my home directory, just <code>.zshenv</code>;</p>
<p>I checked <code>/etc</code> too and found</p>
<pre><code>zprofile
zshrc
zshrc_Apple_Terminal
</code></pre>
<p>but none of those do alter the <code>PATH</code> variable</p>
<hr />
<p>on <code>/etc/paths</code></p>
<p>I have</p>
<pre><code>/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
</code></pre>
<p>but again, shouldn't be <code>PATH</code> already set with those paths when <code>.zshenv</code> is processed ?</p>
|
[
{
"answer_id": 74589173,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "*args def subt(*num):\n diff = num[0]\n for i in range(1,len(num)):\n diff = diff - num[i]\n return diff\n diff(1,2,3) #=> *num = [1,2,3]\n *args **kwargs"
},
{
"answer_id": 74589212,
"author": "Naveen Kaulwar",
"author_id": 20549546,
"author_profile": "https://Stackoverflow.com/users/20549546",
"pm_score": -1,
"selected": true,
"text": "def subt1(*numbers): # defining a function subt1 and using a non-keyword argument *numbers so that variable number of arguments can be provided by user. All these arguments will be stored as a tuple.\n\ntry: # using try-except to handle the errors. If numbers are given as arguments, then the statements in the try block will get executed.\n\n diff = numbers[0] # assigning the first element/number to the variable diff\n \n for i in range(1,len(numbers)): # iterating through all the given elements/ numbers of a tuple using a for loop\n diff = diff - numbers[i] # performing the subtraction operation for multiple numbers from left to right, for eg, a-b-c = (a-b)-c\n return diff # returning the final value of the above operation\n\nexcept: # if no arguments OR more than one non-numbers are passed, then the statement in the except block will get executed\n return 'please enter numbers as arguments'\n def subt2(*numbers):\n\ntry:\n add = 0 # initializing a variable add with 0\n \n for i in range(1,len(numbers)):\n add = add+ numbers[i] # performing the addition operation for the numbers starting from the index 1\n return numbers[0]-add # returning the final value of subtraction of given numbers, logic : a-b-c = a-(b+c) = a-add(b,c)\n\nexcept:\n return 'please enter numbers as arguments'\n"
},
{
"answer_id": 74589232,
"author": "Someone193",
"author_id": 18256963,
"author_profile": "https://Stackoverflow.com/users/18256963",
"pm_score": 0,
"selected": false,
"text": "def subt(*nums):\n first_num = nums[0] # The first number\n for num in nums[1:]: # index 1 to the last number\n first_num -= num\n return first_num\n\nprint(subt(33, 2, 3, 4, 7)) # -> 17\nprint(subt(13, 7)) # -> 6\n def subt(*nums):\n first_num = nums[0] # The first number\n sum_of_rest = sum(nums[1:]) # The sum of all the number except the first number\n # Or you can say, sum of numbers from index 1 to the last\n\n return first_num - sum_of_rest\n\nprint(subt(33, 2, 3, 4, 7)) # -> 17\nprint(subt(13, 7)) # -> 6\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1579327/"
] |
74,589,046
|
<p>Recently I've been trying to do some webscraping, however I am utterly unable to run Selenium's webdriver.</p>
<p>I am trying to run this basic boilerplate code:</p>
<pre><code>import pandas as pd
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
web = webdriver.Chrome(service_args=["--verbose", "--log-path=D:\\qc1.log"])
url = 'https://www.google.com/'
web.get(url)
</code></pre>
<p>However this results in the following error:</p>
<pre><code>raise WebDriverException(f"Service {self.path} unexpectedly exited. Status code was: {return_code}")
selenium.common.exceptions.WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 1
</code></pre>
<p>From doing some research, this error was because ChromeDriver <a href="https://stackoverflow.com/questions/61820322/selenium-common-exceptions-webdriverexception-message-service-chromedriver-une">was not being found</a></p>
<p>I can confirm that Chrome and Chromedriver are up to date:
<a href="https://i.stack.imgur.com/bzOtO.png" rel="nofollow noreferrer">Chrome Version</a>
<a href="https://i.stack.imgur.com/WFfYV.png" rel="nofollow noreferrer">ChromeDriver Version</a></p>
<p>I can also confirm that I have ChromeDriver successfully added as a PATH environment variable</p>
<p>I have tried other solutions, such as using a path instead:</p>
<pre><code>import pandas as pd
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
PATH = 'C:\webdrivers\chromedriver.exe'
web = webdriver.Chrome(executable_path=PATH, service_args=["--verbose", "--log-path=D:\\qc1.log"])
url = 'https://www.google.com/'
web.get(url)
</code></pre>
<p>however the same error persists.</p>
<p>I have also tried adding options to the WebDriver, but to no avail.</p>
<p>When running without service_args added, the webpage will briefly open, before closing itself with <a href="https://i.stack.imgur.com/ncUSj.png" rel="nofollow noreferrer">no crash information</a></p>
|
[
{
"answer_id": 74589173,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 0,
"selected": false,
"text": "*args def subt(*num):\n diff = num[0]\n for i in range(1,len(num)):\n diff = diff - num[i]\n return diff\n diff(1,2,3) #=> *num = [1,2,3]\n *args **kwargs"
},
{
"answer_id": 74589212,
"author": "Naveen Kaulwar",
"author_id": 20549546,
"author_profile": "https://Stackoverflow.com/users/20549546",
"pm_score": -1,
"selected": true,
"text": "def subt1(*numbers): # defining a function subt1 and using a non-keyword argument *numbers so that variable number of arguments can be provided by user. All these arguments will be stored as a tuple.\n\ntry: # using try-except to handle the errors. If numbers are given as arguments, then the statements in the try block will get executed.\n\n diff = numbers[0] # assigning the first element/number to the variable diff\n \n for i in range(1,len(numbers)): # iterating through all the given elements/ numbers of a tuple using a for loop\n diff = diff - numbers[i] # performing the subtraction operation for multiple numbers from left to right, for eg, a-b-c = (a-b)-c\n return diff # returning the final value of the above operation\n\nexcept: # if no arguments OR more than one non-numbers are passed, then the statement in the except block will get executed\n return 'please enter numbers as arguments'\n def subt2(*numbers):\n\ntry:\n add = 0 # initializing a variable add with 0\n \n for i in range(1,len(numbers)):\n add = add+ numbers[i] # performing the addition operation for the numbers starting from the index 1\n return numbers[0]-add # returning the final value of subtraction of given numbers, logic : a-b-c = a-(b+c) = a-add(b,c)\n\nexcept:\n return 'please enter numbers as arguments'\n"
},
{
"answer_id": 74589232,
"author": "Someone193",
"author_id": 18256963,
"author_profile": "https://Stackoverflow.com/users/18256963",
"pm_score": 0,
"selected": false,
"text": "def subt(*nums):\n first_num = nums[0] # The first number\n for num in nums[1:]: # index 1 to the last number\n first_num -= num\n return first_num\n\nprint(subt(33, 2, 3, 4, 7)) # -> 17\nprint(subt(13, 7)) # -> 6\n def subt(*nums):\n first_num = nums[0] # The first number\n sum_of_rest = sum(nums[1:]) # The sum of all the number except the first number\n # Or you can say, sum of numbers from index 1 to the last\n\n return first_num - sum_of_rest\n\nprint(subt(33, 2, 3, 4, 7)) # -> 17\nprint(subt(13, 7)) # -> 6\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18530228/"
] |
74,589,091
|
<p>I am meeting a rails problem.</p>
<p>I created a rails folder by this command</p>
<pre><code>rails new airbnb-clone -T -d postgresql --css tailwindcss
</code></pre>
<p>And it gave me these problems</p>
<p>1st</p>
<pre><code>rails turbo:install stimulus:install
rails aborted!
</code></pre>
<p>Second</p>
<pre><code>rails css:install:tailwindcss
rails aborted!
</code></pre>
<p>I thought that when I used the code tailwindcss, it must automatically create the tailwindcss by rails ? So why it had these error ? Should I must install tailwindcss by hand ? Could you please give me some advices?</p>
<p>By the way, here is my rails and ruby v</p>
<p>rails -v 7.0.4
ruby -v 3.1.2</p>
|
[
{
"answer_id": 74589626,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 1,
"selected": false,
"text": "tailwind tailwindcss rails new airbnb-clone -T -d postgresql --css tailwind\n"
},
{
"answer_id": 74595966,
"author": "LihnNguyen",
"author_id": 15527415,
"author_profile": "https://Stackoverflow.com/users/15527415",
"pm_score": 0,
"selected": false,
"text": "rails new airbnb-clone -T -d postgresql -c=tailwind\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15347191/"
] |
74,589,095
|
<p>I use</p>
<pre><code>git remote set-url origin https://ooker777@github.com/QuaCau-TheSphere/LandofSpheres.git
</code></pre>
<p>But why can't I push?</p>
<pre><code>git push
remote: Permission to QuaCau-TheSphere/LandofSpheres.git denied to ooker777.
fatal: unable to access 'https://github.com/QuaCau-TheSphere/LandofSpheres.git/': The requested URL returned error: 403
</code></pre>
<p>I am the creator of the organization and the admin of the repo so I must have permission. I pushed successfully before, so it shouldn't be SSH stuff. I don't understand why it happens today.</p>
|
[
{
"answer_id": 74593188,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "git config --global credential.helper\n manager-core printf \"host=github.com\\nprotocol=https\\nusername=ooker777\" | git credential-manager-core get\n printf \"host=github.com\\nprotocol=https\\nusername=ooker777\\npassword=ghp_yourToken\" | git credential-manager-core store\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3416774/"
] |
74,589,124
|
<p><a href="https://i.stack.imgur.com/qVwsI.png" rel="nofollow noreferrer">Dataset image</a></p>
<p>Please help, I have a dataset in which I have columns Country, Gas and Year from 2019 to 1991. Also attaching the snapshot of the dataset. I want to answer a question that I want to add all the values of a country column wise? For example, for Afghanistan, value should come 56.4 under 2019 (adding 28.79 + 6.23 + 16.37 + 5.01 = 56.4). Now I want it should calculate the result for every year. I have used below code for achieving 2019 data.</p>
<pre><code>df.groupby(by='Country')['2019'].sum()
</code></pre>
<p>This is the output of that code:</p>
<pre><code>Country
---------------------
Afghanistan 56.40
Albania 17.31
Algeria 558.67
Andorra 1.18
Angola 256.10
...
Venezuela 588.72
Vietnam 868.40
Yemen 50.05
Zambia 182.08
Zimbabwe 235.06
</code></pre>
<p>I have group the data country wise and adding the 2019 column values, but how should I add values of other years in single line of code?</p>
<p>Please help.</p>
<p>I can do the code shown here, to add rows and show multiple columns like this but this will be tedious task to do so write each column name.</p>
<pre><code>df.groupby(by='Country')[['2019','2018','2017']].sum()
</code></pre>
|
[
{
"answer_id": 74593188,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "git config --global credential.helper\n manager-core printf \"host=github.com\\nprotocol=https\\nusername=ooker777\" | git credential-manager-core get\n printf \"host=github.com\\nprotocol=https\\nusername=ooker777\\npassword=ghp_yourToken\" | git credential-manager-core store\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19402713/"
] |
74,589,150
|
<p>I'm writing a method to realize bubble sort with recursion, and my base case is "the length of array", in that case, I have to recursively call the function from "0" to <code>array.length-1</code>, however, as I went through the codes from other people, I found them all using the base case "1",and that is running the recursion from <code>array.length</code> to "1". I know both of our recursion run the same number of times and get the same result, but I'm just a bit confused, does it mean my understanding of recursion is wrong ?</p>
<p>my code :</p>
<pre><code> public static void bubbleRecursion(int arr[],int n){
if (n==arr.length){
System.out.println(Arrays.toString(arr));
return;
}
for (int i = 0;i<arr.length-1-n;i++){
if (arr[i]>arr[i+1]){
int temp;
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
bubbleRecursion(arr, n+1);
}
bubbleRecursion(array,0);
</code></pre>
<p>others' code:</p>
<pre><code>public static void sortingRecursion(int[] arr, int n){
if (n == 1){
return;
}
for (int i = 0;i < n-1;i++){
if (arr[i]>arr[i+1]){
int temp;
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
sortingRecursion(arr, n-1);
}
sortingRecursion(array, array.length);
</code></pre>
<p>I then looked up the definition of recursion, it seems that the input should get smaller and smaller every time, but my code is increasing the value of n every time, so now I'm a bit confused, does it mean my code is a wrong answer though the output is correct?</p>
<p>Could anyone help me? thank you</p>
|
[
{
"answer_id": 74593188,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "git config --global credential.helper\n manager-core printf \"host=github.com\\nprotocol=https\\nusername=ooker777\" | git credential-manager-core get\n printf \"host=github.com\\nprotocol=https\\nusername=ooker777\\npassword=ghp_yourToken\" | git credential-manager-core store\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20591456/"
] |
74,589,171
|
<p>I have the following type of strings:
"CanadaUnited States",
"GermanyEnglandSpain"</p>
<p>I want to split them into the countries' names, i.e.:</p>
<p>['Canada', 'United States']
['Germany', 'England', 'Spain']</p>
<p>I have tried using the following regex:</p>
<pre><code>text = "GermanyEnglandSpain"
re.split('[a-z](?=[A-Z])', text)
</code></pre>
<p>and I'm getting:
<code>['German', 'Englan', 'Spain']</code></p>
<p>How can I not lose the last char in every word?]
Thanks!</p>
|
[
{
"answer_id": 74589196,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "re.findall inp = \"CanadaUnited States\"\ncountries = re.findall(r'[A-Z][a-z]+(?: [A-Z][a-z]+)*', inp)\nprint(countries) # ['Canada', 'United States']\n [A-Z][a-z]+ (?: [A-Z][a-z]+)*"
},
{
"answer_id": 74589220,
"author": "frankenapps",
"author_id": 4593433,
"author_profile": "https://Stackoverflow.com/users/4593433",
"pm_score": 1,
"selected": false,
"text": "re.split import re\n\ntext = \"GermanyEnglandSpain\"\nres = re.split('([A-Z][a-z]*)', text)\nres = list(filter(None, res))\nprint(res)\n"
},
{
"answer_id": 74589561,
"author": "Mehmet N",
"author_id": 2656197,
"author_profile": "https://Stackoverflow.com/users/2656197",
"pm_score": 2,
"selected": false,
"text": "import re\ntext = \"GermanyUnited StatesEnglandUnited StatesSpain\"\ntext2=re.sub('([A-Z])', r' \\1', text) #adds a single space before every upper letter\nprint(text2) \n#Germany United States England United States Spain\ntext3=re.sub('\\s{2,}', '*', text2)#replaces 2 or more spaces with * so that we can replace later\nprint(text3)\n#Germany United*States England United*States Spain\ntext4=re.split(' ',text3)#splits the text into list on evert single space\nprint(text4)\n#['', 'Germany', 'United*States', 'England', 'United*States', 'Spain']\ntext5=[]\n\nfor i in text4:\n text5.append(re.sub('\\*', ' ', i)) #replace every * with a single space \ntext5=list(filter(None, text5)) #remove empty elements \n\nprint(text5)\n#['Germany', 'United States', 'England', 'United States', 'Spain']\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14702047/"
] |
74,589,198
|
<p>I am trying to make a loop for a string that contains 16 numbers, idea is to multiply *2 all the pair digits, but while doing that, I get an error of a string. I tried several ways but not succeeding.</p>
<pre><code>cardNumber = input("Enter a 16-digit card number:")
cardNumber = int(cardNumber.replace(" ",""))
#cardNumber = str(cardNumber)
print(cardNumber)
i = 0
for i in range(0, 16, 2):
cardNumber[i] *= 2
print(cardNumber)
</code></pre>
<p>Can you help me to understand this simple issue? I do not understand why is not allowing it.</p>
<p>Thanks for the help</p>
|
[
{
"answer_id": 74589196,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "re.findall inp = \"CanadaUnited States\"\ncountries = re.findall(r'[A-Z][a-z]+(?: [A-Z][a-z]+)*', inp)\nprint(countries) # ['Canada', 'United States']\n [A-Z][a-z]+ (?: [A-Z][a-z]+)*"
},
{
"answer_id": 74589220,
"author": "frankenapps",
"author_id": 4593433,
"author_profile": "https://Stackoverflow.com/users/4593433",
"pm_score": 1,
"selected": false,
"text": "re.split import re\n\ntext = \"GermanyEnglandSpain\"\nres = re.split('([A-Z][a-z]*)', text)\nres = list(filter(None, res))\nprint(res)\n"
},
{
"answer_id": 74589561,
"author": "Mehmet N",
"author_id": 2656197,
"author_profile": "https://Stackoverflow.com/users/2656197",
"pm_score": 2,
"selected": false,
"text": "import re\ntext = \"GermanyUnited StatesEnglandUnited StatesSpain\"\ntext2=re.sub('([A-Z])', r' \\1', text) #adds a single space before every upper letter\nprint(text2) \n#Germany United States England United States Spain\ntext3=re.sub('\\s{2,}', '*', text2)#replaces 2 or more spaces with * so that we can replace later\nprint(text3)\n#Germany United*States England United*States Spain\ntext4=re.split(' ',text3)#splits the text into list on evert single space\nprint(text4)\n#['', 'Germany', 'United*States', 'England', 'United*States', 'Spain']\ntext5=[]\n\nfor i in text4:\n text5.append(re.sub('\\*', ' ', i)) #replace every * with a single space \ntext5=list(filter(None, text5)) #remove empty elements \n\nprint(text5)\n#['Germany', 'United States', 'England', 'United States', 'Spain']\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14918931/"
] |
74,589,200
|
<p>Can anyone point me in the right direction please? My C and Python skills are limited, but I have set up a R-pi3b to run a python program at boot and it is fine. I have also added a script to shut it down easily using GPIO3.</p>
<p>My problem is that once running, the keyboard is ineffective and I cannot get out of the script except by SSH and killing the process, which is fine if the network remains the same, but it has to move between different locations. This means I cannot access the existing Wi-fi I.P. address from the new location.</p>
<p>Is there a simple way (maybe using an IO interrupt) to exit the program and get back to terminal or the GUI so that I can manually alter the wi-fi details and then be able to SSH in?</p>
<p>The Python script running is "picframe" based on 3piD viewer as detailed here: <a href="https://www.thedigitalpictureframe.com/how-to-add-crossfading-slide-transitions-to-your-digital-picture-frame-using-pi3d/" rel="nofollow noreferrer">https://www.thedigitalpictureframe.com/how-to-add-crossfading-slide-transitions-to-your-digital-picture-frame-using-pi3d/</a> which works very well by the way.</p>
<p>I am using Raspbian Buster release as suggested in the above link. PC is Windows 10 64bit.</p>
<p>I have tried various suggestions to allow access by re-writing some parts of the sd card from windows, and tried to follow some tunneling ideas but none have been successful. The only way I seem to be able to change the address is by reloading the whole OS and the program again which is frustrating and time consuming.</p>
<p>As I cannot get to the terminal at bootup there is no way to access it, unless I have missed something very obvious, using the keyboard and the external SSH will not connect either.</p>
<p>Any help would be appreciated.</p>
|
[
{
"answer_id": 74589196,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "re.findall inp = \"CanadaUnited States\"\ncountries = re.findall(r'[A-Z][a-z]+(?: [A-Z][a-z]+)*', inp)\nprint(countries) # ['Canada', 'United States']\n [A-Z][a-z]+ (?: [A-Z][a-z]+)*"
},
{
"answer_id": 74589220,
"author": "frankenapps",
"author_id": 4593433,
"author_profile": "https://Stackoverflow.com/users/4593433",
"pm_score": 1,
"selected": false,
"text": "re.split import re\n\ntext = \"GermanyEnglandSpain\"\nres = re.split('([A-Z][a-z]*)', text)\nres = list(filter(None, res))\nprint(res)\n"
},
{
"answer_id": 74589561,
"author": "Mehmet N",
"author_id": 2656197,
"author_profile": "https://Stackoverflow.com/users/2656197",
"pm_score": 2,
"selected": false,
"text": "import re\ntext = \"GermanyUnited StatesEnglandUnited StatesSpain\"\ntext2=re.sub('([A-Z])', r' \\1', text) #adds a single space before every upper letter\nprint(text2) \n#Germany United States England United States Spain\ntext3=re.sub('\\s{2,}', '*', text2)#replaces 2 or more spaces with * so that we can replace later\nprint(text3)\n#Germany United*States England United*States Spain\ntext4=re.split(' ',text3)#splits the text into list on evert single space\nprint(text4)\n#['', 'Germany', 'United*States', 'England', 'United*States', 'Spain']\ntext5=[]\n\nfor i in text4:\n text5.append(re.sub('\\*', ' ', i)) #replace every * with a single space \ntext5=list(filter(None, text5)) #remove empty elements \n\nprint(text5)\n#['Germany', 'United States', 'England', 'United States', 'Spain']\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613319/"
] |
74,589,261
|
<p>I want to extract data from a tag to simply retrieve the text. Unfortunately I can't extract just the text, I always have links in this one.</p>
<p>Is it possible to remove all of the <code><img></code> and <code><a href></code> tags from my text?</p>
<pre><code><div class="xxx" data-handler="xxx">its a good day
<a class="link" href="https://" title="text">https:// link</a></div>
</code></pre>
<p>I just want to recover this : <code>its a good day</code> and ignore the content of the <code><a href></code> tag in my <code><div></code> tag</p>
<p>Currently I perform the extraction via a <code>beautifulsoup.find('div)</code></p>
|
[
{
"answer_id": 74589334,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 0,
"selected": false,
"text": "<a> previous_siblings NavigableString ' '.join(\n [s for s in soup.select_one('.xxx a').previous_siblings if isinstance(s, NavigableString)]\n)\n from bs4 import Tag, NavigableString, BeautifulSoup\n\nhtml='''\n<div class=\"xxx\" data-handler=\"xxx\"><br>New wallpaper <br>Find over 100+ of <a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div>\n'''\nsoup = BeautifulSoup(html)\n\n' '.join(\n [s for s in soup.select_one('.xxx a').previous_siblings if isinstance(s, NavigableString)]\n)\n .find(text=True)\n .contents[0]\n from bs4 import BeautifulSoup\nhtml='''\n<div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div>\n'''\n\nsoup = BeautifulSoup(html)\n\nsoup.div.find(text=True).strip()\n its a good day\n"
},
{
"answer_id": 74589360,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "re re.sub import re \n\ns1 = '<div class=\"xxx\" data-handler=\"xxx\">its a good day'\ns2 = '<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div>'\n \n \ns1 = re.sub(r'\\<[^()]*\\>', '', s1)\ns2 = re.sub(r'\\<[^()]*\\>', '', s2)\n >>> print(s1)\n... 'its a good day'\n>>> print(s2)\n... ''\n"
},
{
"answer_id": 74589373,
"author": "Mihalych",
"author_id": 20256993,
"author_profile": "https://Stackoverflow.com/users/20256993",
"pm_score": 1,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup\n\n#response = requests.get('your url')\n\nhtml = BeautifulSoup('''<div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a> \n</div>''', 'html.parser')\n\nsoup = html.find_all(class_='xxx')\n\nprint(soup[0].text.split('\\n')[0])\n"
},
{
"answer_id": 74590544,
"author": "user20614895",
"author_id": 20614895,
"author_profile": "https://Stackoverflow.com/users/20614895",
"pm_score": 0,
"selected": false,
"text": "<a> from bs4 import BeautifulSoup\n\nhtml1='''\n<div class=\"xxx\" data-handler=\"xxx\"><br>New wallpaper <br>Find over 100+ of <a class=\"link\" href=\"https://\" title=\"text\">https:// link </a></div>\n'''\nhtml2 = ''' <div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div> '''\n\nhtml3 = ''' <div class=\"xxx\" data-handler=\"xxx\"><br>New wallpaper <br>Find over 100+ of <a class=\"link\" href=\"https://\" title=\"text\">https:// link </a><div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div></div> '''\n\nsoup = BeautifulSoup(html3,'html.parser')\n\n\nfor t in soup.find_all('a', href=True):\n t.decompose()\ntest = soup.find('div',class_='xxx').getText().strip()\n\nprint(test)\n #for html1: New wallpaper Find over 100+ of\n#for html2: its a good day\n#for html3: New wallpaper Find over 100+ of its a good day\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613500/"
] |
74,589,299
|
<p>I need to write a Python program in which the user enters two numbers and receives the LCM and HCF of those numbers. I tried it, and my LCM was correct, but my HCF was not, so could anyone assist me in locating the HCF? Thank you!</p>
<pre><code>num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
def compute_lcm(x, y):
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
print("The L.C.M. is", compute_lcm(num1, num2))
</code></pre>
|
[
{
"answer_id": 74589352,
"author": "evanstjabadi",
"author_id": 13271830,
"author_profile": "https://Stackoverflow.com/users/13271830",
"pm_score": 1,
"selected": false,
"text": "num1 = 36\nnum2 = 60\nhcf = 1\n\nfor i in range(1, min(num1, num2)):\n if num1 % i == 0 and num2 % i == 0:\n hcf = i\nprint(\"Hcf of\", num1, \"and\", num2, \"is\", hcf)\n# HCF of 36 and 60 is 12\n"
},
{
"answer_id": 74589531,
"author": "m00racle",
"author_id": 14685186,
"author_profile": "https://Stackoverflow.com/users/14685186",
"pm_score": 2,
"selected": false,
"text": "\"\"\" \nfinding HCF\n\"\"\"\n\ndef hcfLoop(x : int, y : int) -> int:\n \"\"\" \n finding hinghest common factor using loop\n returns int\n \"\"\"\n while (x % y) > 0:\n remainder = x % y\n x = y\n y = remainder\n \n return y\n\ndef hcfRecurs(x : int, y : int) -> int:\n \"\"\" \n find highest common factor using recursion\n \"\"\"\n if y == 0 :\n return x\n else:\n return hcfRecurs(y, x % y)\n\n\nx = 1220\ny = 516\nprint(f\"the HCF for {x} and {y} using loop: {hcfLoop(x,y)}\")\nprint(f\"the HCF for {x} and {y} using recursion: {hcfRecurs(x,y)}\")\n the HCF for 1220 and 516 using loop: 4\nthe HCF for 1220 and 516 using recursion: 4\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20237989/"
] |
74,589,331
|
<p><a href="https://i.stack.imgur.com/x2YQn.png" rel="nofollow noreferrer">I tried everything I could but somehow it still doesnt work can anyone help?</a></p>
|
[
{
"answer_id": 74589352,
"author": "evanstjabadi",
"author_id": 13271830,
"author_profile": "https://Stackoverflow.com/users/13271830",
"pm_score": 1,
"selected": false,
"text": "num1 = 36\nnum2 = 60\nhcf = 1\n\nfor i in range(1, min(num1, num2)):\n if num1 % i == 0 and num2 % i == 0:\n hcf = i\nprint(\"Hcf of\", num1, \"and\", num2, \"is\", hcf)\n# HCF of 36 and 60 is 12\n"
},
{
"answer_id": 74589531,
"author": "m00racle",
"author_id": 14685186,
"author_profile": "https://Stackoverflow.com/users/14685186",
"pm_score": 2,
"selected": false,
"text": "\"\"\" \nfinding HCF\n\"\"\"\n\ndef hcfLoop(x : int, y : int) -> int:\n \"\"\" \n finding hinghest common factor using loop\n returns int\n \"\"\"\n while (x % y) > 0:\n remainder = x % y\n x = y\n y = remainder\n \n return y\n\ndef hcfRecurs(x : int, y : int) -> int:\n \"\"\" \n find highest common factor using recursion\n \"\"\"\n if y == 0 :\n return x\n else:\n return hcfRecurs(y, x % y)\n\n\nx = 1220\ny = 516\nprint(f\"the HCF for {x} and {y} using loop: {hcfLoop(x,y)}\")\nprint(f\"the HCF for {x} and {y} using recursion: {hcfRecurs(x,y)}\")\n the HCF for 1220 and 516 using loop: 4\nthe HCF for 1220 and 516 using recursion: 4\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19337513/"
] |
74,589,346
|
<p>If I have a list of variables and each variable is assigned to an equation,
how can I print the variable itself from the list not the result of the equation</p>
<p>For example:</p>
<pre><code>x = 1 + 1
y = 2 + 2
z = 3 + 3
list = [x, y, z]
print(list[0])
print(list[1])
print(list[2])
</code></pre>
<p>Should print out:</p>
<pre><code>x
y
z
</code></pre>
<p>Instead of:</p>
<pre><code>2
4
6
</code></pre>
|
[
{
"answer_id": 74589407,
"author": "Emilia Zero",
"author_id": 20434184,
"author_profile": "https://Stackoverflow.com/users/20434184",
"pm_score": 1,
"selected": false,
"text": "x = 1 + 1\ny = 2 + 2\nz = 3 + 3\n x = \"x\"\ny = \"y\"\nz = \"z\"\n"
},
{
"answer_id": 74589539,
"author": "gimix",
"author_id": 15844296,
"author_profile": "https://Stackoverflow.com/users/15844296",
"pm_score": 0,
"selected": false,
"text": "my_dict = {}\nmy_dict['x'] = 1 + 1\nmy_dict['y'] = 2 + 2\nmy_dict['z'] = 3 + 3\n\n','.join(my_dict.keys()) #'x,y,z'\nsum(my_dict.values()) # 12\n"
},
{
"answer_id": 74589847,
"author": "Emilia Zero",
"author_id": 20434184,
"author_profile": "https://Stackoverflow.com/users/20434184",
"pm_score": 0,
"selected": false,
"text": "def dna_content(seq):\n A = [\"A\", (seq.count(\"A\") / len(seq)) * 100]\n\n T = [\"T\", (seq.count(\"T\") / len(seq)) * 100]\n G = [\"G\", (seq.count(\"G\") / len(seq)) * 100]\n C = [\"C\", (seq.count(\"C\") / len(seq)) * 100]\n bases = [A, T, G, C]\n for i in bases:\n print(str(i[0]) + \" content is: \" + str(i[1]))\n x = 1 + 1\ny = 2 + 2\nz = 3 + 3\nlist = [\"x\", \"y\", \"z\"]\n\n\nfor i in list:\n print(i, globals()[i])\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613506/"
] |
74,589,392
|
<p>I am just learning python and making a calculator and the tutorial says float instead of int. what is a floating number</p>
<p>Why not just use int</p>
|
[
{
"answer_id": 74589407,
"author": "Emilia Zero",
"author_id": 20434184,
"author_profile": "https://Stackoverflow.com/users/20434184",
"pm_score": 1,
"selected": false,
"text": "x = 1 + 1\ny = 2 + 2\nz = 3 + 3\n x = \"x\"\ny = \"y\"\nz = \"z\"\n"
},
{
"answer_id": 74589539,
"author": "gimix",
"author_id": 15844296,
"author_profile": "https://Stackoverflow.com/users/15844296",
"pm_score": 0,
"selected": false,
"text": "my_dict = {}\nmy_dict['x'] = 1 + 1\nmy_dict['y'] = 2 + 2\nmy_dict['z'] = 3 + 3\n\n','.join(my_dict.keys()) #'x,y,z'\nsum(my_dict.values()) # 12\n"
},
{
"answer_id": 74589847,
"author": "Emilia Zero",
"author_id": 20434184,
"author_profile": "https://Stackoverflow.com/users/20434184",
"pm_score": 0,
"selected": false,
"text": "def dna_content(seq):\n A = [\"A\", (seq.count(\"A\") / len(seq)) * 100]\n\n T = [\"T\", (seq.count(\"T\") / len(seq)) * 100]\n G = [\"G\", (seq.count(\"G\") / len(seq)) * 100]\n C = [\"C\", (seq.count(\"C\") / len(seq)) * 100]\n bases = [A, T, G, C]\n for i in bases:\n print(str(i[0]) + \" content is: \" + str(i[1]))\n x = 1 + 1\ny = 2 + 2\nz = 3 + 3\nlist = [\"x\", \"y\", \"z\"]\n\n\nfor i in list:\n print(i, globals()[i])\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613677/"
] |
74,589,398
|
<p>I'm trying to implement a login form in a Spring boot application. It has an email and a password field. The email field failed to get user input, here is the form:</p>
<pre><code> <form th:action="@{/login}" method="get" th:object="${loginForm}" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="text" th:field="*{email}" name="q" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control" required/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</div>
</form>
</code></pre>
<p>Here is the controller:</p>
<pre><code> @GetMapping("login")
public ModelAndView login(Model model, @RequestParam(name = "q", required = false) Optional<String> email) {
Optional<UserDto> aUser;
System.out.println(email);
if (email.isPresent()) {
aUser = userService.getAUserByEmail(email.get());
model.addAttribute("user", aUser);
var mv = new ModelAndView("user/user-list", model.asMap());
return mv;
} else {
model.addAttribute("loginForm", new LoginForm());
return new ModelAndView("/login/login-form", model.asMap());
}
}
</code></pre>
<p>I thought the <code>@RequestParam(name = "q")</code> and <code>name="q"</code> in html would do the job, but I always get <code>Optional.empty</code> for email. Any idea what's wrong here?</p>
<p>UPDATE:
From the answers I changed controller to this:</p>
<pre><code> @GetMapping("login")
public ModelAndView login(Model model, LoginForm loginForm) {
Optional<UserDto> aUser;
if (loginForm.getEmail() != null) {
aUser = userService.getAUserByEmail(loginForm.getEmail());
model.addAttribute("user", aUser);
var mv = new ModelAndView("user/user-list", model.asMap());
return mv;
} else {
model.addAttribute("loginForm", new LoginForm());
return new ModelAndView("/login/login-form", model.asMap());
}
}
</code></pre>
<p><code>login-form.html</code> to this:</p>
<pre><code> <form th:action="@{/login}" method="get" th:object="${loginForm}" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="text" th:field="*{email}" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control" required/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</div>
</form>
</code></pre>
<p>I also have <code>LoginForm.java</code> like this</p>
<pre><code>@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginForm {
private String email;
private String password;
}
</code></pre>
<p>but still not getting user email field input?</p>
|
[
{
"answer_id": 74589407,
"author": "Emilia Zero",
"author_id": 20434184,
"author_profile": "https://Stackoverflow.com/users/20434184",
"pm_score": 1,
"selected": false,
"text": "x = 1 + 1\ny = 2 + 2\nz = 3 + 3\n x = \"x\"\ny = \"y\"\nz = \"z\"\n"
},
{
"answer_id": 74589539,
"author": "gimix",
"author_id": 15844296,
"author_profile": "https://Stackoverflow.com/users/15844296",
"pm_score": 0,
"selected": false,
"text": "my_dict = {}\nmy_dict['x'] = 1 + 1\nmy_dict['y'] = 2 + 2\nmy_dict['z'] = 3 + 3\n\n','.join(my_dict.keys()) #'x,y,z'\nsum(my_dict.values()) # 12\n"
},
{
"answer_id": 74589847,
"author": "Emilia Zero",
"author_id": 20434184,
"author_profile": "https://Stackoverflow.com/users/20434184",
"pm_score": 0,
"selected": false,
"text": "def dna_content(seq):\n A = [\"A\", (seq.count(\"A\") / len(seq)) * 100]\n\n T = [\"T\", (seq.count(\"T\") / len(seq)) * 100]\n G = [\"G\", (seq.count(\"G\") / len(seq)) * 100]\n C = [\"C\", (seq.count(\"C\") / len(seq)) * 100]\n bases = [A, T, G, C]\n for i in bases:\n print(str(i[0]) + \" content is: \" + str(i[1]))\n x = 1 + 1\ny = 2 + 2\nz = 3 + 3\nlist = [\"x\", \"y\", \"z\"]\n\n\nfor i in list:\n print(i, globals()[i])\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8720421/"
] |
74,589,431
|
<p>Need help:</p>
<p>I have a number (let's say 550) and need to create a perfect distributed SEQUENCE of length N where SUM of numbers will give this number (550).</p>
<p>Something like: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100</p>
<p>The only input I have is the length of sequence and the final sum of it's numbers.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74590217,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "x y =INDEX(SEQUENCE(B1, 1)*A1/B1)\n =INDEX(SEQUENCE(B1, 1, 0)*A1/(B1-1))\n"
},
{
"answer_id": 74591824,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile": "https://Stackoverflow.com/users/3894917",
"pm_score": 1,
"selected": true,
"text": "=MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))\n =lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r)))))\n =lambda(intpairs,makearray(rows(intpairs),n,lambda(r,c,index(intpairs,r,1)+(c-1)*index(intpairs,r,2))))(lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))))\n =sequence(1,n,F10,G10)\n"
},
{
"answer_id": 74600573,
"author": "Egor Menshov",
"author_id": 20613659,
"author_profile": "https://Stackoverflow.com/users/20613659",
"pm_score": 1,
"selected": false,
"text": "=INDEX(SEQUENCE(length;1;1)*2*sum/length/(length+1);;)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613659/"
] |
74,589,437
|
<p>I have a table with the columns as below -</p>
<p><a href="https://i.stack.imgur.com/nHv9f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nHv9f.png" alt="enter image description here" /></a></p>
<p>There are rows showing the allocation of various people under various project. The months (columns) can extend to Dec,20 and continue on from Jan,21 in the same pattern as above.</p>
<p>One Staff can be tagged to any number of projects in a given month.</p>
<p>Now to prepare a report on this I would like to format the data as below -</p>
<p><a href="https://i.stack.imgur.com/ED6lM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ED6lM.png" alt="enter image description here" /></a></p>
<p>So basically for each project that a staff is assigned to, I would like to duplicate each of the 12 months for each year and show the designated allocation.</p>
<p>The name of the table containing the data is [Staff Allocation] and it has the following fields - [Staff ID],[Project ID],[Jan,20],[Feb,20],[Mar,20],[Apr,20] and so on as per the image above.</p>
<p>Is there any way to do this?</p>
<p>Any help on this is highly appreciated.</p>
<p>Adding in the sample data as below -</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Staff ID</th>
<th>Project ID</th>
<th>Jan,20</th>
<th>Feb,20</th>
<th>Mar,20</th>
<th>Apr,20</th>
<th>May,20</th>
<th>Jun,20</th>
<th>Jul,20</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>20</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>100</td>
<td>80</td>
<td>10</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>30</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>20</td>
<td>90</td>
<td>100</td>
</tr>
<tr>
<td>2</td>
<td>20</td>
<td>100</td>
<td>100</td>
<td>100</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>50</td>
<td>80</td>
<td>100</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>60</td>
<td>15</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>20</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>70</td>
<td>5</td>
<td>0</td>
<td>100</td>
<td>100</td>
<td>80</td>
<td>0</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<pre><code>create table test(StaffID int, ProjectID int, Jan20 int, Feb20 int, Mar20 int, Apr20 int, May20 int, Jun20 int, Jul20 int)
insert into test values
(1,20,0,0,0,100,80,10,0),
(1,30,0,0,0,0,20,90,100),
(2,20,100,100,100,0,0,0,0),
(3,50,80,100,0,0,0,0,0),
(3,60,15,0,0,0,20,0,0),
(3,70,5,0,100,100,80,0,0)
Select * from test
</code></pre>
|
[
{
"answer_id": 74590217,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "x y =INDEX(SEQUENCE(B1, 1)*A1/B1)\n =INDEX(SEQUENCE(B1, 1, 0)*A1/(B1-1))\n"
},
{
"answer_id": 74591824,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile": "https://Stackoverflow.com/users/3894917",
"pm_score": 1,
"selected": true,
"text": "=MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))\n =lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r)))))\n =lambda(intpairs,makearray(rows(intpairs),n,lambda(r,c,index(intpairs,r,1)+(c-1)*index(intpairs,r,2))))(lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))))\n =sequence(1,n,F10,G10)\n"
},
{
"answer_id": 74600573,
"author": "Egor Menshov",
"author_id": 20613659,
"author_profile": "https://Stackoverflow.com/users/20613659",
"pm_score": 1,
"selected": false,
"text": "=INDEX(SEQUENCE(length;1;1)*2*sum/length/(length+1);;)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10599073/"
] |
74,589,441
|
<p>I'm trying to pull data from tables in a Word document to Excel. I'm able to pull it as text but I don't know how to pull the numbers as numbers.</p>
<pre><code>Sub extractData()
Dim wd As New Word.Application
Dim doc As Word.Document
Dim sh As Worksheet
wd.Visible = True
Set doc = wd.Documents.Open(ActiveWorkbook.Path & "C:\Users\itays\Desktop\TTd.docx")
Set tbl = doc.Tables
Set sh = ActiveSheet
For i = 1 To 17
sh.Cells(i, 1).Value = tbl(5).Rows(i).Cells(1).Range.Text
Next
For i = 1 To 17
sh.Cells(i, 2).Value = tbl(5).Rows(i).Cells(2).Range.Text
Next
Range("a:e").Columns.AutoFit
doc.Close
End Sub
</code></pre>
<p>Basically, I need the second <code>For</code> command to pull the data as a number and not as a text.</p>
|
[
{
"answer_id": 74590217,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "x y =INDEX(SEQUENCE(B1, 1)*A1/B1)\n =INDEX(SEQUENCE(B1, 1, 0)*A1/(B1-1))\n"
},
{
"answer_id": 74591824,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile": "https://Stackoverflow.com/users/3894917",
"pm_score": 1,
"selected": true,
"text": "=MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))\n =lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r)))))\n =lambda(intpairs,makearray(rows(intpairs),n,lambda(r,c,index(intpairs,r,1)+(c-1)*index(intpairs,r,2))))(lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))))\n =sequence(1,n,F10,G10)\n"
},
{
"answer_id": 74600573,
"author": "Egor Menshov",
"author_id": 20613659,
"author_profile": "https://Stackoverflow.com/users/20613659",
"pm_score": 1,
"selected": false,
"text": "=INDEX(SEQUENCE(length;1;1)*2*sum/length/(length+1);;)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10007174/"
] |
74,589,500
|
<p>I have a problem regarding of mini program that will return me the exit status of my child process in case of error occuring during execve.</p>
<pre><code>#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main ()
{
char *argv[] = {"ls",NULL};
char *envp[] = {NULL};
int status;
int pid;
int err;
pid = fork();
if (pid == 0)
{
execve("/usr/bin/lds", argv, envp);
perror("error");
}
else
{
waitpid(pid, &status, 0);
printf("%d\n", status);
if (WIFEXITED(status))
err = WEXITSTATUS(status);
exit(status);
}
}
</code></pre>
<p>The above code is just demo to make me understand how process exit status work, the problem is when when I put a wrong path such /usr/bin/lds the status code print is 0 while an error occured in my child process, while when a command is not found in bash the status code sent back is 127 my question is how to make it return 127 as bash does when a bad command is entered ?</p>
|
[
{
"answer_id": 74590217,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "x y =INDEX(SEQUENCE(B1, 1)*A1/B1)\n =INDEX(SEQUENCE(B1, 1, 0)*A1/(B1-1))\n"
},
{
"answer_id": 74591824,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile": "https://Stackoverflow.com/users/3894917",
"pm_score": 1,
"selected": true,
"text": "=MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))\n =lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r)))))\n =lambda(intpairs,makearray(rows(intpairs),n,lambda(r,c,index(intpairs,r,1)+(c-1)*index(intpairs,r,2))))(lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))))\n =sequence(1,n,F10,G10)\n"
},
{
"answer_id": 74600573,
"author": "Egor Menshov",
"author_id": 20613659,
"author_profile": "https://Stackoverflow.com/users/20613659",
"pm_score": 1,
"selected": false,
"text": "=INDEX(SEQUENCE(length;1;1)*2*sum/length/(length+1);;)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16715270/"
] |
74,589,512
|
<p>Here is the code:</p>
<pre><code>list_a = [3,2,5,7,4,1]
def insertion_sort(list_a):
indexing_length = range(1,len(list_a))
for i in indexing_length:
value_to_sort = list_a[i]
while list_a[i-1] > value_to_sort and i>0:
list_a[i], list_a[i-1] = list_a[i-1], list_a[i]
i = i - 1
return list_a
</code></pre>
<p>I understand the logic to the rest of the algorithm but I can't seem to grasp the logic for doing i = i - 1. Can someone explain please?</p>
|
[
{
"answer_id": 74590217,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "x y =INDEX(SEQUENCE(B1, 1)*A1/B1)\n =INDEX(SEQUENCE(B1, 1, 0)*A1/(B1-1))\n"
},
{
"answer_id": 74591824,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile": "https://Stackoverflow.com/users/3894917",
"pm_score": 1,
"selected": true,
"text": "=MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))\n =lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r)))))\n =lambda(intpairs,makearray(rows(intpairs),n,lambda(r,c,index(intpairs,r,1)+(c-1)*index(intpairs,r,2))))(lambda(pairs,filter(pairs,index(pairs,,2)=int(index(pairs,,2))))(MAKEARRAY(S/n,2,LAMBDA(r,c,if(c=1,r,2/(n-1)*(S/n-r))))))\n =sequence(1,n,F10,G10)\n"
},
{
"answer_id": 74600573,
"author": "Egor Menshov",
"author_id": 20613659,
"author_profile": "https://Stackoverflow.com/users/20613659",
"pm_score": 1,
"selected": false,
"text": "=INDEX(SEQUENCE(length;1;1)*2*sum/length/(length+1);;)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19930097/"
] |
74,589,566
|
<p>I have a table that is something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>amount</th>
<th>status</th>
<th>timestamp</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>A</td>
<td>0</td>
</tr>
<tr>
<td>10</td>
<td>B</td>
<td>1</td>
</tr>
<tr>
<td>15</td>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>10</td>
<td>C</td>
<td>3</td>
</tr>
<tr>
<td>12</td>
<td>D</td>
<td>4</td>
</tr>
<tr>
<td>20</td>
<td>A</td>
<td>5</td>
</tr>
<tr>
<td>25</td>
<td>B</td>
<td>6</td>
</tr>
<tr>
<td>17</td>
<td>C</td>
<td>7</td>
</tr>
<tr>
<td>19</td>
<td>D</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p>The amounts have no restriction (other than being a number). And status lines can have duplicates (the 'B' in the example).</p>
<p>What I want is to sum over everything between 'A' status. So the result should be</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sum</th>
<th>timestamp</th>
</tr>
</thead>
<tbody>
<tr>
<td>57</td>
<td>1</td>
</tr>
<tr>
<td>81</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<p>I need this for ansi-sql (Spark)</p>
|
[
{
"answer_id": 74589897,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 1,
"selected": true,
"text": "with data(ord, amount, status) as (\n select 1, 10, 'A' from dual union all\n select 2, 10, 'B' from dual union all\n select 3, 15, 'B' from dual union all\n select 4, 10, 'C' from dual union all\n select 5, 12, 'D' from dual union all\n select 6, 20, 'A' from dual union all\n select 7, 25, 'B' from dual union all\n select 8, 17, 'C' from dual union all\n select 9, 19, 'D' from dual \n),\npdata as (\n select d.*, case status when 'A' then lv else last_value(lv) ignore nulls over(order by ord) end as llv\n from (\n select d.*, \n nvl(last_value(case status when 'A' then ord end) over(partition by status order by ord\n RANGE BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING\n ), case status when 'A' then ord - 1 \n end) as lv\n from data d\n ) d\n)\nselect sum(amount) from pdata\nwhere llv is not null\ngroup by llv\n;\n\nsum(amount)\n57\n81\n"
},
{
"answer_id": 74589946,
"author": "Rodrigue",
"author_id": 18370039,
"author_profile": "https://Stackoverflow.com/users/18370039",
"pm_score": 0,
"selected": false,
"text": "Tmp \nDROP PROCEDURE IF EXISTS summing;\nDELIMITER |\nCREATE PROCEDURE summing()\n BEGIN\n DECLARE _begin INT DEFAULT NULL;\n DECLARE _end INT DEFAULT NULL;\n \n SELECT `timestamp` INTO _begin FROM Tmp WHERE status='A' ORDER BY `timestamp` LIMIT 1;\n \n IF _begin IS NOT NULL THEN\n \n SELECT `timestamp` INTO _end FROM Tmp WHERE status='A' AND `timestamp` > _begin ORDER BY `timestamp` LIMIT 1;\n WHILE _end IS NOT NULL DO\n SELECT SUM(amount) FROM Tmp WHERE `timestamp` > _begin AND `timestamp` < _end;\n SET _begin = _end;\n SET _end = NULL;\n SELECT `timestamp` INTO _end FROM Tmp WHERE status='A' AND `timestamp` > _begin ORDER BY `timestamp` LIMIT 1;\n END WHILE;\n END IF;\n END|\nDELIMITER ;\n\nCALL summing ();\n"
},
{
"answer_id": 74592629,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 1,
"selected": false,
"text": "with data(ts, amount, status) as (\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF'), 10, 'A' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+1/24, 10, 'B' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+2/24, 15, 'B' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+3/24, 10, 'C' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+4/24, 12, 'D' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+5/24, 20, 'A' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+6/24, 25, 'B' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+7/24, 17, 'C' from dual union all\n select to_timestamp('27-11-2022 12:00:00.00', 'DD-MM-YYYY HH24:MI:SS.FF')+8/24, 19, 'D' from dual \n)\nselect res from (\n select \n status, ts, sum(amount) over(partition by s) as res\n from (\n select \n d.*, sum(flag) over(order by ts) as s\n from (select d.*, decode(status,'A',1,0) as flag from data d) d\n ) d\n)\nwhere status = 'A'\norder by ts\n;\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129750/"
] |
74,589,582
|
<p>The project is ASP.NET Core MVC, .NET 6. I'm trying to seed a role if it's not there yet and create a user that will have this role. I tried every way to twist the code and it doesn't work. When I run the app for the first time, the following error appears on the line where the user is added to the role:</p>
<blockquote>
<p>Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while saving the entity changes. See the inner exception for details.'</p>
</blockquote>
<blockquote>
<p>SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUserRoles_AspNetUsers_UserId". The conflict occurred in database "ViewMovies", table "dbo.AspNetUsers", column 'Id'.
The statement has been terminated.</p>
</blockquote>
<p>Then when I check the database the new role is created, but the user is not.</p>
<p>This all happens in Program.cs. Here I create scope and use it to get role manager and user manager. Then, if the role does not exist, create it and a new user. After that add the new role to the new user.</p>
<pre><code>var app = builder.Build();
var scope = app.Services
.GetService<IServiceScopeFactory>()
?.CreateScope();
if (scope is not null)
{
using (scope)
{
var roleManager = scope
.ServiceProvider
.GetService<RoleManager<IdentityRole>>();
var userManager = scope
.ServiceProvider
.GetRequiredService<UserManager<User>>();
Task
.Run(async () =>
{
if (await roleManager.RoleExistsAsync("test"))
{
return;
}
var role = new IdentityRole { Name = "test" };
await roleManager.CreateAsync(role);
const string testEmail = "test@role.com";
const string testPassword = "test123";
var user = new User
{
Email = testEmail,
UserName = testEmail
};
await userManager.CreateAsync(user, testPassword);
await userManager.AddToRoleAsync(user, role.Name);
})
.GetAwaiter()
.GetResult();
}
}
</code></pre>
<p>I have registered these services:</p>
<pre><code>builder.Services.AddDefaultIdentity<User>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<ViewMoviesDbContext>();
</code></pre>
|
[
{
"answer_id": 74615748,
"author": "FadoBagi",
"author_id": 14364144,
"author_profile": "https://Stackoverflow.com/users/14364144",
"pm_score": 2,
"selected": true,
"text": "test123 Test123+"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14364144/"
] |
74,589,647
|
<p>I had an excel script to search for files in a command.</p>
<p>I found this example on the forum, the statement says that to search for a file by name, you need to write down the name and send (*) but when requested, it does not find anything</p>
<pre><code>Get-ChildItem -Path "C:\\Folder\\test\*"
</code></pre>
<p>What can I do to simplify the code and make it much faster. Wait 10 minutes to find a file out of 10000. this is very long</p>
<p>I have a folder with 10,000 files, and excel searches through VBA for a script in almost 2-3 seconds.
When to script in PowerShell via</p>
<pre><code>
$find = Get-ChildItem -Path "C:\\Folder"
for ($f=0; $f -lt $find.Count; $f++){
$path_name = $find\[$f\].Name
if($path_name-eq 'test'){
Write Host 'success'
}
}
</code></pre>
<p>ut it turns out sooooooo long, the script hangs for 10 minutes and does not respond, and maybe he will be lucky to answer.
How can I find a file by filter using</p>
<pre><code>Get-ChildItem
</code></pre>
|
[
{
"answer_id": 74615748,
"author": "FadoBagi",
"author_id": 14364144,
"author_profile": "https://Stackoverflow.com/users/14364144",
"pm_score": 2,
"selected": true,
"text": "test123 Test123+"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14735028/"
] |
74,589,652
|
<p>Since the <code>std::forward_list</code> is implemented as a single-linked list, its iterator should be just a pointer to the underlying element ± some offset.</p>
<p>Is there a way to convert a pointer to an element on a list to the iterator to this element without iterating through the entire list?</p>
<pre class="lang-cpp prettyprint-override"><code>#include <forward_list>
template<typename T>
typename std::forward_list<T>::iterator makeIterator(T *element)
{
// magic here
}
int main()
{
std::forward_list<int> list;
list.emplace_front(101);
auto i = makeIterator(&list.front());
return i == list.begin() ? 0 : 1;
}
</code></pre>
|
[
{
"answer_id": 74615748,
"author": "FadoBagi",
"author_id": 14364144,
"author_profile": "https://Stackoverflow.com/users/14364144",
"pm_score": 2,
"selected": true,
"text": "test123 Test123+"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3052438/"
] |
74,589,665
|
<p>Can ANSI escape code SGR 38 - Set foreground color with argument 2;r;g;b be used with print function?
Example of use with code 33 is of course</p>
<pre><code>OKBLUE = '\033[94m'
</code></pre>
<p>I would like to use 038 instead to be able to use any RGB color. Is that posible?</p>
<p>I tried</p>
<pre><code>GREEN = '\038[2;0;153;0m'
ENDC = '\033[0m'
print(f"{GREEN} some text {ENDC}")
</code></pre>
<p>Expected to change the color of "some text" in green</p>
|
[
{
"answer_id": 74589877,
"author": "su yong kim",
"author_id": 20612454,
"author_profile": "https://Stackoverflow.com/users/20612454",
"pm_score": -1,
"selected": false,
"text": "print('\\033[90m' + 'hello' + '\\033[96m' + ' there?' )\n"
},
{
"answer_id": 74601731,
"author": "S3DEV",
"author_id": 6340496,
"author_profile": "https://Stackoverflow.com/users/6340496",
"pm_score": 2,
"selected": true,
"text": "# Print Hello! in lime green text.\nprint('\\033[38;2;146;255;12mHello!\\033[0m')\n# ^\n# |\n# \\ The 38 goes here, to indicate a foreground colour.\n\n# Print Hello! in white text on a fuschia background.\nprint('\\033[48;2;246;45;112mHello!\\033[0m') \n \\033[38;2;146;255;12mHello!\\033[0m\n^ ^ ^ ^ ^ ^ ^ ^ ^ \n| | | R G B | | |\n| | | | | | \\ Reset the colour to default\n| | | | | | \n| | | | | \\ Escape character\n| | | | |\n| | | \\ R;G;B \\ Text to print\n| | |\n| | \\ Indicate the following sequence is RGB\n| |\n| \\ Code to instruct the setting of an 8 or 24-bit foreground (text) colour\n|\n\\ Escape character\n 38;2 38;5 \\033 \\x1b 38 48"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3963267/"
] |
74,589,702
|
<p>I am working on project which is asp.net mvc core. I want to replace string list of duplicate values to one with comma separated,</p>
<pre><code>List<string> stringList = surveylist.Split('&').ToList();
</code></pre>
<p>I have string list
This generate following output:</p>
<pre><code>7=55
6=33
5=MCC
4=GHI
3=ABC
1003=DEF
1003=ABC
1=JKL
</code></pre>
<p>And I want to change output like this</p>
<pre><code>7=55
6=33
5=MCC
4=GHI
3=ABC
1003=DEF,ABC
1=JKL
</code></pre>
<p>Duplicate items values should be comma separated.</p>
|
[
{
"answer_id": 74589877,
"author": "su yong kim",
"author_id": 20612454,
"author_profile": "https://Stackoverflow.com/users/20612454",
"pm_score": -1,
"selected": false,
"text": "print('\\033[90m' + 'hello' + '\\033[96m' + ' there?' )\n"
},
{
"answer_id": 74601731,
"author": "S3DEV",
"author_id": 6340496,
"author_profile": "https://Stackoverflow.com/users/6340496",
"pm_score": 2,
"selected": true,
"text": "# Print Hello! in lime green text.\nprint('\\033[38;2;146;255;12mHello!\\033[0m')\n# ^\n# |\n# \\ The 38 goes here, to indicate a foreground colour.\n\n# Print Hello! in white text on a fuschia background.\nprint('\\033[48;2;246;45;112mHello!\\033[0m') \n \\033[38;2;146;255;12mHello!\\033[0m\n^ ^ ^ ^ ^ ^ ^ ^ ^ \n| | | R G B | | |\n| | | | | | \\ Reset the colour to default\n| | | | | | \n| | | | | \\ Escape character\n| | | | |\n| | | \\ R;G;B \\ Text to print\n| | |\n| | \\ Indicate the following sequence is RGB\n| |\n| \\ Code to instruct the setting of an 8 or 24-bit foreground (text) colour\n|\n\\ Escape character\n 38;2 38;5 \\033 \\x1b 38 48"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613852/"
] |
74,589,728
|
<p>Calculus exam results are announced and your result is above the announced average. You want to have an idea about the letter grade you will get, and to do this you ask everyone you know about their exam results. You want to calculate the median of the results, which will give you some more idea about the distribution of the grades so that you can take a better guess about your letter grade.</p>
<p>Write a function named find_median that takes a list of integers as the distribution of the grades and returns an integer as the median of this distribution. If the list has an even length, the function must return the higher of the two middle elements.</p>
<p>Hint: You can use the built-in function sorted() to get the grades in the increasing order.</p>
<p>thank you for your helping in advance.</p>
|
[
{
"answer_id": 74589877,
"author": "su yong kim",
"author_id": 20612454,
"author_profile": "https://Stackoverflow.com/users/20612454",
"pm_score": -1,
"selected": false,
"text": "print('\\033[90m' + 'hello' + '\\033[96m' + ' there?' )\n"
},
{
"answer_id": 74601731,
"author": "S3DEV",
"author_id": 6340496,
"author_profile": "https://Stackoverflow.com/users/6340496",
"pm_score": 2,
"selected": true,
"text": "# Print Hello! in lime green text.\nprint('\\033[38;2;146;255;12mHello!\\033[0m')\n# ^\n# |\n# \\ The 38 goes here, to indicate a foreground colour.\n\n# Print Hello! in white text on a fuschia background.\nprint('\\033[48;2;246;45;112mHello!\\033[0m') \n \\033[38;2;146;255;12mHello!\\033[0m\n^ ^ ^ ^ ^ ^ ^ ^ ^ \n| | | R G B | | |\n| | | | | | \\ Reset the colour to default\n| | | | | | \n| | | | | \\ Escape character\n| | | | |\n| | | \\ R;G;B \\ Text to print\n| | |\n| | \\ Indicate the following sequence is RGB\n| |\n| \\ Code to instruct the setting of an 8 or 24-bit foreground (text) colour\n|\n\\ Escape character\n 38;2 38;5 \\033 \\x1b 38 48"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15963929/"
] |
74,589,759
|
<p>How can I get the local time in my country Indonesia?</p>
<pre><code>var date = new Date();
var local = date.getLocal();
</code></pre>
<p>I know the above code doesn't work, how do I retrieve it? I want to take (WIB) western Indonesian time / Waktu Indonesia Barat.</p>
<p>Please help me, all answers are like precious gold.</p>
|
[
{
"answer_id": 74589788,
"author": "raiyan22",
"author_id": 9550867,
"author_profile": "https://Stackoverflow.com/users/9550867",
"pm_score": 0,
"selected": false,
"text": "worldtimeapi.org/ function getTime(url) {\n return new Promise((resolve, reject) => {\n const req = new XMLHttpRequest();\n req.open(\"GET\", url);\n req.onload = () =>\n req.status === 200\n ? resolve(req.response)\n : reject(Error(req.statusText));\n req.onerror = (e) => reject(Error(`Network Error: ${e}`));\n req.send();\n });\n}\n let url = \"http://worldtimeapi.org/api/timezone/Pacific/Auckland\";\n\ngetTime(url)\n .then((response) => {\n let dateObj = JSON.parse(response);\n let dateTime = dateObj.datetime;\n console.log(dateObj);\n console.log(dateTime);\n })\n .catch((err) => {\n console.log(err);\n });\n"
},
{
"answer_id": 74589822,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "const time = new Date().toLocaleTimeString('en-US', { timeZone: 'Asia/Jakarta' });\nconsole.log(time);"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20491248/"
] |
74,589,770
|
<p>I'm trying to render the string array <code>keys</code> into a React component. <code>keys</code> are the keys that the user presses (but I just hard-coded them for the sake of this example).</p>
<pre><code>import { useState } from "react";
import * as ReactDOM from "react-dom";
let keys = ["a", "b"];
function App() {
let [keysState, setKeysState] = useState([]);
setKeysState((keysState = keys));
return (
<div>
{keysState.map((key) => (
<li>{key}</li>
))}{" "}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.createRoot(rootElement).render(<App />);
</code></pre>
<p>But I'm getting this error:</p>
<blockquote>
<p>Too many re-renders. React limits the number of renders to prevent an infinite loop.</p>
</blockquote>
<p>I know I can avoid this error by creating and onClick handler ... but I don't want to display <code>keysState</code> on click. I want it to display and re-render immediately when <code>keys</code> changes.</p>
<p>Live code: <a href="https://codesandbox.io/s/react-18-with-createroot-forked-vgkeiu?file=/src/index.js:0-504" rel="nofollow noreferrer">https://codesandbox.io/s/react-18-with-createroot-forked-vgkeiu?file=/src/index.js:0-504</a></p>
|
[
{
"answer_id": 74589885,
"author": "Ed de Almeida",
"author_id": 5021963,
"author_profile": "https://Stackoverflow.com/users/5021963",
"pm_score": 0,
"selected": false,
"text": "setKeyState useState keyState setState const [keyState, setKeyState] = useState([\"a\",\"b\"]);\n keyState [\"a\",\"b\"] setKeyState useEffect useEffect(() => {\n // Things to perform when `stateKeys` changes\n},[stateKeys])\n [stateKeys]"
},
{
"answer_id": 74590017,
"author": "monim",
"author_id": 16632344,
"author_profile": "https://Stackoverflow.com/users/16632344",
"pm_score": 3,
"selected": true,
"text": "setKeysState Too many re-renders useState() let [keysState, setKeysState] = useState(keys);\n useState Hook let keys = [\"a\", \"b\"];\n\nfunction App() {\n\n return (\n <div>\n {keys?.map((key) => (\n <li>{key}</li>\n ))}\n </div>\n );\n}\n"
},
{
"answer_id": 74590214,
"author": "MalwareMoon",
"author_id": 20241005,
"author_profile": "https://Stackoverflow.com/users/20241005",
"pm_score": 1,
"selected": false,
"text": "useState [] setKeysState setKeysState keysState setKeysState(newValue) const [keysState, setKeysState] = useState(keys);\n"
},
{
"answer_id": 74590261,
"author": "criszz77",
"author_id": 14056591,
"author_profile": "https://Stackoverflow.com/users/14056591",
"pm_score": 2,
"selected": false,
"text": "useState setKeysState import * as ReactDOM from \"react-dom\";\n\nlet keys = [\"a\", \"b\"];\n\nfunction App() {\n\n return (\n <div>\n {keys.map((key) => (\n <li>{key}</li>\n ))}\n </div>\n );\n}\n\nconst rootElement = document.getElementById(\"root\");\n\nReactDOM.createRoot(rootElement).render(<App />);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122536/"
] |
74,589,771
|
<p>So, I have a method called 'room' in my views.py file.</p>
<p>I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well.</p>
<p>How can I do that?</p>
<p>Views.py</p>
<pre><code>def room(request):
rooms = Rooms.objects.all()
photos = RoomImage.objects.all()
context = {'rooms':rooms, 'photos':photos}
return render(request, 'hotelbook/room.html', context)
</code></pre>
|
[
{
"answer_id": 74589885,
"author": "Ed de Almeida",
"author_id": 5021963,
"author_profile": "https://Stackoverflow.com/users/5021963",
"pm_score": 0,
"selected": false,
"text": "setKeyState useState keyState setState const [keyState, setKeyState] = useState([\"a\",\"b\"]);\n keyState [\"a\",\"b\"] setKeyState useEffect useEffect(() => {\n // Things to perform when `stateKeys` changes\n},[stateKeys])\n [stateKeys]"
},
{
"answer_id": 74590017,
"author": "monim",
"author_id": 16632344,
"author_profile": "https://Stackoverflow.com/users/16632344",
"pm_score": 3,
"selected": true,
"text": "setKeysState Too many re-renders useState() let [keysState, setKeysState] = useState(keys);\n useState Hook let keys = [\"a\", \"b\"];\n\nfunction App() {\n\n return (\n <div>\n {keys?.map((key) => (\n <li>{key}</li>\n ))}\n </div>\n );\n}\n"
},
{
"answer_id": 74590214,
"author": "MalwareMoon",
"author_id": 20241005,
"author_profile": "https://Stackoverflow.com/users/20241005",
"pm_score": 1,
"selected": false,
"text": "useState [] setKeysState setKeysState keysState setKeysState(newValue) const [keysState, setKeysState] = useState(keys);\n"
},
{
"answer_id": 74590261,
"author": "criszz77",
"author_id": 14056591,
"author_profile": "https://Stackoverflow.com/users/14056591",
"pm_score": 2,
"selected": false,
"text": "useState setKeysState import * as ReactDOM from \"react-dom\";\n\nlet keys = [\"a\", \"b\"];\n\nfunction App() {\n\n return (\n <div>\n {keys.map((key) => (\n <li>{key}</li>\n ))}\n </div>\n );\n}\n\nconst rootElement = document.getElementById(\"root\");\n\nReactDOM.createRoot(rootElement).render(<App />);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14680196/"
] |
74,589,773
|
<p>If I have a list of strings such as this:</p>
<pre><code>names = ["Alice", "Bob", "Charlie", "Darren"]
</code></pre>
<p>How would I find how many of these strings contain the letter 'a'?</p>
<p>I tried using the count function</p>
<pre><code>names.count("a")
</code></pre>
<p>But this only output the amount of elements that <strong>were</strong> 'a' rather than <strong>contained</strong> 'a'.</p>
|
[
{
"answer_id": 74589790,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "loop names = [\"Alice\", \"Bob\", \"Charlie\", \"Darren\"]\n\ncount=0\n\nfor i in range(len(names)):\n if 'a' in list(names[i]):\n count+=1\n \nprint(count)\n >>> 2 \n"
},
{
"answer_id": 74589811,
"author": "Sam",
"author_id": 16660603,
"author_profile": "https://Stackoverflow.com/users/16660603",
"pm_score": 1,
"selected": false,
"text": "'a' print(len([x for x in names if 'a' in x]))\n 2"
},
{
"answer_id": 74589863,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 0,
"selected": false,
"text": "names = [\"Alice\", \"Bob\", \"Charlie\", \"Darren\"]\ncount = 0\n\nfor name in names:\n if 'a' in name:\n count += 1\n\nprint(count)\n a in b sum print(sum('a' in name for name in names))\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614004/"
] |
74,589,824
|
<p>I wrote a function that generates a table after feeding it a list.</p>
<p>It is part of a web scraping script I'm working on.</p>
<p>The function works (not the best but good enough for its purpose) but is there a better way to achieve better/similar/same result?</p>
<p>For example, here's a list I would want to turn into a table:</p>
<pre><code>listings =
["Search Result", "Advanced Search", "Item Trader Location Price Last Seen", "Sealed Blacksmithing Writ", "Rewards 356 Vouchers",
"Level 1", "@rscus2001", "Shadowfen: Stormhold", "Ghost Sea Trading Co", "71,200", "X", "1", "=", "71,200 3 Hour ago", "Sealed Blacksmithing Writ", "Rewards 328 Vouchers",
"Level 1", "@Deirdre531", "Grahtwood: Elden Root", "piston", "100,000", "X", "1", "=", "100,000 6 Hour ago", "Sealed Blacksmithing Writ", "Rewards 328 Vouchers",
"Level 1", "@Araxas", "Luminous Legion", "100,000", "X", "1", "=", "100,000 9 Hour ago", "Sealed Blacksmithing Writ", "Rewards 356 Vouchers",
"Level 1", "@CaffeinatedMayhem", "Craglorn: Belkarth", "Masser's Merchants", "25,000", "X", "1", "=", "25,000 13 Hour ago", "Sealed Blacksmithing Writ", "Rewards 287 Vouchers",
"Level 1", "@Gregori_Weissteufel", "Wrothgar: Morkul Stronghold", "The Cutthroat Mutineers", "45,000", "X", "1", "=", "45,000 13 Hour ago", "<", "1", ">"]
</code></pre>
<p>Result:</p>
<pre><code> 0 1 2 3 4 5 6 7 8 9 10
0 Sealed Blacksmithing Writ Rewards 356 Vouchers Level 1 @rscus2001 Shadowfen: Stormhold Ghost Sea Trading Co 71,200 X 1 = 71,200 3 Hour ago
1 Sealed Blacksmithing Writ Rewards 328 Vouchers Level 1 @Deirdre531 Grahtwood: Elden Root piston 100,000 X 1 = 100,000 6 Hour ago
2 Sealed Blacksmithing Writ Rewards 328 Vouchers Level 1 @Araxas Luminous Legion 100,000 X 1 = 100,000 9 Hour ago None
3 Sealed Blacksmithing Writ Rewards 356 Vouchers Level 1 @CaffeinatedMayhem Craglorn: Belkarth Masser's Merchants 25,000 X 1 = 25,000 13 Hour ago
4 Sealed Blacksmithing Writ Rewards 287 Vouchers Level 1 @Gregori_Weissteufel Wrothgar: Morkul Stronghold The Cutthroat Mutineers 45,000 X 1 = 45,000 13 Hour ago
</code></pre>
<p>Below is my code:</p>
<pre><code>import re
import pandas as pd
pd.set_option('display.max_columns', None)
pd.options.display.width=None
def MakeTable(listings):
hour_idx = [i for i, item in enumerate(listings) if re.search(r"([0-9,]*\s[0-9]*\s(Minute|Hour)\sago|[0-9,]*\sNow)", item)]
if len(hour_idx) == 1:
ls = [listings[3:hour_idx[0]+1]]
elif len(hour_idx) == 2:
ls = [listings[3:hour_idx[0]+1],listings[hour_idx[0]+1:hour_idx[1]+1]]
elif len(hour_idx) == 3:
ls = [listings[3:hour_idx[0]+1],listings[hour_idx[0]+1:hour_idx[1]+1],listings[hour_idx[1]+1:hour_idx[2]+1]]
elif len(hour_idx) == 4:
ls = [listings[3:hour_idx[0]+1],listings[hour_idx[0]+1:hour_idx[1]+1],listings[hour_idx[1]+1:hour_idx[2]+1],listings[hour_idx[2]+1:hour_idx[3]+1]]
else:
ls = [listings[3:hour_idx[0]+1],listings[hour_idx[0]+1:hour_idx[1]+1],listings[hour_idx[1]+1:hour_idx[2]+1],listings[hour_idx[2]+1:hour_idx[3]+1],listings[hour_idx[3]+1:hour_idx[4]+1]]
df = pd.DataFrame(ls)
print(df)
</code></pre>
|
[
{
"answer_id": 74590068,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 3,
"selected": true,
"text": "list comprehensions zip def MakeTable(listings):\n\n hour_idx = [i for i, item in enumerate(listings) if re.search(r\"([0-9,]*\\s[0-9]*\\s(Minute|Hour)\\sago|[0-9,]*\\sNow)\", item)]\n \n ls = [listings[3:hour_idx[0]+1]]\n \n ls_2 = [x[y[i]+1:y[i+1]+1] for (x, y, i) in zip(listings, hour_idx, range(len(hour_idx)-1))]\n \n ls = ls.append(ls_2)\n\n df = pd.DataFrame(ls)\n \n print(df)\n"
},
{
"answer_id": 74590226,
"author": "Glycerine",
"author_id": 235146,
"author_profile": "https://Stackoverflow.com/users/235146",
"pm_score": 1,
"selected": false,
"text": "import re\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.options.display.width=None\n\nhuman_time_re = re.compile(r\"([0-9,]*\\s[0-9]*\\s(Minute|Hour)\\sago|[0-9,]*\\sNow)\")\n\n\ndef make_table(listings):\n hour_idx = [i for i, item in enumerate(listings) if human_time_re.search(item)]\n\n hour_key = lambda key: hour_idx[key] + 1\n idx = lambda key, key2=0: listings[key:hour_key(key2)]\n idx_more = lambda key=0, key2=1: listings[hour_key(key):hour_key(key2)]\n\n ls = (idx(3),) + tuple(idx_more(i, i+1) for i in range(len(hour_idx) - 1))\n return ls\n\n\nres = make_table(listings)\nls = pd.DataFrame(res)\nprint(res)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20002373/"
] |
74,589,825
|
<p>I had tried to imitate to this below tips to display the IconButton the same as below image:</p>
<p><a href="https://i.stack.imgur.com/aHW8m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHW8m.png" alt="enter image description here" /></a></p>
<p>These are links I had made reference to:
<a href="https://stackoverflow.com/questions/52777164/how-to-set-background-color-for-an-icon-button">How to set background color for an icon button?</a>
<a href="https://dartpad.dev/?null_safety=true&id=6182feb015bbb179e08bf5eb61cbabac" rel="nofollow noreferrer">https://dartpad.dev/?null_safety=true&id=6182feb015bbb179e08bf5eb61cbabac</a></p>
<p>This is my code:</p>
<pre><code>import 'package:cached_network_image/cached_network_image.dart';
import 'package:fakebook_frontend/screens/home/widgets/ProfileAvatar.dart';
import 'package:flutter/material.dart';
import 'package:fakebook_frontend/models/Models.dart';
class OnlineUsers extends StatelessWidget {
final List<User> onlineUsers;
const OnlineUsers({Key? key, required this.onlineUsers}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: 80, // mong muốn không fix cứng
color: Colors.white,
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 4),
child: Material(
color: Colors.transparent,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: onlineUsers.length,
itemBuilder: (BuildContext context, int index) {
if(index == 0) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Stack(
alignment: Alignment(0,-1),
children: [
CircleAvatar(
radius: 22.0,
backgroundImage: CachedNetworkImageProvider(onlineUsers[0].imageUrl),
),
Positioned(
right: 1.0,
bottom: 0.0,
child: Ink(
decoration: ShapeDecoration(
color: Colors.blue,
shape: CircleBorder(),
),
child: IconButton(
padding: EdgeInsets.zero,
constraints: BoxConstraints(),
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
icon: Icon(Icons.add_circle),
iconSize: 16,
color: Colors.white,
onPressed: () {
print("hello");
},
),
),
),
],
),
Text('Tin của bạn', style: TextStyle(fontSize: 10, fontWeight: FontWeight.normal, color: Colors.black45)),
],
);
}
return Padding(
padding: EdgeInsets.symmetric(horizontal: 6),
child: ProfileAvatar(avtUrl: onlineUsers[index].imageUrl, name: onlineUsers[index].name, isActive: true));
}),
),
);
}
}
</code></pre>
<p>Please notice to the first IconButton to see which Widget is error.
<a href="https://i.stack.imgur.com/mxyCT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxyCT.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/qDY8b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qDY8b.png" alt="enter image description here" /></a></p>
<p>Please help me to draw the same as that above image. Thank you very much</p>
|
[
{
"answer_id": 74590068,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 3,
"selected": true,
"text": "list comprehensions zip def MakeTable(listings):\n\n hour_idx = [i for i, item in enumerate(listings) if re.search(r\"([0-9,]*\\s[0-9]*\\s(Minute|Hour)\\sago|[0-9,]*\\sNow)\", item)]\n \n ls = [listings[3:hour_idx[0]+1]]\n \n ls_2 = [x[y[i]+1:y[i+1]+1] for (x, y, i) in zip(listings, hour_idx, range(len(hour_idx)-1))]\n \n ls = ls.append(ls_2)\n\n df = pd.DataFrame(ls)\n \n print(df)\n"
},
{
"answer_id": 74590226,
"author": "Glycerine",
"author_id": 235146,
"author_profile": "https://Stackoverflow.com/users/235146",
"pm_score": 1,
"selected": false,
"text": "import re\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.options.display.width=None\n\nhuman_time_re = re.compile(r\"([0-9,]*\\s[0-9]*\\s(Minute|Hour)\\sago|[0-9,]*\\sNow)\")\n\n\ndef make_table(listings):\n hour_idx = [i for i, item in enumerate(listings) if human_time_re.search(item)]\n\n hour_key = lambda key: hour_idx[key] + 1\n idx = lambda key, key2=0: listings[key:hour_key(key2)]\n idx_more = lambda key=0, key2=1: listings[hour_key(key):hour_key(key2)]\n\n ls = (idx(3),) + tuple(idx_more(i, i+1) for i in range(len(hour_idx) - 1))\n return ls\n\n\nres = make_table(listings)\nls = pd.DataFrame(res)\nprint(res)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20582783/"
] |
74,589,833
|
<p>I have an array of objects as</p>
<pre><code>const arr = [
{
"id": 2,
"key": "cc_edit"
},
{
"id": 4,
"key": "cc_upload"
},
{
"id": 4,
"key": "cc_download"
},
{
"id": 1,
"key": "cc_project"
}]
</code></pre>
<p>I want a object with unique key as key of new object and its values as array. Something like:</p>
<pre><code>{
2 : ["cc_edit"],
4 : ["cc_upload", "cc_download"],
1 : ["cc_project"],
},
</code></pre>
<p>How it can be achieved?</p>
|
[
{
"answer_id": 74589845,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 2,
"selected": false,
"text": "Array#reduce const arr = [ { \"id\": 2, \"key\": \"cc_edit\" }, { \"id\": 4, \"key\": \"cc_upload\" }, { \"id\": 4, \"key\": \"cc_download\" }, { \"id\": 1, \"key\": \"cc_project\" } ];\n\nconst res = arr.reduce((acc, { id, key }) => ({\n ...acc,\n [id]: [...(acc[id] ?? []), key]\n}), {});\n\nconsole.log(res);"
},
{
"answer_id": 74589849,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "const arr = [\n\n {\n \"id\": 2,\n \"key\": \"cc_edit\"\n },\n {\n \"id\": 4,\n \"key\": \"cc_upload\"\n },\n {\n \"id\": 4,\n \"key\": \"cc_download\"\n },\n {\n \"id\": 1,\n \"key\": \"cc_project\"\n }\n]\n\nconst reducedArr = arr.reduce((acc, curr) => {\n const [key, value] = [curr.id, curr.key]\n \n if(key in acc){\n acc[key].push(value)\n } else {\n acc[key] = [value]\n }\n \n return acc\n}, {})\n\nconsole.log(reducedArr)"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5951227/"
] |
74,589,841
|
<p>i have two dataframes, i wanna iterate through the first one, and if a condition is checked, I move to the second dataframe and see if another condition is checked (in the same rowxcolumn as the first dataframe)</p>
<p>this would be dataframe 1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>XY00</td>
<td>AB80</td>
<td>XY01</td>
</tr>
<tr>
<td>1</td>
<td>FY34</td>
<td>XY60</td>
<td>XY91</td>
</tr>
<tr>
<td>2</td>
<td>AB46</td>
<td>AC40</td>
<td>NY23</td>
</tr>
<tr>
<td>3</td>
<td>XY70</td>
<td>AB23</td>
<td>DG60</td>
</tr>
</tbody>
</table>
</div>
<p>this would be dataframe 2, they have the same id and idx, but different column names, although the same length</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>e1</th>
<th>e2</th>
<th>e3</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>2003-12-09</td>
<td>2005-01-01</td>
<td>2006-12-14</td>
</tr>
<tr>
<td>1</td>
<td>2004-11-09</td>
<td>2002-01-01</td>
<td>1999-07-10</td>
</tr>
<tr>
<td>2</td>
<td>2012-02-13</td>
<td>2011-08-22</td>
<td>2003-03-16</td>
</tr>
<tr>
<td>3</td>
<td>2003-01-17</td>
<td>2005-01-01</td>
<td>2017-09-30</td>
</tr>
</tbody>
</table>
</div>
<p>the ideal output would be</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>XY00</td>
<td>AB80</td>
<td>XY01</td>
</tr>
<tr>
<td>3</td>
<td>XY70</td>
<td>AB23</td>
<td>DG60</td>
</tr>
</tbody>
</table>
</div>
<p>so only the values from dataframe 1 that start with 'XY' and that are older than '2003-01-01' in the corresponding column in dataframe 2</p>
<p>i try this for loop, but it outputs an empty dataframe</p>
<pre><code>new_df = pd.DataFrame(data = None, columns = df1.columns)
for ind, row in df1.iterrows():
if ((ind,row) == ("XY00")):
for ind2, row2 in df2.iterrows():
if((ind2,row2) >= ("2003-01-01")):
new_df = new_df.append(row)
</code></pre>
|
[
{
"answer_id": 74589845,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 2,
"selected": false,
"text": "Array#reduce const arr = [ { \"id\": 2, \"key\": \"cc_edit\" }, { \"id\": 4, \"key\": \"cc_upload\" }, { \"id\": 4, \"key\": \"cc_download\" }, { \"id\": 1, \"key\": \"cc_project\" } ];\n\nconst res = arr.reduce((acc, { id, key }) => ({\n ...acc,\n [id]: [...(acc[id] ?? []), key]\n}), {});\n\nconsole.log(res);"
},
{
"answer_id": 74589849,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "const arr = [\n\n {\n \"id\": 2,\n \"key\": \"cc_edit\"\n },\n {\n \"id\": 4,\n \"key\": \"cc_upload\"\n },\n {\n \"id\": 4,\n \"key\": \"cc_download\"\n },\n {\n \"id\": 1,\n \"key\": \"cc_project\"\n }\n]\n\nconst reducedArr = arr.reduce((acc, curr) => {\n const [key, value] = [curr.id, curr.key]\n \n if(key in acc){\n acc[key].push(value)\n } else {\n acc[key] = [value]\n }\n \n return acc\n}, {})\n\nconsole.log(reducedArr)"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521289/"
] |
74,589,860
|
<p>I'm trying to create a leaderboard system by using a merge sort algorithm that sorts the scores in ascending order and then sorts the usernames by their score. I then use a for loop that displays the scores in descending order. The code in the image works perfectly fine when each user has a unique score and duplicate scores do not exist. However, I am having a problem when more than one user has the same score (i.e. there are duplicate scores).</p>
<p>For example, if two users have the same score (in this case 5), the wrong username is displayed. I believe this is because it only looks at the first occurrence of the sorted score. Hence, it's overwriting the original name. Is there any way I can skip the first occurrence of the duplicate number after it has been visited?</p>
<pre><code>string[] UsernameAndScoresArray = System.IO.File.ReadAllLines(@"UsernamesAndScores.txt");
string[] UnsortedUsernamesArray = new string[UsernameAndScoresArray.Length];
int[] UnsortedScoresArray = new int[UsernameAndScoresArray.Length];
string UsernameAndScore = "";
string Username = "";
int Score = 0;
int position = 0;
for (int i = 0; i < UsernameAndScoresArray.Length; i++)
{
//Locates the username and scores and stores them in an 'unsorted array'
UsernameAndScore = UsernameAndScoresArray[i];
position = UsernameAndScore.IndexOf(':');
Username = UsernameAndScore.Substring(0, position);
UnsortedUsernamesArray[i] = Username;
position = UsernameAndScore.IndexOf(':');
Score = int.Parse(UsernameAndScore.Remove(0, position + 1));
UnsortedScoresArray[i] = Score;
}
//Sorts the Scores in ascending order using the merge sort algorithm
SortedArray = MergeSort(UnsortedScoresArray);
SortedUsernames = new string[SortedArray.Length];
for (int i = 0; i < UnsortedScoresArray.Length; i++)
{
for (int a = 0; a < SortedArray.Length; a++)
{
if (UnsortedScoresArray[i] == SortedArray[a])
{
//The usernames are sorted based on the scores
SortedUsernames[a] = UnsortedUsernamesArray[i];
}
}
}
int place = 0;
for (int i = SortedArray.Length - 1; i >= 0; i--)
{
//The place, username and number of points are displayed in descending order
place++;
Username = SortedUsernames[i];
Score = SortedArray[i];
ListBoxLeaderBoardPlaceAndUser.Items.Add(place + ": " + Username);
ListBoxLeaderboardScore.Items.Add(Score);
}
</code></pre>
<pre><code>//This is an example of the error
UnsortedScoresArray[] = {46, 7, 5, 10, 5}
UnsortedUsernamesArray[] = {User1, User2, User3, User4, User5}
SortedScoresArray[] = {5, 5, 7, 10, 46}
SortedUsernamesArray[] = {User5, User5, User2, User4, User1}
</code></pre>
<p>It should say <code>SortedUsernamesArray[] = {User3, User5, User2, User4, User1}</code></p>
|
[
{
"answer_id": 74589845,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 2,
"selected": false,
"text": "Array#reduce const arr = [ { \"id\": 2, \"key\": \"cc_edit\" }, { \"id\": 4, \"key\": \"cc_upload\" }, { \"id\": 4, \"key\": \"cc_download\" }, { \"id\": 1, \"key\": \"cc_project\" } ];\n\nconst res = arr.reduce((acc, { id, key }) => ({\n ...acc,\n [id]: [...(acc[id] ?? []), key]\n}), {});\n\nconsole.log(res);"
},
{
"answer_id": 74589849,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "const arr = [\n\n {\n \"id\": 2,\n \"key\": \"cc_edit\"\n },\n {\n \"id\": 4,\n \"key\": \"cc_upload\"\n },\n {\n \"id\": 4,\n \"key\": \"cc_download\"\n },\n {\n \"id\": 1,\n \"key\": \"cc_project\"\n }\n]\n\nconst reducedArr = arr.reduce((acc, curr) => {\n const [key, value] = [curr.id, curr.key]\n \n if(key in acc){\n acc[key].push(value)\n } else {\n acc[key] = [value]\n }\n \n return acc\n}, {})\n\nconsole.log(reducedArr)"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20613987/"
] |
74,589,883
|
<p>I have array of array double but it won't add element after using <code>.plusElement</code>or <code>.plus</code>. code below inside from view model that returns it.data which is a list of object</p>
<h3>Code</h3>
<pre><code>var ageEntry : Int
val dataObject : Array<Array<Double>> = arrayOf()
for (dataWeight in it.data!!){
ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
dataObject.plusElement(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
Log.d("DATA_SERIES_BARU", "setupViewInstance: ${dataObject.contentToString()}")
}
</code></pre>
<h3>Log</h3>
<p><a href="https://i.stack.imgur.com/CP1n2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CP1n2.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74590934,
"author": "Irgi Ahmad Maulana",
"author_id": 7354428,
"author_profile": "https://Stackoverflow.com/users/7354428",
"pm_score": -1,
"selected": false,
"text": "fun <T> appendArray(arr: Array<T>, element: T): Array<T?> {\n val array = arr.copyOf(arr.size + 1)\n array[arr.size] = element\n return array\n }\n appendArray(copyDataObject, arrayOf(ageEntry,arrayOf(arrayOf(2.0, 3.0)))\n"
},
{
"answer_id": 74591138,
"author": "Emanuel Moecklin",
"author_id": 534471,
"author_profile": "https://Stackoverflow.com/users/534471",
"pm_score": 1,
"selected": false,
"text": "it.data?.fold(ArrayList<Array<Double>>()) { list, dataWeight ->\n val ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()\n list.add(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))\n list\n}\n toTypedArray()"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7354428/"
] |
74,589,913
|
<p>I am trying to perform a search in the XML file in order to check if a specific group policy is linked to a few OUs.</p>
<p>The format of the OU is <strong>"OU=XXXXX-Name,OU=DEMO OU,dc=domain,dc=local"</strong></p>
<p>I managed to get the full distinguishedname property of each OU and i kept only the first part of it</p>
<p><strong>OU=XXXXX-Name</strong>,</p>
<p>discarding the rest and the "OU=" part so i am left with the display name which i need</p>
<p>I am a bit confused while struggling to create an "If condition" where i am using the</p>
<pre><code>GPO-Report -XML
</code></pre>
<p>output to search and check the value in section and see if it matches with the target OU name so i can determine if the GPO is already linked to the specific OU</p>
<p>The XML file has the section below</p>
<pre><code><LinksTo>
<SOMName>XXXXX-Name</SOMName>
<SOMPath>domain.local/DEMO OUs</SOMPath>
<Enabled>true</Enabled>
<NoOverride>false</NoOverride>
</LinksTo>
</code></pre>
<p>Any help would be much appreciated cause i ve spend a good amount of hours circling around this issue, trying to figure out how regular expressions will help me achieve that.</p>
<p>PS I am not an expert in code but i try my best to get into it.</p>
<p>I have tried a few regular expression examples without any luck.</p>
<p><strong>UPDATE</strong></p>
<p>Apologies for the incomplete post (i am still new in here)</p>
<p>I think i managed to make it work by adding 2 lines of code. My code as follows:</p>
<pre><code> Clear-Host
$gpoName = "TestGPO"
$oulist=(Get-Content C:\temp\ou.txt|foreach {
Get-ADOrganizationalUnit -Filter "name -like `"*$_*`"" -Properties distinguishedname|`
select -ExpandProperty distinguishedname}) -replace '^OU=|,.*$'
$xmlgpo=Get-GPO $gpoName |Get-GPOReport -ReportType XML
foreach ($item in $oulist){
if ($xmlgpo -match $item){
Write-Warning "GPO '$gponame' has a link already to '$item'"
}
else{
Write-Warning "No link to OU '$item' found"
}
}
</code></pre>
|
[
{
"answer_id": 74590934,
"author": "Irgi Ahmad Maulana",
"author_id": 7354428,
"author_profile": "https://Stackoverflow.com/users/7354428",
"pm_score": -1,
"selected": false,
"text": "fun <T> appendArray(arr: Array<T>, element: T): Array<T?> {\n val array = arr.copyOf(arr.size + 1)\n array[arr.size] = element\n return array\n }\n appendArray(copyDataObject, arrayOf(ageEntry,arrayOf(arrayOf(2.0, 3.0)))\n"
},
{
"answer_id": 74591138,
"author": "Emanuel Moecklin",
"author_id": 534471,
"author_profile": "https://Stackoverflow.com/users/534471",
"pm_score": 1,
"selected": false,
"text": "it.data?.fold(ArrayList<Array<Double>>()) { list, dataWeight ->\n val ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()\n list.add(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))\n list\n}\n toTypedArray()"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601902/"
] |
74,589,991
|
<p>I want to create a plot that looks like this:
<a href="https://i.stack.imgur.com/jrTCX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jrTCX.png" alt="enter image description here" /></a></p>
<pre><code>x=1:20
y=sample(20)
df <- tibble(x=x,y=y)
ggplot(df,aes(x,y))+
geom_smooth()+
geom_point()
</code></pre>
<p>But the codes unabled to show legends.
Could anyone help me, thanks!</p>
|
[
{
"answer_id": 74590934,
"author": "Irgi Ahmad Maulana",
"author_id": 7354428,
"author_profile": "https://Stackoverflow.com/users/7354428",
"pm_score": -1,
"selected": false,
"text": "fun <T> appendArray(arr: Array<T>, element: T): Array<T?> {\n val array = arr.copyOf(arr.size + 1)\n array[arr.size] = element\n return array\n }\n appendArray(copyDataObject, arrayOf(ageEntry,arrayOf(arrayOf(2.0, 3.0)))\n"
},
{
"answer_id": 74591138,
"author": "Emanuel Moecklin",
"author_id": 534471,
"author_profile": "https://Stackoverflow.com/users/534471",
"pm_score": 1,
"selected": false,
"text": "it.data?.fold(ArrayList<Array<Double>>()) { list, dataWeight ->\n val ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()\n list.add(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))\n list\n}\n toTypedArray()"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17878237/"
] |
74,590,053
|
<p>Probably a stupid question but I have no idea how to do this.</p>
<p>Consider the following game, in which a balanced die with six sides numbered from 1 to 6 is rolled. If a 4 or 1 is rolled, you lose 50 euros. If you roll 2 or 3, nothing happens. If you roll 5, you win 50 euros. If you roll 6, you win 16×50 euros.</p>
<p>We would like to know how much money you can expect to win per game on average. Setting the seed to 990, simulate 5649 repetitions of the game.</p>
<p>Calculate the average of the winnings in these repetitions, as an estimate of the expected value of the winning in the game. Indicate this value circled to 2 decimal places.</p>
|
[
{
"answer_id": 74590073,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 1,
"selected": false,
"text": "#Simulation of the dice roll\nset.seed(990);dice_roll <- sample(1:6,5649,replace = TRUE)\n\nlibrary(dplyr)\n\ndf <- tibble(dice_roll = dice_roll)\n\ndf %>% \n mutate(\n #Setting each dice roll to their respective result\n result = case_when(\n dice_roll == 6 ~ (16*50),\n dice_roll == 5 ~ 50,\n (dice_roll == 2 | dice_roll == 3) ~ 0,\n (dice_roll == 1 | dice_roll == 4) ~ -50,\n )\n ) %>% \n # The global average\n summarise(average = round(mean(result),2)) %>% \n pull(average)\n\n[1] 121.47\n"
},
{
"answer_id": 74591410,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "set.seed(990)\n\nrolls <- sample(6, 5649, TRUE)\n\nwin <- integer(5649)\nwin[rolls %in% c(1, 4)] <- -50\nwin[rolls == 5] <- 50\nwin[rolls == 6] <- 16*50\nmean(win)\n#> [1] 121.4728\n prizes <- c(-50, 0, 0, -50, 50, 16*50)\n\nwin <- prizes[rolls]\nmean(win)\n#> [1] 121.4728\n round(mean(win), 2)\n#> 121.47\n"
},
{
"answer_id": 74591961,
"author": "Baraliuh",
"author_id": 11157753,
"author_profile": "https://Stackoverflow.com/users/11157753",
"pm_score": 1,
"selected": false,
"text": "-50/3 + 0/3 + 50/6 + 16*50/6\n[1] 125\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357700/"
] |
74,590,058
|
<p>I want to change the</p>
<pre><code>id="navbar"
</code></pre>
<p>font color while the page is in dark mode, and make the font color back when the page switches to light mode. The switch is made with js:</p>
<pre><code>const onClick = () => {
theme.value = theme.value === 'light'
? 'dark'
: 'light'
setPreference()
}
const getColorPreference = () => {
if (localStorage.getItem(storageKey))
return localStorage.getItem(storageKey)
else
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
const setPreference = () => {
localStorage.setItem(storageKey, theme.value)
reflectPreference()
}
const reflectPreference = () => {
document.firstElementChild
.setAttribute('data-theme', theme.value)
document
.querySelector('#theme-toggle')
?.setAttribute('aria-label', theme.value)
}
const theme = {
value: getColorPreference()
}
</code></pre>
<p>and the background is set here</p>
<pre><code>html {
background: linear-gradient(135deg, #a1c4fd 10%, #c2e9fb 90%);
block-size: 100%;
color-scheme: light;
background-attachment: fixed;
}
html[data-theme=dark] {
background: linear-gradient(135deg, #061c43 10%, #08101f 90%);
color-scheme: dark;
background-attachment: fixed;
}
</code></pre>
<pre><code>#navbar ul li[data-theme=dark] {
padding: 10px;
border-radius: 25px;
float: right;
margin-left: 3px;
margin-right: 8px;
font-weight: 500;
color: white;
box-shadow: -5px -5px 8px #ffffff60,5px 5px 10px #00000060;
}
</code></pre>
<p>that's not doing anything. what am i missing?</p>
|
[
{
"answer_id": 74590073,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 1,
"selected": false,
"text": "#Simulation of the dice roll\nset.seed(990);dice_roll <- sample(1:6,5649,replace = TRUE)\n\nlibrary(dplyr)\n\ndf <- tibble(dice_roll = dice_roll)\n\ndf %>% \n mutate(\n #Setting each dice roll to their respective result\n result = case_when(\n dice_roll == 6 ~ (16*50),\n dice_roll == 5 ~ 50,\n (dice_roll == 2 | dice_roll == 3) ~ 0,\n (dice_roll == 1 | dice_roll == 4) ~ -50,\n )\n ) %>% \n # The global average\n summarise(average = round(mean(result),2)) %>% \n pull(average)\n\n[1] 121.47\n"
},
{
"answer_id": 74591410,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "set.seed(990)\n\nrolls <- sample(6, 5649, TRUE)\n\nwin <- integer(5649)\nwin[rolls %in% c(1, 4)] <- -50\nwin[rolls == 5] <- 50\nwin[rolls == 6] <- 16*50\nmean(win)\n#> [1] 121.4728\n prizes <- c(-50, 0, 0, -50, 50, 16*50)\n\nwin <- prizes[rolls]\nmean(win)\n#> [1] 121.4728\n round(mean(win), 2)\n#> 121.47\n"
},
{
"answer_id": 74591961,
"author": "Baraliuh",
"author_id": 11157753,
"author_profile": "https://Stackoverflow.com/users/11157753",
"pm_score": 1,
"selected": false,
"text": "-50/3 + 0/3 + 50/6 + 16*50/6\n[1] 125\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12245970/"
] |
74,590,080
|
<p>The firebase Sveltekit client app and server api use a google cloud run hosting container. This works fine when I use the cloud run url: <code>https://app...-4ysldefc4nq-uc.a.run.app/</code></p>
<p>But when I use firebase rewriting the client works fine using: <code>https://vc-ticker.web.app/...</code> but receives 502 and 504 responses from the <a href="https://kit.svelte.dev/docs/routing#server" rel="nofollow noreferrer">API service</a>. The cloud run log does not show any errors, receives the client fetch POST request and returns a Readablestream response.<br />
<strong>But this API service response stream never arrives when using rewrites.</strong></p>
<p>firebase.json</p>
<pre class="lang-json prettyprint-override"><code>{
"hosting": {
"public": "public", !! NOT used, cloud run hosts the app
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"run": {
"serviceId": "vc-ticker-app",
"region": "us-central1"
}
}
]
}
}
</code></pre>
<p>+page.svelte client API request:</p>
<pre class="lang-js prettyprint-override"><code>const logging = true;
const controller = new AbortController();
let reader = null;
const signal = controller.signal;
async function streamer(params) {
console.log("stream with logging:", logging, JSON.stringify(params));
try {
const response = await fetch("api/my-ticker", {
method: "POST",
body: JSON.stringify(params),
headers: {
"content-type": "application/json",
},
signal: signal,
});
const stream = response.body.pipeThrough(new TextDecoderStream("utf-8"));
reader = stream.getReader();
while (true) {
const { value, done } = await reader.read();
if (done || response.status !== 200) {
console.log("done response", response.status, done, value);
await reader.cancel(`reader done or invalid response: ${response.status}`);
reader = null;
break;
}
// response ok: parse multi json chunks => array => set store
const quotes = {};
JSON.parse(`[${value.replaceAll("}{", "},{")}]`).forEach((each, idx) => {
quotes[each.id] = [each.price, each.changePercent];
console.log(`quote-${idx}:`, quotes[each.id]);
});
positions.set(quotes);
}
} catch (err) {
console.log("streamer exception", err.name, err);
if (reader) {
await reader.cancel(`client exception: ${err.name}`);
reader = null;
}
}
}
$: if ($portfolio?.coins) {
const params = {
logging,
symbols: Object.values($portfolio.symbols),
};
streamer(params);
}
onDestroy(async () => {
if (reader) await reader.cancel("client destroyed");
controller.abort();
console.log("finished");
});
</code></pre>
<p>I use the Sveltekit adapter-node to build the app.</p>
|
[
{
"answer_id": 74590073,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 1,
"selected": false,
"text": "#Simulation of the dice roll\nset.seed(990);dice_roll <- sample(1:6,5649,replace = TRUE)\n\nlibrary(dplyr)\n\ndf <- tibble(dice_roll = dice_roll)\n\ndf %>% \n mutate(\n #Setting each dice roll to their respective result\n result = case_when(\n dice_roll == 6 ~ (16*50),\n dice_roll == 5 ~ 50,\n (dice_roll == 2 | dice_roll == 3) ~ 0,\n (dice_roll == 1 | dice_roll == 4) ~ -50,\n )\n ) %>% \n # The global average\n summarise(average = round(mean(result),2)) %>% \n pull(average)\n\n[1] 121.47\n"
},
{
"answer_id": 74591410,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "set.seed(990)\n\nrolls <- sample(6, 5649, TRUE)\n\nwin <- integer(5649)\nwin[rolls %in% c(1, 4)] <- -50\nwin[rolls == 5] <- 50\nwin[rolls == 6] <- 16*50\nmean(win)\n#> [1] 121.4728\n prizes <- c(-50, 0, 0, -50, 50, 16*50)\n\nwin <- prizes[rolls]\nmean(win)\n#> [1] 121.4728\n round(mean(win), 2)\n#> 121.47\n"
},
{
"answer_id": 74591961,
"author": "Baraliuh",
"author_id": 11157753,
"author_profile": "https://Stackoverflow.com/users/11157753",
"pm_score": 1,
"selected": false,
"text": "-50/3 + 0/3 + 50/6 + 16*50/6\n[1] 125\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/675006/"
] |
74,590,090
|
<p>i have such data
(the data is given as an example, so both groups have the same values)</p>
<pre class="lang-r prettyprint-override"><code> dat=structure(list(sku = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), period = c("30.09.2021",
"14.03.2019", "01.04.2022", "18.02.2022", "07.07.2021", "09.10.2020",
"17.01.2019", "10.11.2020", "14.07.2021", "10.09.2019", "31.01.2019",
"01.07.2021", "30.09.2021", "14.03.2019", "01.04.2022", "18.02.2022",
"07.07.2021", "09.10.2020", "17.01.2019", "10.11.2020", "14.07.2021",
"10.09.2019", "31.01.2019", "01.07.2021"), hist.prices = c(3728.16,
34899.84, 6126, 1789.44, 18098.4, 15633.6, 26174.88, 2401.56,
12668.88, 239500.8, 26174.88, 5429.52, 3728.16, 34899.84, 6126,
1789.44, 18098.4, 15633.6, 26174.88, 2401.56, 12668.88, 239500.8,
26174.88, 5429.52), hist.revenue = c(178951.68, 20102307.84,
367560, 42946.56, 4343616, 3752064, 11307548.16, 86456.16, 2128371.84,
965667225.6, 11307548.16, 390925.44, 178951.68, 20102307.84,
367560, 42946.56, 4343616, 3752064, 11307548.16, 86456.16, 2128371.84,
965667225.6, 11307548.16, 390925.44), hist.demand = c(254L, 276L,
272L, 250L, 299L, 297L, 291L, 260L, 270L, 275L, 295L, 279L, 254L,
276L, 272L, 250L, 299L, 297L, 291L, 260L, 270L, 275L, 295L, 279L
), hist.cost = c(12572.6698, 10498.9848, 14949.392, 13160.5,
14557.9512, 12443.3199, 10692.3294, 10893.116, 13145.976, 10222.6025,
10982.9975, 13584.1752, 12572.6698, 10498.9848, 14949.392, 13160.5,
14557.9512, 12443.3199, 10692.3294, 10893.116, 13145.976, 10222.6025,
10982.9975, 13584.1752), unity.cost = c(49.4987, 38.0398, 54.961,
52.642, 48.6888, 41.8967, 36.7434, 41.8966, 48.6888, 37.1731,
37.2305, 48.6888, 49.4987, 38.0398, 54.961, 52.642, 48.6888,
41.8967, 36.7434, 41.8966, 48.6888, 37.1731, 37.2305, 48.6888
), hist.profit = c(1336L, 1592L, 1128L, 1882L, 1387L, 1818L,
1357L, 1087L, 1253L, 1009L, 1092L, 1804L, 1336L, 1592L, 1128L,
1882L, 1387L, 1818L, 1357L, 1087L, 1253L, 1009L, 1092L, 1804L
)), class = "data.frame", row.names = c(NA, -24L))
</code></pre>
<p>I need to do a regression analysis and calculate the coefficients for each sku(group variable) separately. The demand function is the same for all sku. Then i perform regression:</p>
<pre class="lang-r prettyprint-override"><code> # example of linear demand curve (first equation)
demand = function(p, alpha = -40, beta = 500, sd = 10) {
error = rnorm(length(p), sd = sd)
q = p*alpha + beta + error
return(q)
}
</code></pre>
<p>in this example, this is only for one sku, but it is necessary for all that are available.</p>
<pre class="lang-r prettyprint-override"><code> library(stargazer)
model.fit = lm(hist.demand ~ hist.prices)
stargazer(model.fit, type = 'html', header = FALSE) # output
# estimated parameters
beta = model.fit$coefficients[1]
alpha = model.fit$coefficients[2]
p.revenue = -beta/(2*alpha) # estimated price for revenue
p.profit = (alpha*unity.cost - beta)/(2*alpha) # estimated price for profit
true.revenue = function(p) p*(-40*p + 500) # Revenue with true parameters (chunck demand)
true.profit = function(p) (p - unity.cost)*(-40*p + 500) # price with true parameters
# estimated curves
estimated.revenue = function(p) p*(model.fit$coefficients[2]*p + model.fit$coefficients[1])
estimated.profit = function(p) (p - unity.cost)*(model.fit$coefficients[2]*p + model.fit$coefficients[1])
opt.revenue = true.revenue(p.revenue) # Revenue with estimated optimum price
opt.profit = true.profit(p.profit) # Profit with estimated optimum price
</code></pre>
<p>how to execute this code for all sku separately, so that the desired output is something like this</p>
<pre class="lang-r prettyprint-override"><code> sku opt.profit opt.revenue
1 722.0413 1562.041
2 722.0413 1562.041
</code></pre>
<p>thanks for any of your valuable help</p>
|
[
{
"answer_id": 74590073,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 1,
"selected": false,
"text": "#Simulation of the dice roll\nset.seed(990);dice_roll <- sample(1:6,5649,replace = TRUE)\n\nlibrary(dplyr)\n\ndf <- tibble(dice_roll = dice_roll)\n\ndf %>% \n mutate(\n #Setting each dice roll to their respective result\n result = case_when(\n dice_roll == 6 ~ (16*50),\n dice_roll == 5 ~ 50,\n (dice_roll == 2 | dice_roll == 3) ~ 0,\n (dice_roll == 1 | dice_roll == 4) ~ -50,\n )\n ) %>% \n # The global average\n summarise(average = round(mean(result),2)) %>% \n pull(average)\n\n[1] 121.47\n"
},
{
"answer_id": 74591410,
"author": "Rui Barradas",
"author_id": 8245406,
"author_profile": "https://Stackoverflow.com/users/8245406",
"pm_score": 2,
"selected": false,
"text": "set.seed(990)\n\nrolls <- sample(6, 5649, TRUE)\n\nwin <- integer(5649)\nwin[rolls %in% c(1, 4)] <- -50\nwin[rolls == 5] <- 50\nwin[rolls == 6] <- 16*50\nmean(win)\n#> [1] 121.4728\n prizes <- c(-50, 0, 0, -50, 50, 16*50)\n\nwin <- prizes[rolls]\nmean(win)\n#> [1] 121.4728\n round(mean(win), 2)\n#> 121.47\n"
},
{
"answer_id": 74591961,
"author": "Baraliuh",
"author_id": 11157753,
"author_profile": "https://Stackoverflow.com/users/11157753",
"pm_score": 1,
"selected": false,
"text": "-50/3 + 0/3 + 50/6 + 16*50/6\n[1] 125\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529548/"
] |
74,590,091
|
<pre><code>const combinations = [{rolledOnes: true, scoredOnes:false},
{rolledTwos: true, scoredTwos:false}];
</code></pre>
<p>I am fairly new to Javascript. So, my actual array is larger than this. I want to set rolledOnes and rolledTwos to false, without affecting scoredOnes and scoredTwos. Some sort of loop or nice method would be nice?</p>
<p>I tried an array of arrays and can get it to function the way i want, but it is not clear compared to objects.</p>
|
[
{
"answer_id": 74590112,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "Array.forEach() Object.keys() let combinations = [{rolledOnes: true, scoredOnes:false}, \n {rolledTwos: true, scoredTwos:false}];\ncombinations.forEach(e => {\n let k = Object.keys(e)[0]\n e[k] = false\n})\n \nconsole.log(combinations)"
},
{
"answer_id": 74590219,
"author": "Krelq",
"author_id": 15000290,
"author_profile": "https://Stackoverflow.com/users/15000290",
"pm_score": 0,
"selected": false,
"text": "forEach() keys() const combinations = [\n { rolledOnes: true, scoredOnes: false },\n { rolledTwos: true, scoredTwos: false }\n];\n\ncombinations.forEach(combination => {\n let property = Object.keys(combination)[0];\n combination[property] = false;\n return combination;\n})\n"
},
{
"answer_id": 74590275,
"author": "jsejcksn",
"author_id": 438273,
"author_profile": "https://Stackoverflow.com/users/438273",
"pm_score": 1,
"selected": true,
"text": "const combinations = [\n {rolledOnes: true, scoredOnes: false},\n {rolledTwos: true, scoredTwos: false},\n];\n\nconst falseKeys = ['rolledOnes', 'rolledTwos'];\n\nfor (const obj of combinations) {\n for (const key of falseKeys) {\n if (key in obj) obj[key] = false;\n }\n}\n\nconsole.log(combinations); // [ { rolledOnes: false, scoredOnes: false }, { rolledTwos: false, scoredTwos: false } ]"
},
{
"answer_id": 74590300,
"author": "Salwa A. Soliman",
"author_id": 18270700,
"author_profile": "https://Stackoverflow.com/users/18270700",
"pm_score": 0,
"selected": false,
"text": "const combinations = [{\n rolledOnes: true,\n scoredOnes: false\n },\n {\n rolledTwos: true,\n scoredTwos: false\n },\n {\n rolledThrees: true,\n scoredThrees: false\n },\n];\n\ncombinations.forEach(comb => {\n Object.keys(comb).map(key => {\n if (key.startsWith('rolled')) {\n comb[key] = false;\n }\n })\n\n})\n\nconsole.log(combinations);"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614322/"
] |
74,590,120
|
<p>I'm trying to create a betting API, and I've now discovered a way to minimize the code rework with Mapper, but I'm not understanding the problem I'm having in the code.</p>
<p>ERROR:</p>
<pre><code>***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in api.loteria.loteriaapi.services.Mysql.BetServiceMysql required a bean of type 'api.loteria.loteriaapi.dtos.mappers.BetMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'api.loteria.loteriaapi.dtos.mappers.BetMapper' in your configuration.
</code></pre>
<p>BetMapper.Java</p>
<pre class="lang-java prettyprint-override"><code>@Mapper(componentModel = "spring")
public interface BetMapper {
@Mapping(target = "bet.id", source = "betId")
Bet betResquetToEntity(BetRequest betRequest);
@Mapping(source = "bet.id", target = "betId")
BetResponse entityToBetResponse(Bet bet);
}
</code></pre>
<p>BetServiceMysql.java</p>
<pre class="lang-java prettyprint-override"><code>@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class BetServiceMysql implements BetService {
private BetRepository betRepository;
private BetMapper betMapper;
@Override
public List<BetResponse> list() {
List<Bet> bets = betRepository.findAll();
return bets.stream().map(bet -> betMapper.entityToBetResponse(bet)).collect(Collectors.toList());
}
@Override
public BetResponse save(BetRequest betRequest) {
Bet bet = betMapper.betResquetToEntity(betRequest);
try {
betRepository.save(bet);
}catch(RuntimeException e){
throw new DataIntegrityViolationException(e.getMessage());
}
return betMapper.entityToBetResponse(bet);
}
@Override
public BetResponse update(Long id, BetRequest betRequest) {
Bet bet = verifyIfExist(id);
updateData(bet, betRequest);
betRepository.save(bet);
return betMapper.entityToBetResponse(bet);
}
@Override
public BetResponse delete(Long id) {
Bet bet = verifyIfExist(id);
betRepository.delete(bet);
return betMapper.entityToBetResponse(bet);
}
@Override
public BetResponse getBetById(Long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<BetResponse> getBets() {
// TODO Auto-generated method stub
return null;
}
protected Bet verifyIfExist(Long id){
return betRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(String.format("ID: %s || Não foi encontrado nenhuma entidade para o id fornecido", id)));
}
protected void updateData(Bet bet, BetRequest betRequest){
bet.setMaxNumbersByUsers(betRequest.getMaxNumbersByUsers());
}
}
</code></pre>
<p>BetService.java</p>
<pre class="lang-java prettyprint-override"><code>public interface BetService {
List<BetResponse> list();
BetResponse save(BetRequest betRequest);
BetResponse update(Long id, BetRequest betRequest);
BetResponse delete(Long id);
BetResponse getBetById(Long id);
List<BetResponse> getBets();
}
</code></pre>
<p>I tried removing <code>@Autowired</code> from Mapper, the code runs, but when a new bet is inserted there is another error from Mapper being <code>null</code>.</p>
|
[
{
"answer_id": 74592828,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 2,
"selected": true,
"text": "bet betResquetToEntity @Mapping(target = \"bet.id\", source = \"betId\") @Mapping(target = \"id\", source = \"betRequest.betId\") mapstruct-processor maven-compiler-plugin plugin"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12406838/"
] |
74,590,199
|
<p>I am using a Triggered Trapezoid block within Modelica Logical Blocks.
I am using it on a variable in my model, to eliminate the peaks that occur to this variable, because this variable is triggered by a boolean named ON, and when this boolean is equal to 1 the first seconds the variable records Peaks as it figures in the figure.</p>
<p><img src="https://i.stack.imgur.com/XmEY9.png" alt="1" /></p>
<p>When I use the Triggered Trapezoid it gives me the wrong value for my variable.
here is an extract from my model where I used the Triggered trapzoid:</p>
<pre><code> model prog
Real y;
Boolean u;
protected
discrete Real endValue "Value of y at time of recent edge";
discrete Real rate "Current rising/falling rate";
discrete Modelica.SIunits.Time T "Predicted time of output reaching endValue";
equation
amplitude = Var;
u = ON;
y = if time < T then endValue - (T - time) * rate else endValue;
when {initial(), u, not u} then
endValue = if u then offset + amplitude else offset;
rate = if u and rising > 0 then amplitude / rising else if not u and falling > 0 then -amplitude / falling else 0;
T = if u and not rising > 0 or not u and not falling > 0 or not abs(amplitude) > 0 or initial() then time else time + (endValue - pre(y)) / rate;
end when;
end prog;
</code></pre>
|
[
{
"answer_id": 74622957,
"author": "Akhil Nandan",
"author_id": 16020568,
"author_profile": "https://Stackoverflow.com/users/16020568",
"pm_score": 1,
"selected": false,
"text": "model Test\n Modelica.Blocks.Nonlinear.SlewRateLimiter slewRateLimiter(Td = 0.5) annotation(\n Placement(visible = true, transformation(origin = {-4, 30}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));\n Modelica.Blocks.Sources.BooleanPulse booleanPulse(period = 10) annotation(\n Placement(visible = true, transformation(origin = {-82, 30}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));\n Modelica.Blocks.Math.BooleanToReal booleanToReal annotation(\n Placement(visible = true, transformation(origin = {-44, 30}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));\nequation\n connect(booleanToReal.u, booleanPulse.y) annotation(\n Line(points = {{-56, 30}, {-70, 30}}, color = {255, 0, 255}));\n connect(booleanToReal.y, slewRateLimiter.u) annotation(\n Line(points = {{-32, 30}, {-16, 30}}, color = {0, 0, 127}));\n annotation(\n uses(Modelica(version = \"4.0.0\")));\nend Test;\n Modelica.Blocks.Sources.BooleanPulse"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11214365/"
] |
74,590,220
|
<p>I am trying to calculate the Net Income based on a given Gross Income Value. The rules are this :</p>
<ol>
<li>If grossValue is lower or equal to 1000, no tax is applied</li>
<li>10% Tax is applied to the exess amout</li>
</ol>
<p>Example : Given a gross value of 3400, we apply 10% tax to the exess so 10% out of 2400 is 240 => Then we just return 2160 + 1000</p>
<p>The problem is this line : <code>double netSalary = exessAmout - (10 / 100 * exessAmout);</code> For some reason the value doesnt change</p>
<pre><code>
public double CalculateNetSalary(double grossSalary)
{
// Taxes dont apply, return grossValue
if(grossSalary <= 1000)
{
return grossSalary;
}
double exessAmout = grossSalary - 1000;
// Apply normal tax
double netSalary = exessAmout - (10 / 100 * exessAmout);
return netSalary + 1000;
}
</code></pre>
<p>I expected given a value of 3400 to receive 3160</p>
<p>Why :</p>
<ul>
<li><p>exessAmout = 3400 - 1000 => 2400</p>
</li>
<li><p>netSalary = 2400 - (10% of 2400)</p>
</li>
<li><p>return netSalary + 1000</p>
</li>
</ul>
<p>using a calculator to solve this I get the right answer, but running the code the value always stays the same</p>
|
[
{
"answer_id": 74590262,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 2,
"selected": true,
"text": "int int int 10 / 100 double 10.0 / 100.0"
},
{
"answer_id": 74590333,
"author": "Sachith Wickramaarachchi",
"author_id": 3703534,
"author_profile": "https://Stackoverflow.com/users/3703534",
"pm_score": 0,
"selected": false,
"text": "10 / 100 // Apply Social Tax\nif (grossSalary > 3000)\n{\n netSalary -= (10.0 / 100.0 * netSalary);\n Console.WriteLine(netSalary);\n}\n netSalary"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614392/"
] |
74,590,255
|
<p>EDIT: Command <code>lista = [int(i) for i in input("Podaj Liczby: ").split(",")]</code> still doesn't sort.
When I try to enter numbers, it does not sort them for me
Even if i use "," still doesn't sort.
Here's code:</p>
<pre><code>lista = [int(i) for i in input("Podaj Liczby: ").split(",")]
def sortowaniebabelkowe():
n = len(lista)
zmiana = False
while n > 1:
for l in range(0, n-1):
if lista[l]>lista[l+1]:
lista[l],lista[l+1]==lista[l+1],lista[l]
zamien = True
n -= 1
print(lista)
if zmiana == False: break
sortowaniebabelkowe()
</code></pre>
|
[
{
"answer_id": 74590262,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 2,
"selected": true,
"text": "int int int 10 / 100 double 10.0 / 100.0"
},
{
"answer_id": 74590333,
"author": "Sachith Wickramaarachchi",
"author_id": 3703534,
"author_profile": "https://Stackoverflow.com/users/3703534",
"pm_score": 0,
"selected": false,
"text": "10 / 100 // Apply Social Tax\nif (grossSalary > 3000)\n{\n netSalary -= (10.0 / 100.0 * netSalary);\n Console.WriteLine(netSalary);\n}\n netSalary"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18717371/"
] |
74,590,260
|
<p>I have a dataset like following :</p>
<pre><code> link from_node to_node
1 412300044 100923 100185
2 412300047 100190 100198
3 412300057 100197 100198
4 412300058 100198 100199
5 412300076 100190 100199
... ... ... ...
</code></pre>
<p>I will use 'link' variable as an edge, and 'from_node' and 'to_node' as vertices. No weighted value currently.
I decided this, but have no idea what can I do further.
I searched internet about making edge betweenness figure but there were very few...I would be very helpful if you help me.</p>
|
[
{
"answer_id": 74590506,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 2,
"selected": false,
"text": "set.seed(1234)\n\ndf <- data.frame(link = sample(30, 10) + 412300040,\n from_node = sample(10, 10, T) + 100184,\n to_node = sample(10, 10, T) + 100184)\n\ndf\n#> link from_node to_node\n#> 1 412300068 100188 100189\n#> 2 412300056 100186 100192\n#> 3 412300066 100191 100188\n#> 4 412300062 100190 100192\n#> 5 412300045 100194 100187\n#> 6 412300052 100190 100188\n#> 7 412300055 100188 100194\n#> 8 412300049 100192 100189\n#> 9 412300070 100188 100186\n#> 10 412300046 100188 100192\n library(igraph)\n\nig <- graph_from_data_frame(df[c(3, 2, 1)])\nedge_betweenness(ig)\n#> [1] 2.5 2.0 6.0 1.5 4.0 4.5 6.0 2.5 3.0 2.0\n plot(ig, edge.width = edge_betweenness(ig), edge.label = df$link)\n library(tidygraph)\nlibrary(ggraph)\n\nas_tbl_graph(df[c(3, 2, 1)]) %>%\n activate(edges) %>%\n mutate(betweenness = centrality_edge_betweenness()) %>%\n ggraph() +\n geom_edge_diagonal(aes(edge_width = betweenness, label = link), \n angle_calc = \"along\", alpha = 0.5, vjust = -1,\n color = \"lightblue\") +\n geom_node_circle(aes(r = 0.2), fill = \"lightblue\", color = \"navy\") +\n geom_node_text(aes(label = name)) +\n coord_equal() +\n theme_graph()\n"
},
{
"answer_id": 74590600,
"author": "clp",
"author_id": 3604103,
"author_profile": "https://Stackoverflow.com/users/3604103",
"pm_score": 1,
"selected": false,
"text": "require(igraph)\ndf <- data.frame(\n edge = c(412300044, 412300047, 412300057, 412300058, 412300076),\n from_node = c(100923, 100190 , 100197 , 100198 , 100190),\n to_node = c(100185, 100198 , 100198 , 100199 , 100199)\n)\n\n# reorder, rename columns\ndf2 <- data.frame(to_node=df[,2], from_node=df[,3], label=df[,1])\n\n g <- graph_from_data_frame(df2, directed=TRUE)\nplot(g)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19743121/"
] |
74,590,267
|
<p>Hey currently I'm trying to program a quadratic programming algorithm with Python.</p>
<p><strong>My goal:</strong>
I want to program a function where the given parameters are one vector c, and a matrix G. They are connected through the function Phi = 0.5 *(x^T * G * x) + c^T *x (x^T in this context means vector x transposed). The goal of the function is to find a vector x so that the function Phi is minimized. In order to do that, I need to perform some algebraic calculations (multiplication, transposing and deriving the gradient of the function Phi).</p>
<p>My problem: But I'm struggling with creating a vector which indicates the dimensions of the problem. I am trying to create a vector x = [x_1, x_2, x_3, ..., x_N] which containts N elements. N varies. The elements 'x_N' should be variables (since I want to compute them later on, but I need them 'beforehand' to calculate e.g. the gradient).</p>
<p>My code so far: ('NoE'... is equal to N+1, thats why Im substracting 1 in my while statement)</p>
<pre><code> #filling the x-vector according to the dimension of the given problem
temp_2 = 0
while temp_2 <= (NoE-1):
x[temp_2]= 'x_' + temp_2
print(x)
</code></pre>
<p><strong>The previous answer just helped me partially:</strong>
The only problem I am encountering now, is that those are all strings and I cant perform any kind of mathematical operation with them (like multiplying them with a matrix). Do you know any fix how I can still do it with strings?</p>
<p>Or do you think I could use the sympy library (which would help me with future calculations)?</p>
<p><strong>Im open to every suggestion of solving this, since I dont have a lot of experience in programming generally</strong></p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74603632,
"author": "MannyC",
"author_id": 12008379,
"author_profile": "https://Stackoverflow.com/users/12008379",
"pm_score": 2,
"selected": true,
"text": "import sympy\nfrom sympy import symbols\n\n### First we initialize some Symbol objects\n\n# this does essentially what you were doing in the question, but in one line\n# see list comprehensions* \nsymbol_names = [f'x_{i}' for i in range(NoE-1)]\n\n# then we make them become 'Symbols'\nx = symbols(symbol_names)\n\n### Next we can do stuff with them:\n\n# multiply the first two\nexpr = x[0] * x[1]\nprint(expr) # x_0*x_1\n\n# evaluate the expression `expr` with x_0=3, x_1=2\nres = expr.evalf(subs={'x_0':3, 'x_1':2})\nprint(res) # 6.00000\n sympy list x x = []\nfor i in range(NoE-1):\n x.append(\n float(input(f'insert value x_{i}'))\n )\n x x[0] x[1]"
},
{
"answer_id": 74604022,
"author": "S. A.",
"author_id": 9245600,
"author_profile": "https://Stackoverflow.com/users/9245600",
"pm_score": 0,
"selected": false,
"text": "class Vector(int):\n def __new__(cls, name: str, number: int):\n created_object = super().__new__(cls, number)\n return created_object\n\n def __init__(self, name, number):\n self.name = name \n self.number = number\n # print(f'{name} is called with number={number}')\n \n # if ypu want to get the same type after math operation\n # you'll have to implement all magics like so\n ## otherwise comment it and you'll get the result of int type on multiplying\n def __mul__(self, other):\n return Vector(\"\".join([self.name, \"*\",other.name]), self.number * other.number)\n \n def __repr__(self):\n return f'{self.name}: {self.number}'\n\nv1 = Vector(\"v1\", 3)\nv2 = Vector(\"v2\", 4)\n\nprint(v1)\nprint(v2)\n\nprint(v1*v2)\n\n# int result as it is not implemented in class\nv3 = v1 + v2\nprint(v3)\n\n\nv = [ Vector(f\"v_{x}\", x+1) for x in range(0,2)]\n\nprint(v)\n\nt = [mv * v1 for mv in v]\n\nprint(t)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614501/"
] |
74,590,306
|
<p>I need to check if the String word can be added on the array length, without lose any character out of bounds.
Right now when I add some String words it goes out of the length and I don't know how to fix that.</p>
<p>Right now I fill an 2D array with (*) and I want to add words like <em>"schedule"</em> but when I add the word in rows and columns like 2, 5 the word goes out of bounds and print:</p>
<hr />
<p>*<strong>relax</strong>
****<em>sche</em>
<em>ridiculo</em>
******<em>ta</em></p>
<p>And the rest characters of the word disappear.</p>
<pre class="lang-java prettyprint-override"><code>public class WordSearch {
private static int rows = 5;
private static int columns = 10;
char board[][] = new char [rows][columns];
public WordSearch(){
for(int row=0; row<rows; row++){
for(int col=0; col<columns; col++){
board[row][col] = '*';
}
}
}
public void addWord(String word, int position, int x , int y) {
switch(position){
case 0:
for(int i=0; i<word.length(); i++){
if(y + 1 >= board[x].length){
continue;
} else if(board[x][y] == '*'){
board[x][y++] = word.charAt(i);
} else {
board[x][y++] = word.charAt(i);
}
}
break;
case 1:
for(int i=0; i<word.length(); i++){
if(x + 1 >= board[y].length){
continue;
} else if(board[x][y] == '*'){
board[x++][y] = word.charAt(i);
} else {
board[x++][y] = word.charAt(i);
}
}
break;
default:
System.out.println("Give 0 to add word horizontally, or 1 vertically");
}
}
}
</code></pre>
|
[
{
"answer_id": 74603632,
"author": "MannyC",
"author_id": 12008379,
"author_profile": "https://Stackoverflow.com/users/12008379",
"pm_score": 2,
"selected": true,
"text": "import sympy\nfrom sympy import symbols\n\n### First we initialize some Symbol objects\n\n# this does essentially what you were doing in the question, but in one line\n# see list comprehensions* \nsymbol_names = [f'x_{i}' for i in range(NoE-1)]\n\n# then we make them become 'Symbols'\nx = symbols(symbol_names)\n\n### Next we can do stuff with them:\n\n# multiply the first two\nexpr = x[0] * x[1]\nprint(expr) # x_0*x_1\n\n# evaluate the expression `expr` with x_0=3, x_1=2\nres = expr.evalf(subs={'x_0':3, 'x_1':2})\nprint(res) # 6.00000\n sympy list x x = []\nfor i in range(NoE-1):\n x.append(\n float(input(f'insert value x_{i}'))\n )\n x x[0] x[1]"
},
{
"answer_id": 74604022,
"author": "S. A.",
"author_id": 9245600,
"author_profile": "https://Stackoverflow.com/users/9245600",
"pm_score": 0,
"selected": false,
"text": "class Vector(int):\n def __new__(cls, name: str, number: int):\n created_object = super().__new__(cls, number)\n return created_object\n\n def __init__(self, name, number):\n self.name = name \n self.number = number\n # print(f'{name} is called with number={number}')\n \n # if ypu want to get the same type after math operation\n # you'll have to implement all magics like so\n ## otherwise comment it and you'll get the result of int type on multiplying\n def __mul__(self, other):\n return Vector(\"\".join([self.name, \"*\",other.name]), self.number * other.number)\n \n def __repr__(self):\n return f'{self.name}: {self.number}'\n\nv1 = Vector(\"v1\", 3)\nv2 = Vector(\"v2\", 4)\n\nprint(v1)\nprint(v2)\n\nprint(v1*v2)\n\n# int result as it is not implemented in class\nv3 = v1 + v2\nprint(v3)\n\n\nv = [ Vector(f\"v_{x}\", x+1) for x in range(0,2)]\n\nprint(v)\n\nt = [mv * v1 for mv in v]\n\nprint(t)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13084927/"
] |
74,590,309
|
<p>I learnt about Inheritance in C++. Then to check that I've understood the concept correctly, I have written the below given program that is rejected by clang but accepted by gcc and msvc. <a href="https://godbolt.org/z/hs18KxGM3" rel="nofollow noreferrer">Live Demo</a></p>
<pre><code>#include <array>
#include <iostream>
class Base
{
private:
int data;
public:
Base(int pdata):data(pdata) {}
Base(const Base&){std::cout <<" Copy base";}
};
class Derived : public Base
{
};
int main()
{
Derived d(1); //rejected by clang but accepted by gcc and msvc
}
</code></pre>
<p>I am using C++20 and want to know <strong>which compiler is correct here in C++20</strong>. I've also noticed that with C++17 all compilers reject this but from c++20 onwards, gcc and msvc start compiling the program. So it seems there was some change in the c++20 standard. But I don't know what that change is(assuming there is any such change) and whether or not the program is well formed in c++20.</p>
<p>The clang c++20 error says:</p>
<pre><code><source>:19:12: error: no matching conversion for functional-style cast from 'int' to 'Derived'
Base d(Derived(1));
</code></pre>
|
[
{
"answer_id": 74590383,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "T object ( arg ); (1) \n Derived Derived d(1); Derived Derived d(1); 1"
},
{
"answer_id": 74593515,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "class Derived : public Base\n{ \npublic:\n Derived(int arg) : Base(arg) { } \n};\n #include <array> g++ -std=c++98 <iostream.h> d(1) Derived d = { 1 }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20562802/"
] |
74,590,373
|
<p>I have controller for changing website language, saving cookie and returning url.</p>
<p>`</p>
<pre><code>using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
namespace Website.Controllers;
public class CultureController : Controller
{
[HttpPost]
public IActionResult SetCulture(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(365) }
);
return LocalRedirect(returnUrl);
}
}
</code></pre>
<p>`</p>
<p>And in View I need create html list for better user experience but I don't understand how to change from 'form' to 'list' or how to submit changes and return url
`</p>
<pre><code>@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options
@inject IOptions<RequestLocalizationOptions> LocalizationOptions
@{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocalizationOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.EnglishName })
.ToList();
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";
}
<!-- FROM FORM -->
<div class="language">
<form asp-controller="Culture" asp-action="SetCulture" asp-route-returnUrl="@returnUrl" class="form-horizontal nav-link text-dark">
<select name="culture"
onchange="this.form.submit();"
asp-for="@requestCulture.RequestCulture.UICulture.Name"
asp-items="cultureItems">
</select>
</form>
</div>
<!-- TO LIST -->
<div class="language-toggle">
<a href="#" class="toggle-btn"><i class="fas fa-language"></i></a>
<ul class="language-menu">
@foreach (var item in LocalizationOptions.Value.SupportedUICultures)
{
<li><a href="#?HOW">@item.Name.ToUpper()</a></li>
}
</ul>
</div>
</code></pre>
<p>`</p>
<p>I tried with anchor tag helper but without success</p>
<p>output
<a href="https://i.stack.imgur.com/LJGNp.png" rel="nofollow noreferrer">Output</a></p>
<p>I can get current url in view and append ?culture=en and that changes language and stays on current page but does not save cookie so every time user goes to different page website is in native language not in user selected language.</p>
|
[
{
"answer_id": 74590383,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "T object ( arg ); (1) \n Derived Derived d(1); Derived Derived d(1); 1"
},
{
"answer_id": 74593515,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "class Derived : public Base\n{ \npublic:\n Derived(int arg) : Base(arg) { } \n};\n #include <array> g++ -std=c++98 <iostream.h> d(1) Derived d = { 1 }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614393/"
] |
74,590,381
|
<p>I'm still learning Flutter, so I need some help.</p>
<p>The following page layout is in portrait mode:</p>
<p><a href="https://i.stack.imgur.com/SWyGD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SWyGD.png" alt="enter image description here" /></a></p>
<p>I want it to change to the following layout in landscape mode:</p>
<p><a href="https://i.stack.imgur.com/Qf9Os.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qf9Os.png" alt="enter image description here" /></a></p>
<p>How can I do it without repeating the widgets?</p>
<p>I thought to do it through a list or a map but I didn't know how to apply that to my code</p>
|
[
{
"answer_id": 74590383,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "T object ( arg ); (1) \n Derived Derived d(1); Derived Derived d(1); 1"
},
{
"answer_id": 74593515,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "class Derived : public Base\n{ \npublic:\n Derived(int arg) : Base(arg) { } \n};\n #include <array> g++ -std=c++98 <iostream.h> d(1) Derived d = { 1 }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11878615/"
] |
74,590,430
|
<p>How to transform data frame, given dataset assume this is a large dataset</p>
<pre class="lang-r prettyprint-override"><code>datestamp <- c("2020-04-26 17:45:14","2020-04-17 17:08:54","2020-04-01 17:54:13","2020-04-07 12:50:19","2020-04-18 10:22:59")
member_casual <- c("member","member","member","member","casual")
df <- data.frame(datestamp, member_casual)
</code></pre>
<p>Desire dataset</p>
<pre class="lang-r prettyprint-override"><code>member_casual <- c("member", "casual")
monday <- c(0,0)
tuesday <- c(1,0)
wednesday <- c(1,0)
thursday <- c(0,0)
friday <- c(1,0)
saturday <- c(0,1)
sunday <- c(1,0)
df <- data.frame(member_casual,monday,tuesday,wednesday,thursday,friday,saturday,sunday)
</code></pre>
<p>I want to know which days is the most counted</p>
|
[
{
"answer_id": 74590383,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "T object ( arg ); (1) \n Derived Derived d(1); Derived Derived d(1); 1"
},
{
"answer_id": 74593515,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "class Derived : public Base\n{ \npublic:\n Derived(int arg) : Base(arg) { } \n};\n #include <array> g++ -std=c++98 <iostream.h> d(1) Derived d = { 1 }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614727/"
] |
74,590,439
|
<p>Want to read numbers from a file and add them to <code>List<Integer></code>. But the problem happens to be that two-digit numbers are also split into 2 separate numbers when reading the file.</p>
<p>Text file example:</p>
<pre><code>2, 7
1, 0, 24, 2
3, 0, 6, 3
4, 0, 2, 1
</code></pre>
<p>My code:</p>
<pre class="lang-java prettyprint-override"><code>import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
public void readTestCase(String files) throws IOException {
File file = new File(files);
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("");
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < valueStr.length; i++) {
if(isNumeric(valueStr[i])) {
arr.add(Integer.parseInt(valueStr[i]));
}
}
System.out.println(arr);
}
public static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
}
</code></pre>
<p>This code output:
<code>[2, 7, 1, 0, 2, 4, 2, 3, 0, 6, 3, 4, 0, 2, 1]</code></p>
<p>The correct output should be:
<code>[2, 7, 1, 0, 24, 2, 3, 0, 6, 3, 4, 0, 2, 1]</code></p>
<p>Now, this code works but the problem is in the text file number "24" is also split into "2" and "4".
So my file should contain only 14 numbers in the list. Now it has 15 numbers.
I also try to modify split like this <code>.split(",");</code>, <code>.split(", ");</code> and the output is always wrong.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74590383,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "T object ( arg ); (1) \n Derived Derived d(1); Derived Derived d(1); 1"
},
{
"answer_id": 74593515,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "class Derived : public Base\n{ \npublic:\n Derived(int arg) : Base(arg) { } \n};\n #include <array> g++ -std=c++98 <iostream.h> d(1) Derived d = { 1 }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16661931/"
] |
74,590,474
|
<p>i m having two objects previous and new one, i trying to compare and get difference for those objects, send to as patch payload from patch api,</p>
<p>compare each properties in object if any of the property has any difference i want all those difference in new object as payload</p>
<p>How can i achieve this please help me find the solution?
Is there any <code>lodash</code> method for this solution?</p>
<pre><code>let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln@gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/eNe9X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eNe9X.png" alt="previous object" /></a></p>
<pre><code>let obj2 = {
Name: "Ajmal",
age: 25,
email: "something@gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/k71B8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k71B8.png" alt="new object" /></a></p>
<p><a href="https://i.stack.imgur.com/bucSp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bucSp.png" alt="object 1 and object 2" /></a></p>
<p>result payload i m expecting would look like</p>
<pre><code>let payload = {
email: "something@gmail.com",
contact: [12345678, 11111111],
address: {
pin: 111
}
}
</code></pre>
|
[
{
"answer_id": 74590383,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 2,
"selected": false,
"text": "T object ( arg ); (1) \n Derived Derived d(1); Derived Derived d(1); 1"
},
{
"answer_id": 74593515,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "class Derived : public Base\n{ \npublic:\n Derived(int arg) : Base(arg) { } \n};\n #include <array> g++ -std=c++98 <iostream.h> d(1) Derived d = { 1 }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15366349/"
] |
74,590,496
|
<p>I want to check (using VBA) if a folder path exists.</p>
<pre><code>saveLocation = "G:\documents\"
</code></pre>
<p>If the folder exists then I want to save to this location.</p>
<p>I am currently saving as a PDF using the following code.</p>
<pre><code> saveLocation = saveLocation & "myfile.pdf"
</code></pre>
<p>However the issue I have, is if the folder location doesnt exist I want to prompt or ask the user to select a folder.</p>
<p>How would I go about doing this?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74590594,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 1,
"selected": false,
"text": "Sub testFolderIfExists()\n Dim saveLocation As String\n \n saveLocation = \"G:\\documents\\\"\n\n If Dir(saveLocation, vbDirectory) <> \"\" Then Debug.Print saveLocation & \" folder exists\"\n 'or\n Dim fso As Object: Set fso = CreateObject(\"Scripting.FileSystemObject\")\n \n If fso.FolderExists(saveLocation) Then Debug.Print saveLocation & \" folder exists\"\nEnd Sub\n"
},
{
"answer_id": 74590830,
"author": "Siddharth Rout",
"author_id": 1140579,
"author_profile": "https://Stackoverflow.com/users/1140579",
"pm_score": 3,
"selected": true,
"text": "Option Explicit\n\nSub Sample()\n Dim Ret\n Dim saveLocation As String\n \n saveLocation = \"G:\\documents\\\"\n \n If Dir(saveLocation, vbDirectory) <> \"\" Then\n '~~> Folder Exists\n '~~> Save at saveLocation\n Else\n '~~> Folder doesn't exist\n '~~> Prompt user to select folder\n Ret = BrowseForFolder\n \n If Ret <> False Then\n saveLocation = Ret\n \n If Right(saveLocation, 1) <> \"\\\" Then saveLocation = saveLocation & \"\\\"\n \n '~~> save at saveLocation\n End If\n End If\nEnd Sub\n\nFunction BrowseForFolder(Optional OpenAt As Variant) As Variant\n Dim ShellApp As Object\n \n Set ShellApp = CreateObject(\"Shell.Application\"). _\n BrowseForFolder(0, \"Please choose a folder\", 0, OpenAt)\n \n On Error Resume Next\n BrowseForFolder = ShellApp.self.Path\n On Error GoTo 0\n \n Set ShellApp = Nothing\n \n Select Case Mid(BrowseForFolder, 2, 1)\n Case Is = \":\"\n If Left(BrowseForFolder, 1) = \":\" Then GoTo Whoa\n Case Is = \"\\\"\n If Not Left(BrowseForFolder, 1) = \"\\\" Then GoTo Whoa\n Case Else\n GoTo Whoa\n End Select\n \n Exit Function\nWhoa:\n BrowseForFolder = False\nEnd Function\n"
},
{
"answer_id": 74591780,
"author": "יעקב טורק",
"author_id": 17839542,
"author_profile": "https://Stackoverflow.com/users/17839542",
"pm_score": 0,
"selected": false,
"text": "saveLocation = \"G:\\documents\"\nIf Len(Dir(saveLocation, vbDirectory)) = 0 Then\n MkDir saveLocation\nEnd If\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2013720/"
] |
74,590,516
|
<p>I am copying a model object to another, but I want that it doesn’t copy the relations</p>
<p>For example, assume you have a model like this:</p>
<pre><code>class Dish(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=500)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
def __str__(self):
return self.name
</code></pre>
<p>Then I do:</p>
<pre><code> my_dish = Dish.objects.get(pk=dish.id)
serializer = Dish_Serializer(my_dish)
my_new_object = serializer.data
</code></pre>
<p>I want <code>my_new_object</code> to include only those attributes that are not relations, in this case, name and description.</p>
<p>How do I do that without accessing name and description directly?</p>
|
[
{
"answer_id": 74590594,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 1,
"selected": false,
"text": "Sub testFolderIfExists()\n Dim saveLocation As String\n \n saveLocation = \"G:\\documents\\\"\n\n If Dir(saveLocation, vbDirectory) <> \"\" Then Debug.Print saveLocation & \" folder exists\"\n 'or\n Dim fso As Object: Set fso = CreateObject(\"Scripting.FileSystemObject\")\n \n If fso.FolderExists(saveLocation) Then Debug.Print saveLocation & \" folder exists\"\nEnd Sub\n"
},
{
"answer_id": 74590830,
"author": "Siddharth Rout",
"author_id": 1140579,
"author_profile": "https://Stackoverflow.com/users/1140579",
"pm_score": 3,
"selected": true,
"text": "Option Explicit\n\nSub Sample()\n Dim Ret\n Dim saveLocation As String\n \n saveLocation = \"G:\\documents\\\"\n \n If Dir(saveLocation, vbDirectory) <> \"\" Then\n '~~> Folder Exists\n '~~> Save at saveLocation\n Else\n '~~> Folder doesn't exist\n '~~> Prompt user to select folder\n Ret = BrowseForFolder\n \n If Ret <> False Then\n saveLocation = Ret\n \n If Right(saveLocation, 1) <> \"\\\" Then saveLocation = saveLocation & \"\\\"\n \n '~~> save at saveLocation\n End If\n End If\nEnd Sub\n\nFunction BrowseForFolder(Optional OpenAt As Variant) As Variant\n Dim ShellApp As Object\n \n Set ShellApp = CreateObject(\"Shell.Application\"). _\n BrowseForFolder(0, \"Please choose a folder\", 0, OpenAt)\n \n On Error Resume Next\n BrowseForFolder = ShellApp.self.Path\n On Error GoTo 0\n \n Set ShellApp = Nothing\n \n Select Case Mid(BrowseForFolder, 2, 1)\n Case Is = \":\"\n If Left(BrowseForFolder, 1) = \":\" Then GoTo Whoa\n Case Is = \"\\\"\n If Not Left(BrowseForFolder, 1) = \"\\\" Then GoTo Whoa\n Case Else\n GoTo Whoa\n End Select\n \n Exit Function\nWhoa:\n BrowseForFolder = False\nEnd Function\n"
},
{
"answer_id": 74591780,
"author": "יעקב טורק",
"author_id": 17839542,
"author_profile": "https://Stackoverflow.com/users/17839542",
"pm_score": 0,
"selected": false,
"text": "saveLocation = \"G:\\documents\"\nIf Len(Dir(saveLocation, vbDirectory)) = 0 Then\n MkDir saveLocation\nEnd If\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1353914/"
] |
74,590,579
|
<p>I want to create 12 instantiations of a class and pass a random value as its parameter. The random values should only range from 1 to 6 BUT I need each value from the range to be distributed twice among the 12 instances of the class.</p>
<p>The constructor of the Class is as follows:</p>
<pre><code>Die(int numSide){
this.numside = numSide;
}
</code></pre>
<p>Basically, I want to create 12 instances of dice with 2 of each side, sort of, as a result of a tossing.</p>
|
[
{
"answer_id": 74590594,
"author": "FaneDuru",
"author_id": 2233308,
"author_profile": "https://Stackoverflow.com/users/2233308",
"pm_score": 1,
"selected": false,
"text": "Sub testFolderIfExists()\n Dim saveLocation As String\n \n saveLocation = \"G:\\documents\\\"\n\n If Dir(saveLocation, vbDirectory) <> \"\" Then Debug.Print saveLocation & \" folder exists\"\n 'or\n Dim fso As Object: Set fso = CreateObject(\"Scripting.FileSystemObject\")\n \n If fso.FolderExists(saveLocation) Then Debug.Print saveLocation & \" folder exists\"\nEnd Sub\n"
},
{
"answer_id": 74590830,
"author": "Siddharth Rout",
"author_id": 1140579,
"author_profile": "https://Stackoverflow.com/users/1140579",
"pm_score": 3,
"selected": true,
"text": "Option Explicit\n\nSub Sample()\n Dim Ret\n Dim saveLocation As String\n \n saveLocation = \"G:\\documents\\\"\n \n If Dir(saveLocation, vbDirectory) <> \"\" Then\n '~~> Folder Exists\n '~~> Save at saveLocation\n Else\n '~~> Folder doesn't exist\n '~~> Prompt user to select folder\n Ret = BrowseForFolder\n \n If Ret <> False Then\n saveLocation = Ret\n \n If Right(saveLocation, 1) <> \"\\\" Then saveLocation = saveLocation & \"\\\"\n \n '~~> save at saveLocation\n End If\n End If\nEnd Sub\n\nFunction BrowseForFolder(Optional OpenAt As Variant) As Variant\n Dim ShellApp As Object\n \n Set ShellApp = CreateObject(\"Shell.Application\"). _\n BrowseForFolder(0, \"Please choose a folder\", 0, OpenAt)\n \n On Error Resume Next\n BrowseForFolder = ShellApp.self.Path\n On Error GoTo 0\n \n Set ShellApp = Nothing\n \n Select Case Mid(BrowseForFolder, 2, 1)\n Case Is = \":\"\n If Left(BrowseForFolder, 1) = \":\" Then GoTo Whoa\n Case Is = \"\\\"\n If Not Left(BrowseForFolder, 1) = \"\\\" Then GoTo Whoa\n Case Else\n GoTo Whoa\n End Select\n \n Exit Function\nWhoa:\n BrowseForFolder = False\nEnd Function\n"
},
{
"answer_id": 74591780,
"author": "יעקב טורק",
"author_id": 17839542,
"author_profile": "https://Stackoverflow.com/users/17839542",
"pm_score": 0,
"selected": false,
"text": "saveLocation = \"G:\\documents\"\nIf Len(Dir(saveLocation, vbDirectory)) = 0 Then\n MkDir saveLocation\nEnd If\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17505578/"
] |
74,590,616
|
<p>I need to create a memory game in Python. I need to print a 5x4 (4 rows, 5 elements in a line) field in the console and the fields should have names like a1, b1, c1... in the next row a2, b2, c2 etc. We've already got a list of symbols, which should be used in the game (list1). One of the instructions we have is to create nested lists here, which gives me a hard time. If you see below, I created a nested list, which shuffles the cards and puts them in a list. When I print those, I get the 5x4 row as needed.
If an user writes a1 and b2 in the console, I have to print the exact symbols that are placed in that row.</p>
<p>However, I have no idea how I should proceed at this point. I had some thoughts, but they seem to be unprofessional...</p>
<p>My idea:</p>
<ul>
<li>Create new list with fields a1, b1, etc. and print those. If an user writes a1 and b1, I get the index in the list and find the symbol at the same index in my cards list.
--> Nested lists seem to be useless with that idea + creating a new list with fields is probably not wanted in that task</li>
</ul>
<pre><code>cards = ["✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀",
"✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀"]
</code></pre>
<p>My solution so far:</p>
<pre><code>def create_grid(cards):
random.shuffle(cards)
cards2 = [cards[i:i+5] for i in range(0, len(cards), 5)]
return cards2
</code></pre>
|
[
{
"answer_id": 74590688,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 2,
"selected": false,
"text": "row col row col col, row = interpret_reference(reference)\ncard = grid[row][col]\n reference grid[row] grid[row][col] a b c d e 1 2 3 4 \"1\" interpret_reference() col_letters = {\"a\": 0, \"b\": 1, \"c\": 2, \"d\": 3, \"e\": 4}\nrow_numbers = {\"1\", 0, \"2\": 1, \"3\": 2, \"4\": 3}\n\ndef interpret_reference(userinput):\n col, row = userinput\n return col_letters[col], row_numbers[row]\n col, row grid[col][row] interpret_reference() ValueError KeyError ord() \"a\" col = ord(col_reference) - ord(\"a\")\n col 0 col_reference \"a\" 1 \"b\" input() ord(\"1\") int() \"1\" 1 row = int(row_reference) - 1\n ord() int() z9 col = 25 row = 8 IndexError \"99\" col = -40 \"9\" \"a\" create_grid cards random.shuffle(cards) shuffled = random.sample(cards, len(cards)) cards"
},
{
"answer_id": 74590805,
"author": "arsho",
"author_id": 3129414,
"author_profile": "https://Stackoverflow.com/users/3129414",
"pm_score": 1,
"selected": false,
"text": "a1 d5 ord import random\n\ncards = [\"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\",\n \"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\"]\n\n\ndef create_grid(cards):\n shuffled_cards = cards.copy()\n random.shuffle(shuffled_cards)\n cards2 = [shuffled_cards[i:i + 5] for i in\n range(0, len(shuffled_cards), 5)]\n return cards2\n\n\ngrid = create_grid(cards)\nprint(\"Grid:\")\nfor line in grid:\n print(\" \".join(line))\n\nprint(\"\")\n\nwhile True:\n field = input(\"Enter a name of the field (0 to exit): \")\n if field[0] == '0':\n break\n field = field.lower()\n row = ord(field[0]) - ord('a')\n column = int(field[1]) - 1\n if row >= len(grid) or column >= len(grid[0]):\n print(\"The field is out of grid size. Try again.\\n\")\n continue\n print(f\"{field}: {grid[row][column]}\\n\")\n Grid:\n✂ ✂ ❄ ☀ ✉\n✿ ✖ ✈ ★ ♫\n✖ ✉ ♥ ✿ ❄\n♫ ★ ✈ ♥ ☀\n\nEnter a name of the field (0 to exit): a2\na2: ✂\n\nEnter a name of the field (0 to exit): b1\nb1: ✿\n\nEnter a name of the field (0 to exit): d4\nd4: ♥\n\nEnter a name of the field (0 to exit): e2\nThe field is out of grid size. Try again.\n\nEnter a name of the field (0 to exit): 0\n cards shuffled_cards = cards.copy() a1 d4 0"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20614841/"
] |
74,590,624
|
<p>i have a text file i want to add its data to priority queue and then print out 5 items with max value
each line first has a name then a date then a value i want to print 5 max values with name and date</p>
<pre><code>Queue<String> queue = new PriorityQueue<String>();
String file = "file";
String line;
int order = 1;
try{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
queue.offer(line);
}
br.close();
} catch (IOException e){
System.out.println("File not found");
}
while (!queue.isEmpty()){
System.out.println(order + ".Number: " + queue.poll());
order++;
}
</code></pre>
<p>data.txt :</p>
<pre><code>tloxJcdiMqMWyDW 1976-11-24 3747
KWuHczAFXRGCeTZ 2015-12-5 1740
SyAckDyYyZhrsEK 1920-8-3 3164
pjKEnTTfcdoJwMy 2016-12-28 1941
ZsvJcYbmOFmdXfG 1923-10-10 8314
qkqDyFhObQVpByH 1934-7-21 4907
IRUMpmTSmJDVIJU 2012-12-26 376
nOCCDAmTilqnukW 1968-5-3 5811
uecbYlaCeaTSAsr 1937-4-1 9305
AMdPXptNGayPPAM 1949-2-25 1130
afTQNxogdxpQRpF 1912-11-18 5637
hBUJpjBJgyShNqk 2011-12-9 4075
dMGDWfIrPctuwBs 2005-3-15 8567
UBELfqonZOmmEGf 1954-7-29 7875
EuMbAKoKwYYERxy 1902-3-4 8291
OXvvwLXJjsXrfVI 1927-4-29 4693
amHPTQXCqHkYtXW 1991-8-24 8778
gfAcsQpChfukGlK 1971-7-14 4204
WHguJUYeLBYoton 1987-11-24 9664
ZvMoXwJqLhBlWiG 2006-6-7 7893
</code></pre>
<p>i have tried some other ways to save data to PQ and still didnt get any result</p>
|
[
{
"answer_id": 74590688,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 2,
"selected": false,
"text": "row col row col col, row = interpret_reference(reference)\ncard = grid[row][col]\n reference grid[row] grid[row][col] a b c d e 1 2 3 4 \"1\" interpret_reference() col_letters = {\"a\": 0, \"b\": 1, \"c\": 2, \"d\": 3, \"e\": 4}\nrow_numbers = {\"1\", 0, \"2\": 1, \"3\": 2, \"4\": 3}\n\ndef interpret_reference(userinput):\n col, row = userinput\n return col_letters[col], row_numbers[row]\n col, row grid[col][row] interpret_reference() ValueError KeyError ord() \"a\" col = ord(col_reference) - ord(\"a\")\n col 0 col_reference \"a\" 1 \"b\" input() ord(\"1\") int() \"1\" 1 row = int(row_reference) - 1\n ord() int() z9 col = 25 row = 8 IndexError \"99\" col = -40 \"9\" \"a\" create_grid cards random.shuffle(cards) shuffled = random.sample(cards, len(cards)) cards"
},
{
"answer_id": 74590805,
"author": "arsho",
"author_id": 3129414,
"author_profile": "https://Stackoverflow.com/users/3129414",
"pm_score": 1,
"selected": false,
"text": "a1 d5 ord import random\n\ncards = [\"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\",\n \"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\"]\n\n\ndef create_grid(cards):\n shuffled_cards = cards.copy()\n random.shuffle(shuffled_cards)\n cards2 = [shuffled_cards[i:i + 5] for i in\n range(0, len(shuffled_cards), 5)]\n return cards2\n\n\ngrid = create_grid(cards)\nprint(\"Grid:\")\nfor line in grid:\n print(\" \".join(line))\n\nprint(\"\")\n\nwhile True:\n field = input(\"Enter a name of the field (0 to exit): \")\n if field[0] == '0':\n break\n field = field.lower()\n row = ord(field[0]) - ord('a')\n column = int(field[1]) - 1\n if row >= len(grid) or column >= len(grid[0]):\n print(\"The field is out of grid size. Try again.\\n\")\n continue\n print(f\"{field}: {grid[row][column]}\\n\")\n Grid:\n✂ ✂ ❄ ☀ ✉\n✿ ✖ ✈ ★ ♫\n✖ ✉ ♥ ✿ ❄\n♫ ★ ✈ ♥ ☀\n\nEnter a name of the field (0 to exit): a2\na2: ✂\n\nEnter a name of the field (0 to exit): b1\nb1: ✿\n\nEnter a name of the field (0 to exit): d4\nd4: ♥\n\nEnter a name of the field (0 to exit): e2\nThe field is out of grid size. Try again.\n\nEnter a name of the field (0 to exit): 0\n cards shuffled_cards = cards.copy() a1 d4 0"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9207957/"
] |
74,590,632
|
<p><strong>Context</strong></p>
<p>I have a generic SwiftUI view called <code>ComponentRow</code> and would like to use it in different places inside my app. However, my model only returns the <code>Component</code> as <code>(any Component)?</code>, which is why I used a <code>Switch</code> to bridge between <code>any</code> and the generic <code>ComponentRow</code> view <em>(see variant A in code example)</em>.</p>
<p>I came with an idea to simplify the code <em>(see variant B in code example)</em>, however, I get the following Compiler Error:</p>
<blockquote>
<p>Adjacent operators are in non-associative precedence group 'ComparisonPrecedence'</p>
</blockquote>
<hr />
<p><strong>Code</strong></p>
<pre class="lang-swift prettyprint-override"><code>protocol Component {
static var name: String { get }
}
struct ContentView: View {
var body: some View {
// Variant A: Current Solution
switch component {
case let componentA as ComponentA: ComponentRow<ComponentA>()
case let componentB as ComponentB: ComponentRow<ComponentB>()
case let componentC as ComponentC: ComponentRow<ComponentC>()
default: EmptyView()
}
// Variant B: My Idea, does not work
if let safeComponent = component {
EventRow<type(of: safeComponent)>(for: profile, with: event)
}
}
var component: (any Component)? {
// Some Logic...
}
}
struct ComponentRow<C: Component>: View {
var body: some View {
Text(C.name)
}
}
</code></pre>
<hr />
<p><strong>Question</strong></p>
<ul>
<li>Is there a way to avoid switching through all possible objects conforming to <code>Component</code> to initiate the appropriate <code>ComponentRow</code>?</li>
</ul>
|
[
{
"answer_id": 74590688,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 2,
"selected": false,
"text": "row col row col col, row = interpret_reference(reference)\ncard = grid[row][col]\n reference grid[row] grid[row][col] a b c d e 1 2 3 4 \"1\" interpret_reference() col_letters = {\"a\": 0, \"b\": 1, \"c\": 2, \"d\": 3, \"e\": 4}\nrow_numbers = {\"1\", 0, \"2\": 1, \"3\": 2, \"4\": 3}\n\ndef interpret_reference(userinput):\n col, row = userinput\n return col_letters[col], row_numbers[row]\n col, row grid[col][row] interpret_reference() ValueError KeyError ord() \"a\" col = ord(col_reference) - ord(\"a\")\n col 0 col_reference \"a\" 1 \"b\" input() ord(\"1\") int() \"1\" 1 row = int(row_reference) - 1\n ord() int() z9 col = 25 row = 8 IndexError \"99\" col = -40 \"9\" \"a\" create_grid cards random.shuffle(cards) shuffled = random.sample(cards, len(cards)) cards"
},
{
"answer_id": 74590805,
"author": "arsho",
"author_id": 3129414,
"author_profile": "https://Stackoverflow.com/users/3129414",
"pm_score": 1,
"selected": false,
"text": "a1 d5 ord import random\n\ncards = [\"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\",\n \"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\"]\n\n\ndef create_grid(cards):\n shuffled_cards = cards.copy()\n random.shuffle(shuffled_cards)\n cards2 = [shuffled_cards[i:i + 5] for i in\n range(0, len(shuffled_cards), 5)]\n return cards2\n\n\ngrid = create_grid(cards)\nprint(\"Grid:\")\nfor line in grid:\n print(\" \".join(line))\n\nprint(\"\")\n\nwhile True:\n field = input(\"Enter a name of the field (0 to exit): \")\n if field[0] == '0':\n break\n field = field.lower()\n row = ord(field[0]) - ord('a')\n column = int(field[1]) - 1\n if row >= len(grid) or column >= len(grid[0]):\n print(\"The field is out of grid size. Try again.\\n\")\n continue\n print(f\"{field}: {grid[row][column]}\\n\")\n Grid:\n✂ ✂ ❄ ☀ ✉\n✿ ✖ ✈ ★ ♫\n✖ ✉ ♥ ✿ ❄\n♫ ★ ✈ ♥ ☀\n\nEnter a name of the field (0 to exit): a2\na2: ✂\n\nEnter a name of the field (0 to exit): b1\nb1: ✿\n\nEnter a name of the field (0 to exit): d4\nd4: ♥\n\nEnter a name of the field (0 to exit): e2\nThe field is out of grid size. Try again.\n\nEnter a name of the field (0 to exit): 0\n cards shuffled_cards = cards.copy() a1 d4 0"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13345744/"
] |
74,590,670
|
<p>From my understanding of OOP in Python, if there is no attribute named <code>xyz</code> on an object <code>a</code>, then invoking <code>a.xyz</code> raises "AttributeError."
But in beautifulsoup, if we call any arbitrary attribute on an object of type <code>Tag</code>, we always get some output.
For instance,</p>
<pre><code>>>> from bs4 import BeautifulSoup
>>> import requests
>>> html = requests.get("https://wwww.bing.com").text
>>> tag = BeautifulSoup(html, 'html5lib')
>>> print(tag.title) # makes sense
<title>Bing</title>
>>> print(tag.no_such_attrib) # should throw AttributeError
None
</code></pre>
<p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find" rel="nofollow noreferrer">Here</a>, it is
implied that <code>tag_obj.anything.something</code> gets executed as <code>tag_obj.find("anything").find("something")</code>. But I just can't imagine which type of construct transforms the former form into the later one.</p>
|
[
{
"answer_id": 74590826,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 2,
"selected": false,
"text": "class Tag(PageElement):\n ...\n\n def __getattr__(self, tag):\n \"\"\"Calling tag.subtag is the same as calling tag.find(name=\"subtag\")\"\"\"\n if not tag.startswith(\"__\") and not tag == \"contents\":\n return self.find(tag)\n raise AttributeError(\"'%s' object has no attribute '%s'\" % (self.__class__, tag))\n None AttributeError class Foo:\n def __getattr__(self, item: str):\n return self.__dict__.get(item)\n\n\nif __name__ == \"__main__\":\n foo = Foo()\n foo.bar = 1\n print(foo.bar) # 1\n print(foo.baz) # None\n dict.get None"
},
{
"answer_id": 74591877,
"author": "JL Peyret",
"author_id": 1394353,
"author_profile": "https://Stackoverflow.com/users/1394353",
"pm_score": 0,
"selected": false,
"text": "getattr(obj,\"no_such_attrib\",\"xxx\") __getattr__ find_something() \nX = getattr(obj,\"no_such_attrib\",None) or find_something()\n\n __getattr__ getattr __getattr__ \ndef __getattr__(self, attrname):\n \" sloppy __getattr__ love recursion error :-( \"\n\n if attrname = \"missing_attribute\"):\n return self.another_missing_attribute\n elif attrname = \"another_missing_attribute\"):\n return self.missing_attribute\n else:\n raise AttributeError(attrname)\n\n dict __missing__"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17954536/"
] |
74,590,695
|
<p>I'm seeing this kind of assignment:</p>
<pre><code>info->table = &_ttable_full[0];
</code></pre>
<p>Why not directly use this:</p>
<pre><code>info->table = _ttable_full;
</code></pre>
<p>Is there any advantage? Or is it just the author's style?</p>
|
[
{
"answer_id": 74591164,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 2,
"selected": true,
"text": "A &A[0] A+j &A[j] A &A[0] sizeof A sizeof &A[0] &A &&A[0] &&"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74590695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5739532/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.