qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,415,983 | <p>I am creating a windows forms app (C#) and I want to make a little rpg style battle game where you can perform 1 action per turn: Attack, block, use item, or run. I am new to these kinds of apps however, so can someone explain how I can only let the user hit 1 of the 4 buttons per turn?</p>
<p>I attempted to use .Click, but didn't understand it well enough.</p>
| [
{
"answer_id": 74416091,
"author": "Slonsoid",
"author_id": 20474992,
"author_profile": "https://Stackoverflow.com/users/20474992",
"pm_score": 0,
"selected": false,
"text": "private void button2_Click(object sender, EventArgs e)\n{\n // action is being performed here\n // ...\n // then all buttons become inactive:\n button1.Enabled = false;\n button2.Enabled = false;\n button3.Enabled = false;\n button4.Enabled = false;\n\n // then you wait for another action where the button's accessibility becomes true\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74415983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18386975/"
] |
74,415,989 | <p>I use below code but when I login via Microsoft account I don't receive refresh_token. Someone can explain why?</p>
<pre><code>$login = 'https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxxxxxxx/oauth2/v2.0/authorize?'.http_build_query([
'client_id' => $id,
'scope' => 'https://outlook.office.com/IMAP.AccessAsUser.All',
'redirect_uri' => $redirect,
'response_type' => 'code',
]);
</code></pre>
| [
{
"answer_id": 74418038,
"author": "Dmitry Streblechenko",
"author_id": 332059,
"author_profile": "https://Stackoverflow.com/users/332059",
"pm_score": 1,
"selected": false,
"text": "offline_access"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74415989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19818308/"
] |
74,416,000 | <p>My java version in terminal is different from the version in IntelliJ.</p>
<p>When I typed 'java -version' in the terminal, the version is 13.0.2, but when I set the SDK in the IntelliJ IDEA, the version is 11.0.4. I typed ' usr/libexec/java_home' in the terminal, but get the result 'zsh: no such file or directory: usr/libexec/java_home'. How should I fix it?</p>
| [
{
"answer_id": 74418038,
"author": "Dmitry Streblechenko",
"author_id": 332059,
"author_profile": "https://Stackoverflow.com/users/332059",
"pm_score": 1,
"selected": false,
"text": "offline_access"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488116/"
] |
74,416,060 | <p>I have this window function appled that looks like this:</p>
<pre><code>SUM(value) OVER (
PARTITION BY product, service, site
ORDER BY region, site, service, product, year, week ASC
ROWS BETWEEN 12 PRECEDING AND 0 PRECEDING
) AS value
</code></pre>
<p>The Query is working fine but I want to understand more of the window function, I have two questions:</p>
<ol>
<li>Does the partition columns order matters (PARTITION BY product, service, site)?</li>
<li>Do I need to specify columns from point 1 in the ORDER BY clause or can I omit them?</li>
</ol>
| [
{
"answer_id": 74416267,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 1,
"selected": false,
"text": "PARTITION BY product, service, site"
},
{
"answer_id": 74416467,
"author": "trillion",
"author_id": 12513693,
"author_profile": "https://Stackoverflow.com/users/12513693",
"pm_score": 0,
"selected": false,
"text": "PARTITION BY product, service, site)\nPARTITION BY service, site, product)\nPARTITION BY site, product, service) \n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9250452/"
] |
74,416,071 | <p>I've been trying to learn Laravel by myself and some features are bugging my mind. I'm trying to display a simple login form with just inputs and a button, so should I use function create and return a view or just declare Route::view on web.php to show a blade form?</p>
<p>OBS: I noticed that if the blade expect any data, I have to go through a controller, but since this won't use it that would not be a problem.
Keep in mind I'm just trying to learning the best and professional way possible.</p>
<p>This is how I would code on the AuthController:</p>
<pre class="lang-php prettyprint-override"><code>public function create() {
return view('auth.login');
}
</code></pre>
<h4>VS</h4>
<p>And this is how I would declared on web.php:</p>
<pre class="lang-php prettyprint-override"><code> Route::controller(AuthController::class)->group(function () {
Route::view('/login', 'auth.login')->name('login')->middleware('guest');
}
</code></pre>
| [
{
"answer_id": 74416267,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 1,
"selected": false,
"text": "PARTITION BY product, service, site"
},
{
"answer_id": 74416467,
"author": "trillion",
"author_id": 12513693,
"author_profile": "https://Stackoverflow.com/users/12513693",
"pm_score": 0,
"selected": false,
"text": "PARTITION BY product, service, site)\nPARTITION BY service, site, product)\nPARTITION BY site, product, service) \n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488128/"
] |
74,416,082 | <p>I want to create a text animation, in which the text is automatically and constantly moving from one side to the other side of the website. Like a text would do on a ticker display. Does anybody know about a simple css code I can use to animate the text in this way?</p>
<p>Thanks in advance!</p>
<p>I have tried it out with the tag, but it lags a lot.</p>
| [
{
"answer_id": 74416144,
"author": "Noel Maróti",
"author_id": 20150565,
"author_profile": "https://Stackoverflow.com/users/20150565",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link rel=\"stylesheet\" href=\"main.css\">\n <title>css animation</title>\n</head>\n<body>\n <h2 class=\"anim\">Hello world!</h2>\n</body>\n</html>\n"
},
{
"answer_id": 74418892,
"author": "Pradyot Sinha",
"author_id": 20026645,
"author_profile": "https://Stackoverflow.com/users/20026645",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n\n <link\n rel=\"apple-touch-icon\"\n type=\"image/png\"\n href=\"https://cpwebassets.codepen.io/assets/favicon/apple-touch-icon-5ae1a0698dcc2402e9712f7d01ed509a57814f994c660df9f7a952f3060705ee.png\"\n />\n <meta name=\"apple-mobile-web-app-title\" content=\"CodePen\" />\n\n <link\n rel=\"shortcut icon\"\n type=\"image/x-icon\"\n href=\"https://cpwebassets.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico\"\n />\n\n <link\n rel=\"mask-icon\"\n type=\"image/x-icon\"\n href=\"https://cpwebassets.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg\"\n color=\"#111\"\n />\n\n <title>CodePen - Wave Text</title>\n <link\n href=\"https://fonts.googleapis.com/css?family=Righteous&display=swap\"\n rel=\"stylesheet\"\n />\n\n <link\n rel=\"stylesheet\"\n href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css\"\n />\n\n <style>\n .container {\n max-width: 960px;\n }\n\n body {\n background-color: #fafafa;\n }\n\n .widthset {\n width: 16.5%;\n }\n\n .heading-style {\n font-family: \"Righteous\", cursive;\n font-size: 205px;\n font-weight: bolder;\n -webkit-text-stroke: 2px rgba(6, 188, 209, 0.2);\n background: #ffffff;\n mix-blend-mode: screen;\n padding-top: 190px;\n }\n\n @media (min-width: 1200px) .container,\n .container-lg,\n .container-md,\n .container-sm,\n .container-xl {\n max-width: 1140px;\n }\n\n @media (min-width: 992px) .container,\n .container-lg,\n .container-md,\n .container-sm {\n max-width: 960px;\n }\n\n @media (min-width: 768px) .container, .container-md, .container-sm {\n max-width: 720px;\n }\n\n @media (min-width: 576px) .container, .container-sm {\n max-width: 540px;\n }\n\n @media (min-width: 1200px) .container {\n max-width: 1140px;\n }\n\n @media (min-width: 992px) .container {\n max-width: 960px;\n }\n\n @media (min-width: 768px) .container {\n max-width: 720px;\n }\n\n @media (min-width: 576px) .container {\n max-width: 540px;\n }\n\n .shadow {\n box-shadow: 0px 18px 39.1px 6.9px rgba(224, 241, 255, 0.34) !important;\n }\n\n .card {\n border: 0;\n }\n\n .mt-15 {\n margin-top: 15%;\n }\n\n .progress-wrapper {\n height: 240px;\n overflow: hidden;\n }\n\n .wave {\n position: absolute;\n width: 100%;\n height: 100%;\n }\n\n .card-body {\n -ms-flex: 1 1 auto;\n flex: 1 1 auto;\n min-height: 1px;\n padding: 1.25rem;\n }\n\n .card-title {\n margin-bottom: 0.75rem;\n }\n\n .list-unstyled {\n padding-left: 0;\n list-style: none;\n }\n\n .card {\n position: relative;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-direction: column;\n flex-direction: column;\n min-width: 0;\n word-wrap: break-word;\n background-color: #fff;\n background-clip: border-box;\n border: 1px solid rgba(0, 0, 0, 0.125);\n border-radius: 0.25rem;\n margin-bottom: 20px;\n }\n\n .wave::before,\n .wave::after {\n content: \"\";\n position: absolute;\n width: 470px;\n height: 390px;\n bottom: 0;\n left: 55%;\n background-color: rgba(255, 255, 255, 0.18);\n border-radius: 70%;\n -webkit-transform: translateX(-50%) rotate(0);\n transform: translateX(-50%) rotate(0);\n -webkit-animation: rotate 6s linear infinite;\n animation: rotate 6s linear infinite;\n z-index: 10;\n }\n\n .wave::after {\n border-radius: 30%;\n background-color: rgba(255, 255, 255, 0.9);\n -webkit-transform: translateX(-50%) rotate(0);\n transform: translateX(-50%) rotate(0);\n -webkit-animation: rotate 10s linear -5s infinite;\n animation: rotate 10s linear -5s infinite;\n z-index: 20;\n }\n\n @keyframes rotate {\n 50% {\n transform: translateX(-50%) rotate(180deg);\n }\n\n 100% {\n transform: translateX(-50%) rotate(360deg);\n }\n }\n\n @media only screen and (max-width: 768px) {\n .heading-style {\n font-family: \"Righteous\", cursive;\n font-size: 156px;\n }\n\n .progress-wrapper {\n height: 209px;\n }\n }\n\n @media only screen and (max-width: 425px) {\n .heading-style {\n font-family: \"Righteous\", cursive;\n font-size: 65px;\n }\n\n .progress-wrapper {\n height: 148px;\n }\n\n .wave::before,\n .wave::after {\n width: 490px;\n height: 331px;\n }\n }\n </style>\n\n <script>\n window.console = window.console || function (t) {};\n </script>\n\n <script>\n if (document.location.search.match(/type=embed/gi)) {\n window.parent.postMessage(\"resize\", \"*\");\n }\n </script>\n </head>\n\n <body translate=\"no\">\n <a href=\"https://www.youtube.com/watch?v=szLmLFsisbY\" target=\"_blank\">\n <section class=\"section\">\n <div class=\"container\">\n <div class=\"row mt-15\">\n <div class=\"text-center widthset\">\n <div\n class=\"position-relative rounded-top progress-wrapper\"\n style=\"\n background-image: linear-gradient(\n to bottom,\n #f8e739,\n #f1d42d,\n #eac222,\n #e1b019,\n #d89e10\n );\n \"\n >\n <div class=\"wave\" style=\"bottom: 80%\">\n <h1 class=\"heading-style\">H</h1>\n </div>\n </div>\n </div>\n\n <div class=\"text-center widthset\">\n <div\n class=\"position-relative rounded-top progress-wrapper\"\n style=\"\n background-image: linear-gradient(\n to bottom,\n #d89e10,\n #e28f00,\n #ec7f00,\n #f66b00,\n #ff5200\n );\n \"\n >\n <div class=\"wave\" style=\"bottom: 80%\">\n <h1 class=\"heading-style\">E</h1>\n </div>\n </div>\n </div>\n\n <div class=\"text-center widthset\">\n <div\n class=\"position-relative rounded-top progress-wrapper\"\n style=\"\n background-image: linear-gradient(\n to bottom,\n #e2130b,\n #e1110c,\n #e00f0d,\n #df0c0d,\n #de090e\n );\n \"\n >\n <div class=\"wave\" style=\"bottom: 80%\">\n <h1 class=\"heading-style\">L</h1>\n </div>\n </div>\n </div>\n\n <div class=\"text-center widthset\">\n <div\n class=\"position-relative rounded-top progress-wrapper\"\n style=\"\n background-image: linear-gradient(\n to bottom,\n #ce0061,\n #d50079,\n #d60094,\n #d000b3,\n #c115d4\n );\n \"\n >\n <div class=\"wave\" style=\"bottom: 80%\">\n <h1 class=\"heading-style\">L</h1>\n </div>\n </div>\n </div>\n\n <div class=\"text-center widthset\">\n <div\n class=\"position-relative rounded-top progress-wrapper\"\n style=\"\n background-image: linear-gradient(\n to bottom,\n #6a0ddc,\n #5f0ddd,\n #530edd,\n #450fde,\n #3210de\n );\n \"\n >\n <div class=\"wave\" style=\"bottom: 80%\">\n <h1 class=\"heading-style\">O</h1>\n </div>\n </div>\n </div>\n </div>\n </div>\n </section>\n </a>\n </body>\n</html>\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17202472/"
] |
74,416,085 | <p>I can write something like the following and it works just as it should (it yields 10):</p>
<pre><code>import cats.effect.IO
import cats.effect.unsafe.implicits.global
val zz: fs2.Stream[IO, Int] = fs2.Stream.iterate[IO, Int](1)(_+1).map(_*2)
val qq: IO[Int] = zz.dropWhile(_ < 10).take(1).compile.toList.map(_.head)
qq.unsafeRunSync()
</code></pre>
<p>However, supposing that, instead of a predicate like <code>_ < 10</code> which returns <strong>Boolean</strong>, I have a predicate that returns an <strong>IO[Boolean]</strong>. Is there an alternative form of <em>dropWhile</em> which could handle this situation? I don't want to have to do something like <em>unsafeRunSync()</em> inside the predicate just so that it can yield a <strong>Boolean</strong>.</p>
<p>Clearly, this is a toy case, not the actual problem that I'm working on.</p>
| [
{
"answer_id": 74416253,
"author": "Luis Miguel Mejía Suárez",
"author_id": 4111404,
"author_profile": "https://Stackoverflow.com/users/4111404",
"pm_score": 3,
"selected": true,
"text": "def dropWhileEval[A](sa: Stream[IO, A])(p: A = IO[Boolean]): Stream[IO, A] =\n sa.evalMap(a => p(a).map(b => (b, a))).dropWhile(_._1).map(_._2)\n"
},
{
"answer_id": 74423051,
"author": "Phasmid",
"author_id": 221410,
"author_profile": "https://Stackoverflow.com/users/221410",
"pm_score": 0,
"selected": false,
"text": "import cats.effect.IO\nimport fs2.{Pure, Stream}\nimport cats.effect.unsafe.implicits.global\n\nval fLessThan10: Int => Boolean = _ < 10\nval fLessThan10_lifted: IO[Int] => IO[Boolean] = _ map fLessThan10\n\ndef dropWhileEval[A](sa: Stream[IO, IO[A]])(p: IO[A] => IO[Boolean]): fStream[IO, IO[A]] =\n sa.evalMap(a => p(a).map(b => (b, a))).dropWhile(_._1).map(_._2)\n\nval zz: Stream[IO, IO[Int]] = Stream.iterate[IO, Int](1)(_+1).map(x => IO(x*2))\nval yy: Stream[IO, IO[Int]] = dropWhileEval[Int](zz)(fLessThan10_lifted).take(1)\nval result: IO[List[Int]] = yy.evalMap(identity).compile.toList\n@result.unsafeRunSync()\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/221410/"
] |
74,416,097 | <p>I made a website for fun & testing but it doesn't look well on mobile as it works on desktop, especially images and specially positioned stuff got out of page. I tried</p>
<pre><code> <meta name="viewport" content="width=device-width, initial-scale=1">
</code></pre>
<p>but it still looks a way that nobody wants to see.</p>
<p>I'm a newbie codder please forgive my flaws :)</p>
<p>website: <a href="http://ersinski.epizy.com/" rel="nofollow noreferrer">http://ersinski.epizy.com/</a></p>
<pre><code> <meta name="viewport" content="width=device-width, initial-scale=1">
</code></pre>
| [
{
"answer_id": 74416167,
"author": "Noel Maróti",
"author_id": 20150565,
"author_profile": "https://Stackoverflow.com/users/20150565",
"pm_score": 1,
"selected": false,
"text": "img {\nmax-width: 100%\n}\n"
},
{
"answer_id": 74416302,
"author": "Skeirys",
"author_id": 10871372,
"author_profile": "https://Stackoverflow.com/users/10871372",
"pm_score": 0,
"selected": false,
"text": "left: 500px;"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488055/"
] |
74,416,105 | <p>I have all my <code><a></code> tags with <code>:focus</code>, <code>:hover</code> and <code>:active</code> styled like this:</p>
<pre><code>a:hover,
a:active,
a:focus {
background: rgba(225, 225, 225, 0.35) !important;
}
</code></pre>
<p>But the problem is, they don't work. I have to click like 2 times to see the <code>background color</code>
For example, on this menu</p>
<pre><code><div className="appBottomMenu">
<Link to="/" className="item">
<div className="col">
<i className="fi fi-rr-home"></i>
</div>
</Link>
<Link className="item" to="/area">
<div className="col">
<i className="fi fi-rr-marker"></i>
</div>
</Link>
<Link to="/community" className="item">
<div className="col">
<i className="fi fi-rr-browser"></i>
</div>
</Link>
<Link to="/shop" className="item">
<div className="col">
<i className="fi fi-rr-shopping-cart"></i>
</div>
</Link>
<Link to="/profile" className="item">
<div className="col">
<i className="fi fi-rr-user"></i>
</div>
</Link>
</div>
</code></pre>
<p>How can I make <code>:focus</code>, <code>:hover</code> and <code>:active</code> wor on te first click?</p>
| [
{
"answer_id": 74420755,
"author": "Maryam Sobhanian",
"author_id": 12153475,
"author_profile": "https://Stackoverflow.com/users/12153475",
"pm_score": 0,
"selected": false,
"text": "const {Link} = ReactRouterDOM\n\n\nconst Example = () => {\n return(\n <ReactRouterDOM.HashRouter>\n <Link to = \"/example\">Example</Link> \n </ReactRouterDOM.HashRouter>\n );\n}\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(<Example/>);"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19223350/"
] |
74,416,122 | <p>Suppose I have the following 2 matrices</p>
<pre><code>A <- matrix(nrow = 5, ncol = 3, byrow = TRUE, c(
5, 1, 2,
3, 1, 5,
5, 1, 3,
7, 2, 8,
2, 4, 2
))
B <- matrix(nrow = 5, ncol = 2, byrow = TRUE, c(
2, 1,
3, 5,
1, 4,
3, 3,
3, 4
))
</code></pre>
<p>and I want to create an array</p>
<pre><code>arr <- array(NA, dim = c(ncol(A), ncol(B), nrow(A)))
</code></pre>
<p>to store the cross product of row <code>i</code> of matrix <code>A</code> with the same row <code>i</code> of matrix <code>B</code>. For example, slice 2 of <code>arr</code> would be</p>
<pre><code>A[2, ] %*% t(B[2, ]
[,1] [,2]
[1,] 9 15
[2,] 3 5
[3,] 15 25
</code></pre>
<p>Using a for loop, I can do</p>
<pre><code>for (i in 1:nrow(A)) {
arr[, , i] <- A[i, ] %*% t(B[i, ])
}
</code></pre>
<p>Or using an <code>sapply</code> function</p>
<pre><code>temp <- sapply(1:nrow(A), function(i) A[i, ] %*% t(B[i, ]), simplify = FALSE)
arr <- array(unlist(temp), dim = c(ncol(A), ncol(B), nrow(A)))
</code></pre>
<p>I am wondering if there is more clever way using matrix products or built-in functions in this case. Thank you so much.</p>
| [
{
"answer_id": 74420755,
"author": "Maryam Sobhanian",
"author_id": 12153475,
"author_profile": "https://Stackoverflow.com/users/12153475",
"pm_score": 0,
"selected": false,
"text": "const {Link} = ReactRouterDOM\n\n\nconst Example = () => {\n return(\n <ReactRouterDOM.HashRouter>\n <Link to = \"/example\">Example</Link> \n </ReactRouterDOM.HashRouter>\n );\n}\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(<Example/>);"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488098/"
] |
74,416,136 | <p>Hello I am working with Snowflake and am creating a SQL stored procedure (CDS_EXTRACT). Within CDS_EXTRACT, I have to execute other stored procedures (CDS_EXTRACT_NEW_LOG_ENTRY). The arguments for CDS_EXTRACT_NEW_LOG_ENTRY need to come from variables I declared CDS_EXTRACT. Does anyone know how I can reference variables defined in CDS_EXTRACT to use as arguments as CDS_EXTRACT_NEW_LOG_ENTRY?</p>
<p>In particular, I would like to use the JOBNAME, SOURCEQUERY, CDCQUERY, CDCVALUE variables I declared in CDS_EXTRACT as arguments when I call CDS_NEW_LOG_ENTRY.</p>
<p>Running procedure B outside of procedure A works fine btw.</p>
<p>Hopefully that made sense please refer to my code for better understanding</p>
<pre><code>CREATE OR REPLACE PROCEDURE CDS_EXTRACT (CDSID number)
RETURNS varchar(1677216)
LANGUAGE SQL
AS
DECLARE
JOBNAME varchar(255);
SOURCEQUERY VARCHAR(16777216);
CDCQUERY VARCHAR(16777216);
CDCVALUE VARCHAR(100) DEFAULT NULL;
STAGE_DATABASE VARCHAR(100);
STAGE_SCHEMA VARCHAR(100);
STAGE_TABLE VARCHAR(100);
FILE_FORMAT VARCHAR(100);
BLOB_DIRECTORY VARCHAR(100);
BLOB_FILE VARCHAR(100);
SINGLE_FILE_FLAG BOOLEAN;
OVERWRITE_FILE BOOLEAN;
MAX_FILESIZE int DEFAULT 4900000000;
START_DATE TIMESTAMP_NTZ(9);
LAST_RUN_DATE TIMESTAMP_NTZ(9);
LAST_RUN_CYCLE VARCHAR(30);
LAST_RUN_COMPLETE BOOLEAN;
RUNNEXT BOOLEAN;
ERROR_FLAG BOOLEAN;
BEGIN
-- Gathering job info
JOBNAME := (SELECT JOBNAME FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
SOURCEQUERY := (SELECT SOURCEQUERY FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
CDCQUERY := (SELECT CDCQUERY FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
CDCVALUE := (SELECT CDCVALUE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
STAGE_DATABASE := (SELECT STAGE_DATABASE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
STAGE_SCHEMA := (SELECT STAGE_SCHEMA FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
STAGE_TABLE := (SELECT STAGE_TABLE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
FILE_FORMAT := (SELECT FILE_FORMAT FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
BLOB_DIRECTORY := (SELECT BLOB_DIRECTORY FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
BLOB_FILE := (SELECT BLOB_FILE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
SINGLE_FILE_FLAG := (SELECT SINGLE_FILE_FLAG FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
OVERWRITE_FILE := (SELECT OVERWRITE_FILE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
MAX_FILESIZE := (SELECT MAX_FILESIZE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
START_DATE := (SELECT START_DATE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
LAST_RUN_DATE := (SELECT LAST_RUN_DATE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
LAST_RUN_CYCLE := (SELECT LAST_RUN_CYCLE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
LAST_RUN_COMPLETE := (SELECT LAST_RUN_COMPLETE FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
RUNNEXT := (SELECT RUNNEXT FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
ERROR_FLAG := (SELECT ERROR_FLAG FROM CDS.TALEND_CDS_BLOBEXTRACT WHERE CDSID = :CDSID);
-- Update Start date, and last run date (need to add way to update run cycle as well)
CALL CDS_EXTRACT_UPDATE_RUNCYCLE_DATE(:CDSID);
-- Insert new log entry row
CALL CDS_EXTRACT_NEW_LOG_ENTRY(00000, :CDSID, JOBNAME, SOURCEQUERY, CDCQUERY, CDCVALUE);
RETURN 'Procedure completed!';
END
;
</code></pre>
<p>Running results in the following error: Error:'STATEMENT_ERROR' on line 47 at position 8 : SQL compilation error: error line 1 at position 60 (line 99)</p>
| [
{
"answer_id": 74420755,
"author": "Maryam Sobhanian",
"author_id": 12153475,
"author_profile": "https://Stackoverflow.com/users/12153475",
"pm_score": 0,
"selected": false,
"text": "const {Link} = ReactRouterDOM\n\n\nconst Example = () => {\n return(\n <ReactRouterDOM.HashRouter>\n <Link to = \"/example\">Example</Link> \n </ReactRouterDOM.HashRouter>\n );\n}\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(<Example/>);"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13711883/"
] |
74,416,142 | <p>I need to make a table with more tables, but i dont know how to put this tables inside
<a href="https://i.stack.imgur.com/tRGlb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tRGlb.png" alt="enter image description here" /></a>
It should look like this</p>
<p><strong>i need to do this without CSS</strong></p>
<p>I have tried something...well it turns out like this</p>
<p><a href="https://i.stack.imgur.com/OpctR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OpctR.png" alt="enter image description here" /></a></p>
<p>I don't understand how to make it</p>
| [
{
"answer_id": 74416216,
"author": "patrick",
"author_id": 73804,
"author_profile": "https://Stackoverflow.com/users/73804",
"pm_score": -1,
"selected": false,
"text": " <table>\n\n<tr>\n <td style=\"border:1px solid black;\">\n Spaltenweise\n </td>\n <td style=\"border:1px solid black;\">\n \n \n<table>\n<tr>\n<td style=\"border:1px solid black;\">\n A04\n </td>\n</tr>\n<tr>\n <td style=\"border:1px solid black;\">\n 100\n </td>\n <td style=\"border:1px solid black;\">\n 200\n </td>\n <td style=\"border:1px solid black;\">\n 300\n </td>\n</tr>\n<tr >\n<td colspan=3 style=\"border:1px solid black;\">\n spalte 1 2 3 4\n </td>\n</tr>\n</table>\n </td>\n</tr>\n\n\n</table>"
},
{
"answer_id": 74416696,
"author": "kountouris panagiotis",
"author_id": 20271835,
"author_profile": "https://Stackoverflow.com/users/20271835",
"pm_score": 2,
"selected": false,
"text": "HTML"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488230/"
] |
74,416,182 | <pre><code>library(data.table)
table1 <- data.table(id1 = c(1324, 2324, 29, 29, 1010, 1010),
type = c(1, 1, 2, 1, 1, 1),
class = c("A", "A", "B", "D", "D", "A"),
number = c(1, 98, 100, 100, 70, 70))
table2 <- data.table(id2 = c(1998, 1998, 2000, 2000, 2000, 2010, 2012, 2012),
type = c(1, 1, 3, 1, 1, 5, 1, 1),
class = c("D", "A", "D", "D", "A", "B", "A", "A"),
min_number = c(34, 0, 20, 45, 5, 23, 1, 1),
max_number = c(50, 100, 100, 100, 100, 9, 10, 100))
> table1
id1 type class number
1: 1324 1 A 1
2: 2324 1 A 98
3: 29 2 B 100
4: 29 1 D 100
5: 1010 1 D 70
6: 1010 1 A 70
> table2
id2 type class min_number max_number
1: 1998 1 D 34 50
2: 1998 1 A 0 100
3: 2000 3 D 20 100
4: 2000 1 D 45 100
5: 2000 1 A 5 100
6: 2010 5 B 23 9
7: 2012 1 A 1 10
8: 2012 1 A 1 100
</code></pre>
<p>I have two tables, and I would like to merge them based on <code>type</code>, <code>class</code>, and whether <code>number</code> lies between <code>min_number</code> and <code>max_number</code>. Then I would like to create a new variable <code>nMatch</code> that stores the number of unique <code>id2</code>s that match with each <code>id1</code>.</p>
<pre><code>setindexv(table2, c("type", "class"))
for (t1_row in seq_len(nrow(table1))) {
print(t1_row)
set(
table1, t1_row, "matches",
table2[table1[t1_row], on = c("type", "class", "max_number >= number", "min_number <= number"), .(list(id2))]
)
}
> table1[, .(nMatch = uniqueN(unlist(matches), na.rm = TRUE)), by = .(id1)]
id1 nMatch
1: 1324 2
2: 2324 3
3: 29 1
4: 1010 3
</code></pre>
<p>The approach above is row-by-row as suggested <a href="https://stackoverflow.com/questions/74250585/how-to-count-number-of-unique-entries-after-merging-two-data-tables-in-r">here</a>, but my real dataset has millions of rows. What's another way of doing this that's faster?</p>
| [
{
"answer_id": 74416216,
"author": "patrick",
"author_id": 73804,
"author_profile": "https://Stackoverflow.com/users/73804",
"pm_score": -1,
"selected": false,
"text": " <table>\n\n<tr>\n <td style=\"border:1px solid black;\">\n Spaltenweise\n </td>\n <td style=\"border:1px solid black;\">\n \n \n<table>\n<tr>\n<td style=\"border:1px solid black;\">\n A04\n </td>\n</tr>\n<tr>\n <td style=\"border:1px solid black;\">\n 100\n </td>\n <td style=\"border:1px solid black;\">\n 200\n </td>\n <td style=\"border:1px solid black;\">\n 300\n </td>\n</tr>\n<tr >\n<td colspan=3 style=\"border:1px solid black;\">\n spalte 1 2 3 4\n </td>\n</tr>\n</table>\n </td>\n</tr>\n\n\n</table>"
},
{
"answer_id": 74416696,
"author": "kountouris panagiotis",
"author_id": 20271835,
"author_profile": "https://Stackoverflow.com/users/20271835",
"pm_score": 2,
"selected": false,
"text": "HTML"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3391549/"
] |
74,416,190 | <p>Suppose we have a Stream of Animals.</p>
<p>We have different Subclasses of Animals, and we want to apply a filter on the stream to only have the Zebras of the Stream. We now still have a Stream of Animals, but only containing Zebras. To get a stream of Zebras we still need to cast.</p>
<pre class="lang-java prettyprint-override"><code>Stream<Zebra> zebraStream = animalStream
.filter(Zebra.class::isInstance)
.map(Zebra.class::cast);
</code></pre>
<p>Java 14 introduced pattern matching for instanceof, so we can now use:</p>
<pre class="lang-java prettyprint-override"><code>if (animal instanceof Zebra zebra) {
System.out.println(zebra.countStripes());
}
</code></pre>
<p>Is there a way to use pattern matching in stream pipes?
Of course you could do something like this:</p>
<pre class="lang-java prettyprint-override"><code>Stream<Zebra> zebraStream = animalStream.map(animal -> {
if (animal instanceof Zebra zebra) {
return zebra;
}
return null;
})
.filter(Objects::nonNull);
</code></pre>
<p>But IMHO this is really ugly.</p>
| [
{
"answer_id": 74416358,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 4,
"selected": true,
"text": "mapMulti()"
},
{
"answer_id": 74416406,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": 0,
"selected": false,
"text": "filter"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17133024/"
] |
74,416,247 | <p>I am going to make the <code>imageView</code> and <code>textView</code> side by side in a <code>cardView</code>. It looks good when in design but behaves weird when I run the app.</p>
<p>My <code>item_offer_list.xml</code> file is as below:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UseCompoundDrawables">
<ImageView
android:id="@+id/cv_iv_photo_poster"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="null"
tools:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_toEndOf="@+id/cv_iv_photo_poster"
android:gravity="center"
android:text="@string/app_name">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</code></pre>
<p>I have used above design in recycler view as below:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".OfferWallListFragment">
<LinearLayout
android:id="@+id/llRecyclerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
android:orientation="horizontal">
<ProgressBar
android:id="@+id/pbLoadingItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<TextView
android:id="@+id/txtNoConnection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:visibility="gone"
tools:text="No Internet Connection" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_OfferData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:visibility="visible"
tools:listitem="@layout/item_offer_list">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>My design looks good as below :</p>
<p><a href="https://i.stack.imgur.com/ZFxS7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZFxS7.png" alt="enter image description here" /></a></p>
<p>But when I run the app in emulator my image is very large but and covers all the space as below:</p>
<p><a href="https://i.stack.imgur.com/XyZfJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XyZfJ.png" alt="enter image description here" /></a></p>
<p>Why this behaves like this I dont know? Please look into it if any idea.</p>
| [
{
"answer_id": 74416653,
"author": "Pavel Startsev",
"author_id": 11160418,
"author_profile": "https://Stackoverflow.com/users/11160418",
"pm_score": 2,
"selected": true,
"text": "ImaveView"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13147529/"
] |
74,416,248 | <p>I have been assigned a task, and I cannot seem to figure out how I should proceed with it. It seemed relatively easy, but I must be doing something wrong, I would love it if someone could give me guidance. The code I have so far is:</p>
<pre><code>infile = open("dataset.txt", "r")
outfile = open("emails.txt", "w")
def main():
lines = infile.splitlines()
for line in lines:
if line.find("@", ".")!= -1:
print(line)
infile.close()
outfile.close()
</code></pre>
<p>In dataset.txt is the 20 Newsgroups data set(which is the data set that I am working with). The task is this: Find all valid sender e-mails (the email Ids that have the symbol “@” and “.”) in
the given data set and write them to a new file: “emails.txt”
Make sure you also display the number of characters in each email beside the
email address.Your file must not contain duplicate emails. At the end of your file, display the total numbers of emails in the file and their
average length.</p>
| [
{
"answer_id": 74416367,
"author": "great_pan",
"author_id": 20200173,
"author_profile": "https://Stackoverflow.com/users/20200173",
"pm_score": 0,
"selected": false,
"text": "import re\n\nEMAIL_PATTERN = r'([a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z]{2,5})'\n\ndef main():\n with open('dataset.txt', 'r') as in_file:\n lines = in_file.read().splitlines()\n with open('emails.txt', 'a') as out_file:\n for line in lines:\n match = re.search(EMAIL_PATTERN, line)\n if match is not None:\n out_file.write(match.group(1) + '\\n')\n\nmain()\n"
},
{
"answer_id": 74416380,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 1,
"selected": false,
"text": "str.find"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9223978/"
] |
74,416,265 | <p>I have the following code. I am trying to select the 4th (index) item from a list at a given index location of the dataframe 'df'.</p>
<pre><code>trialoutcomes = []
for j in range(0,len(df.columns)):
for i in range(5,len(df)):
trialoutcome = df.loc[i,j]
trialoutcomes.append(trialoutcome[4])
</code></pre>
<p>However, I keep getting the error: ''float' object is not subscriptable', although I am not sure as to why.</p>
<p>When I take the code out of the loop below and enter the following code, I get the output I want, indicating a 'fullMiss' trial.</p>
<pre><code>easy = df.loc[5,0]
print(easy[4])
fullMiss
</code></pre>
<p>However, in the context of the loop above this does not work.</p>
<p>When I enter:</p>
<pre><code>df.loc[5,0]
</code></pre>
<p>This prints:</p>
<pre><code>['trial', '2:7|2:8|4:1|4:2|8:3|8:4|', '4:7', '4:7', 'fullMiss', '5.828', '11', '37', '66']
</code></pre>
<p>I would be so grateful for a helping hand!</p>
<p>The first 10 rows of the 'df' dataframe looks something like this:</p>
<pre><code> 0 ... 77
5 [trial, 2:7|2:8|4:1|4:2|8:3|8:4|, 4:7, 4:7, fu... ... [trial, 7:4|7:5|2:2|3:2|2:7|2:8|, 4:3, 3:4, fu...
6 [trial, 2:3|3:3|7:6|8:6|3:7|3:8|, 2:7, 2:7, ne... ... [trial, 4:8|5:8|7:3|8:3|2:2|3:2|, 6:2, 6:2, ne...
7 [trial, 3:6|4:6|1:1|1:2|5:2|6:2|, 3:7, 4:6, hi... ... [trial, 5:5|5:6|3:1|4:1|1:6|1:7|, 6:7, 7:8, fu...
8 [trial, 8:5|8:6|1:7|1:8|7:1|8:1|, 2:2, 2:1, fu... ... [trial, 3:3|4:3|2:7|2:8|6:7|7:7|, 4:6, 3:6, ne...
9 [trial, 5:8|6:8|4:3|5:3|9:2|9:3|, 5:3, 5:3, hi... ... [trial, 7:2|7:3|1:4|1:5|5:7|6:7|, 3:4, 4:5, fu...
10 [trial, 1:5|2:5|6:2|7:2|8:7|9:7|, 2:5, 1:6, ne... ... [trial, 7:2|7:3|1:1|2:1|5:7|6:7|, 5:8, 5:9, fu...
11 [trial, 2:2|2:3|4:7|5:7|8:2|8:3|, 4:2, 5:3, fu... ... [trial, 1:3|2:3|5:8|5:9|9:2|9:3|, 5:6, 4:5, fu...
12 [trial, 2:2|2:3|5:9|6:9|8:2|8:3|, 6:5, 7:6, fu... ... [trial, 2:3|2:4|7:4|7:5|8:9|9:9|, 6:8, 6:9, fu...
13 [trial, 2:4|3:4|8:8|9:8|7:2|8:2|, 8:8, 8:9, ne... ... [trial, 2:2|3:2|7:7|7:8|7:3|8:3|, 4:5, 4:5, fu...
14 [trial, 7:5|8:5|3:4|3:5|6:9|7:9|, 7:4, 7:3, fu... ... [trial, 6:3|6:4|3:9|4:9|2:2|2:3|, 4:8, 4:9, hi...
</code></pre>
| [
{
"answer_id": 74416538,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 2,
"selected": true,
"text": "a=['trial', '2:7|2:8|4:1|4:2|8:3|8:4|', '4:7', '4:7', 'fullMiss', '5.828', '11', '37', '66']\n\nprint(a[4]) #fullMiss\n\na=np.nan\nprint(a[4]) #TypeError: 'float' object is not subscriptable\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12985497/"
] |
74,416,272 | <p><strong>Update</strong>: as chepner points out in the comments, creating the class in the function is a bad idea, it performs ten to eighty times slower than other solutions. See the performance comparison in my self-answer, which also shows how to do the typing.</p>
<hr />
<p>I do this:</p>
<pre class="lang-py prettyprint-override"><code>def get_an_x():
class X:
foo = 1
bar = 'Hello'
baz = None
return X
</code></pre>
<p><code>get_an_x</code> returns a class <code>X</code>, which serves as a plain structure.</p>
<p>What is the type of this class <code>X</code>? Doing <code>def get_an_x() -> type: ...</code> (that what <code>type(X)</code> returns) will not work, then PyCharms's type checker does not detect the attributes of <code>X</code>. Annotating the attributes with <code>ClassVar[...]</code> also does not help.</p>
<p>I have seen <a href="https://stackoverflow.com/a/43457817/1658543">this answer</a>, but doing <code>def get_an_x() -> type[X]: ...</code> does not work, because I define the class inside the function, and it is not seen from outside.</p>
| [
{
"answer_id": 74416538,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 2,
"selected": true,
"text": "a=['trial', '2:7|2:8|4:1|4:2|8:3|8:4|', '4:7', '4:7', 'fullMiss', '5.828', '11', '37', '66']\n\nprint(a[4]) #fullMiss\n\na=np.nan\nprint(a[4]) #TypeError: 'float' object is not subscriptable\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658543/"
] |
74,416,273 | <p>How can I make an SQL query to select records that do not have at least one child element?</p>
<p>I have 3 tables: <em>article</em> (~40K rows), <em>calendar</em> (~450K rows) and <em>calendar_cost</em> (~500K rows).</p>
<p>It is necessary to select such entries of the <em>article</em> table:</p>
<ol>
<li>there are no entries in the <em>calendar</em> table,</li>
<li>if there are entries in the <em>calendar</em> table, then all of them should not have any entries in the <em>calendar_cost</em> table.</li>
</ol>
<pre><code>create table article (
id int PRIMARY KEY,
name varchar
);
create table calendar (
id int PRIMARY KEY,
article_id int REFERENCES article (id) ON DELETE CASCADE,
number varchar
);
create table calendar_cost (
id int PRIMARY KEY,
calendar_id int REFERENCES calendar (id) ON DELETE CASCADE,
cost_value numeric
);
insert into article (id, name) values
(1, 'Article 1'),
(2, 'Article 2'),
(3, 'Article 3');
insert into calendar (id, article_id, number) values
(101, 1, 'Point 1-1'),
(102, 1, 'Point 1-2'),
(103, 2, 'Point 2');
insert into calendar_cost (id, calendar_id, cost_value) values
(400, 101, 100.123),
(401, 101, 400.567);
</code></pre>
<p>As a result, "Article 2" (condition 2) and "Article 3" (condition 1) will suit us.</p>
<p>My SQL query is very slow (the second condition part), how can I do it optimally? Is it possible to do without "union all" operator?</p>
<pre><code>-- First condition
select a.id from article a
left join calendar c on a.id = c.article_id
where c.id is null
union all
-- Second condition
select a.id from article a
where id not in(
select aa.id from article aa
join calendar c on aa.id = c.article_id
join calendar_cost cost on c.id = cost.calendar_id
where aa.id = a.id limit 1
)
</code></pre>
<p><strong>UPDATE</strong></p>
<p>This is how you can fill my tables with random data for about the same amount of data. The @Bohemian query is very fast, and the rest are very slow. But as soon as I applied 2 indexes, as @nik advised, all queries began to be executed very, very quickly!</p>
<pre><code>do $$
declare
article_id int;
calendar_id bigint;
i int; j int;
begin
create table article (
id int PRIMARY KEY,
name varchar
);
create table calendar (
id serial PRIMARY KEY,
article_id int REFERENCES article (id) ON DELETE CASCADE,
number varchar
);
create INDEX ON calendar(article_id);
create table calendar_cost (
id serial PRIMARY KEY,
calendar_id bigint REFERENCES calendar (id) ON DELETE CASCADE,
cost_value numeric
);
create INDEX ON calendar_cost(calendar_id);
for article_id in 1..45000 loop
insert into article (id, name) values (article_id, 'Article ' || article_id);
for i in 0..floor(random() * 25) loop
insert into calendar (article_id, number) values (article_id, 'Number ' || article_id || '-' || i) returning id into calendar_id;
for j in 0..floor(random() * 2) loop
insert into calendar_cost (calendar_id, cost_value) values (calendar_id, round((random() * 100)::numeric, 3));
end loop;
end loop;
end loop;
end $$;
</code></pre>
<pre><code>@Bohemian
Planning Time: 0.405 ms
Execution Time: 1196.082 ms
@nbk
Planning Time: 0.702 ms
Execution Time: 165.129 ms
@Chris Maurer
Planning Time: 0.803 ms
Execution Time: 800.000 ms
@Stu
Planning Time: 0.446 ms
Execution Time: 280.842 ms
</code></pre>
<p>So which query to choose now as the right one is a matter of taste.</p>
| [
{
"answer_id": 74416398,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 3,
"selected": true,
"text": "calendar_cost"
},
{
"answer_id": 74416418,
"author": "Chris Maurer",
"author_id": 5440883,
"author_profile": "https://Stackoverflow.com/users/5440883",
"pm_score": 1,
"selected": false,
"text": "select a.id\nfrom article a\n Inner Join (\n Select article_id\n From calendar c left join calendar_cost cc\n On c.id=cc.calendar_id\n Where cc.calendar_id is null\n) cnone\n On a.id = cnone.article_id\n"
},
{
"answer_id": 74416421,
"author": "nbk",
"author_id": 5193536,
"author_profile": "https://Stackoverflow.com/users/5193536",
"pm_score": 1,
"selected": false,
"text": "create table article (\n id int PRIMARY KEY,\n name varchar(100)\n);\n\ncreate table calendar (\n id int PRIMARY KEY,\n article_id int REFERENCES article (id) ON DELETE CASCADE,\n number varchar(100)\n ,index(article_id)\n);\n\ncreate table calendar_cost (\n id int PRIMARY KEY,\n calendar_id int REFERENCES calendar (id) ON DELETE CASCADE,\n cost_value numeric\n ,INDEX(calendar_id)\n);\n\ninsert into article (id, name) values\n(1, 'Article 1'),\n(2, 'Article 2'),\n(3, 'Article 3');\n\ninsert into calendar (id, article_id, number) values\n(101, 1, 'Point 1-1'),\n(102, 1, 'Point 1-2'),\n(103, 2, 'Point 2');\n\ninsert into calendar_cost (id, calendar_id, cost_value) values\n(400, 101, 100.123),\n(401, 101, 400.567);\n\n"
},
{
"answer_id": 74416437,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 1,
"selected": false,
"text": "select a.id \nfrom article a \nwhere not exists (\n select * from calendar c \n where c.article_id = a.id\n)\nor (exists (\n select * from calendar c \n where c.article_id = a.id\n)\n and not exists (\n select * from calendar_cost cc\n where cc.calendar_id in (select id from calendar c where c.article_id = a.id)\n )\n);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4289313/"
] |
74,416,280 | <p>I have a parent component with a handler function:</p>
<pre><code> const folderRef = useRef();
const handleCollapseAllFolders = () => {
folderRef.current.handleCloseAllFolders();
};
</code></pre>
<p>In the parent, I'm rendering multiple items (folders):</p>
<pre><code> {folders &&
folders.map(folder => (
<CollapsableFolderListItem
key={folder.id}
name={folder.name}
content={folder.content}
id={folder.id}
ref={folderRef}
/>
))}
</code></pre>
<p>In the child component I'm using the <code>useImperativeHandle</code> hook to be able to access the child function in the parent:</p>
<pre><code> const [isFolderOpen, setIsFolderOpen] = useState(false);
// Collapse all
useImperativeHandle(ref, () => ({
handleCloseAllFolders: () => setIsFolderOpen(false),
}));
</code></pre>
<p>The problem is, when clicking the button in the parent, it only collapses the last opened folder and not all of them.</p>
<p>Clicking this:</p>
<pre><code> <IconButton
onClick={handleCollapseAllFolders}
>
<UnfoldLessIcon />
</IconButton>
</code></pre>
<p>Only collapses the last opened folder.</p>
<p>When clicking the button, I want to set the state of <strong>ALL</strong> opened folders to <code>false</code> not just the last opened one.</p>
<p>Any way to solve this problem?</p>
| [
{
"answer_id": 74416384,
"author": "kind user",
"author_id": 6695924,
"author_profile": "https://Stackoverflow.com/users/6695924",
"pm_score": 3,
"selected": true,
"text": "ref"
},
{
"answer_id": 74416414,
"author": "Mart",
"author_id": 19493125,
"author_profile": "https://Stackoverflow.com/users/19493125",
"pm_score": 0,
"selected": false,
"text": "useImperativeHandle"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15637129/"
] |
74,416,329 | <p>I have all my rules in the Validation config file, like the documentation suggest:
<a href="https://codeigniter4.github.io/userguide/libraries/validation.html#saving-sets-of-validation-rules-to-the-config-file" rel="nofollow noreferrer">https://codeigniter4.github.io/userguide/libraries/validation.html#saving-sets-of-validation-rules-to-the-config-file</a></p>
<p>For example:</p>
<pre><code>public $userCreate = [
'first_name' => [
'label' => 'First Name',
'rules' => 'required|string|max_length[60]'
],
'last_name' => [
'label' => 'Last Name',
'rules' => 'required|string|max_length[60]',
],
'email' => [
'label' => 'Auth.email',
'rules' => 'required|max_length[254]|valid_email|is_unique[users.email]',
],
];
</code></pre>
<p>In my controllers I can access my validation groups like this:</p>
<pre><code>$validation = \Config\Services::validation();
$rules = $validation->getRuleGroup('userCreate');
</code></pre>
<p>As my app gets bigger, I need more and more validation rules, so the question is, is there a way to organize them in separate files and not to have all of them in a single config file? Something like the custom rules, which are loaded in the config file and stored separately.</p>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815054/"
] |
74,416,341 | <p>If I have a function:</p>
<pre><code>def chars(str1: str, str2: str, str3: str) -> str:
</code></pre>
<p>What should I put inside this so that it returns a new string where the character at index i is
str1[i] if str3[i] is 0 and str2[i] if str3[i] is 1.</p>
<p>for example, if I had:</p>
<pre><code>chars('dog', 'cat', '001')
</code></pre>
<p>it would output:</p>
<pre><code>dot #since the first 0 is d from str1, the second 0 is o from str1 and the 1 is t from str2
</code></pre>
<p>Another example could be:</p>
<pre><code>chars('army', 'game', '0011')
</code></pre>
<p>it would output:</p>
<pre><code>arme ##since the first 0 is a from str1, the second 0 is r from str1, the first 1 is m from str2 and the second 1 is e from str2
</code></pre>
<p>This is what I tried so far:</p>
<pre><code>for i in range(len(str3)):
if str3[i] == '0':
return str1[i]
else:
return str2[i]
</code></pre>
<p>but it only returns the first letter and nothing else so how would I fix this?</p>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20343843/"
] |
74,416,350 | <p>Create a program that will keep track of items for a shopping list. The program should keep asking for new items until nothing is entered (no input followed by enter key). The program should then display the full shopping list</p>
<p>How do I write the condition so it works?</p>
<p>The code I'm writing looks like this:</p>
<pre><code>x = []
i = 0
while i != '':
x.append(input('what u want?'))
i = i + 1
print(x)
```
`
</code></pre>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20486946/"
] |
74,416,359 | <p>Im trying to run docker inside jenkins container, i used this command to create jenkins container</p>
<p><code>docker run -p 8080:8080 -p 50000:50000 -d -v jenkins_home:/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock -v $(which docker):/usr/bin/docker jenkins/jenkins:latest</code></p>
<p>then this command to access jenkins container bash
<code>docker exec -u 0 -it <container-id> bash</code>, whenever i run <code>docker</code> i get this error</p>
<p><code>docker: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.32' not found (required by docker) docker: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.34' not found (required by docker)</code></p>
<p>What is creating this problem and what ways in order to solve it ?</p>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5736821/"
] |
74,416,420 | <p>I have a data that was identified as having JSON format. The data is in a *.txt file and the following is a snapshot from the text:</p>
<pre><code>{"company_number":"09145694","data":{"address":{"address_line_1":"St. Andrews Road","country":"England","locality":"Henley-On-Thames","postal_code":"RG9 1HP","premises":"2"},"ceased_on":"2018-05-14","country_of_residence":"England","date_of_birth":{"month":2,"year":1977},"etag":"3b8caf795c03af63921e381f7bb8300a51ebb73d","kind":"individual-person-with-significant-control","links":{"self":"/company/09145694/persons-with-significant-control/individual/bIhuKnMFctSnjrDjUG8n3NgOrlU"},"name":"Mrs Nga Thanh Wildman","name_elements":{"forename":"Nga","middle_name":"Thanh","surname":"Wildman","title":"Mrs"},"nationality":"Vietnamese","natures_of_control":["ownership-of-shares-50-to-75-percent"],"notified_on":"2016-04-06"}}
{"company_number":"08581893","data":{"address":{"address_line_1":"High Street","address_line_2":"Wendover","country":"England","locality":"Aylesbury","postal_code":"HP22 6EA","premises":"14a","region":"Buckinghamshire"},"ceased_on":"2016-07-01","country_of_residence":"England","date_of_birth":{"month":9,"year":1947},"etag":"45f9c9e5494b574eb52abc3990a49bd96fe09df3","kind":"individual-person-with-significant-control","links":{"self":"/company/08581893/persons-with-significant-control/individual/RgR9Zhc7yGhV0SBys8_WJ6H9O1o"},"name":"Mr Stephen Robert Charles Davies","name_elements":{"forename":"Stephen","middle_name":"Robert Charles","surname":"Davies","title":"Mr"},"nationality":"British","natures_of_control":["ownership-of-shares-25-to-50-percent","ownership-of-shares-25-to-50-percent-as-firm"],"notified_on":"2016-06-30"}}
{"company_number":"08581893","data":{"address":{"address_line_1":"High Street","address_line_2":"Wendover","country":"England","locality":"Aylesbury","postal_code":"HP22 6EA","premises":"14a","region":"Buckinghamshire"},"ceased_on":"2016-07-01","country_of_residence":"England","date_of_birth":{"month":6,"year":1965},"etag":"d55168c49f85ab1ef38a12ed76238d68f79f5a01","kind":"individual-person-with-significant-control","links":{"self":"/company/08581893/persons-with-significant-control/individual/-6HQmkhiomEBXJI2rgHccU67fpM"},"name":"Mr Quentin Colin Maxwell Solt","name_elements":{"forename":"Quentin","middle_name":"Colin Maxwell","surname":"Solt","title":"Mr"},"nationality":"British","natures_of_control":["ownership-of-shares-25-to-50-percent","voting-rights-25-to-50-percent"],"notified_on":"2016-06-30"}}
</code></pre>
<p>How do I transfer this to a normal excel table with appropriate headings please?</p>
<p>The code i Have tried is from the suggestion in the comments and i have added the dictionary to the excel file as described here, suggested by @skin.</p>
<p>github.com/VBA-tools/VBA-JSON</p>
<p>I am getting a 424 error on the line</p>
<pre><code>Set Parsed = JsonConverter.ParseJson(JsonText)
</code></pre>
<p>Here is the code:</p>
<pre><code>Sub jsonchik()
Dim FSO As New FileSystemObject
Dim JsonTS As TextStream
Dim JsonText As String
Dim Parsed As Dictionary
' Read .json file
Set JsonTS = FSO.OpenTextFile("psc-snapshot-2022-11-12_1of22.txt", ForReading)
JsonText = JsonTS.ReadAll
JsonTS.Close
' Parse json to Dictionary
' "values" is parsed as Collection
' each item in "values" is parsed as Dictionary
Set Parsed = JsonConverter.ParseJson(JsonText)
' Prepare and write values to sheet
Dim Values As Variant
ReDim Values(Parsed("values").Count, 3)
Dim Value As Dictionary
Dim i As Long
i = 0
For Each Value In Parsed("values")
Values(i, 0) = Value("a")
Values(i, 1) = Value("b")
Values(i, 2) = Value("c")
i = i + 1
Next Value
Sheets("example").Range(Cells(1, 1), Cells(Parsed("values").Count, 3)) = Values
End Sub
</code></pre>
<p>Many thanks,</p>
<p>Suren</p>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6740849/"
] |
74,416,426 | <p>i try to modify a background div when i hover a child div. Please notice that i have more than one child and here is my solution.</p>
<p>But i'm pretty sure that there is a better way to achieve that who will of course be visible by all navigators (I.E, Firefox, Safari, Opera, Chrome...) That's why i didn't use the has() option !!</p>
<p>here is my <a href="https://jsfiddle.net/kodjoe/oh1u2nvq/#save" rel="nofollow noreferrer">jsfiddle</a></p>
<pre><code><h2 class="wl-bg-collectif">
<span class="w-text-block" style="display: block;">
<span class="w-text-content">ONE</span>
</span>
</h2>
<h2 class="wl-bg-prive">
<span class="w-text-block" style="display: block;">
<span class="w-text-content">TWO</span>
</span>
</h2>
<h2 class="wl-bg-live">
<span class="w-text-block" style="display: block;">
<span class="w-text-content">THREE</span>
</span>
</h2>
</code></pre>
<pre><code>.w-text-content {
padding-bottom: 600px!important;
margin-bottom: -600px!important;
display: block;
text-align: left;
}
.wl-bg-collectif .w-text-content:hover {
background: transparent url(https://res2.yourwebsite.life/res/5ef668f5db29eb0022cd0cd6/636f04c51f4f1b000d196c8c) no-repeat right top!important;
background-size: 50%!important;
z-index: -1;
color: #F24908!important;
}
.wl-bg-prive .w-text-content:hover {
background: transparent url(https://res2.yourwebsite.life/res/5ef668f5db29eb0022cd0cd6/636f04c51f4f1b000d196c8c) no-repeat right top!important;
background-size: 50%!important;
z-index: -1;
color: #F24908!important;
}
.wl-bg-live .w-text-content:hover {
background: transparent url(https://res2.yourwebsite.life/res/5ef668f5db29eb0022cd0cd6/636f04c51f4f1b000d196c8c) no-repeat right top!important;
background-size: 50%!important;
z-index: -1;
color: #F24908!important;
}
</code></pre>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488448/"
] |
74,416,443 | <p>Can I erase last byte or bytes in file without creating new file and changing names?</p>
<p>For example, file contains "00 00 AB" and i need erase "AB". At the end, file contains only "00 00".</p>
| [
{
"answer_id": 74417753,
"author": "steven7mwesigwa",
"author_id": 7376590,
"author_profile": "https://Stackoverflow.com/users/7376590",
"pm_score": 1,
"selected": false,
"text": "app/Validation"
},
{
"answer_id": 74419759,
"author": "Dusan",
"author_id": 1815054,
"author_profile": "https://Stackoverflow.com/users/1815054",
"pm_score": 1,
"selected": true,
"text": "<?php\n\nnamespace App\\Validation;\n\nclass Auth {\n\n public $login = [\n 'email' => [\n 'label' => 'E-mail',\n 'rules' => 'required|max_length[254]|valid_email',\n ],\n 'password' => [\n 'label' => 'Password',\n 'rules' => 'required',\n ],\n 'remember' => [\n 'label' => 'Remember me',\n 'rules' => 'if_exist|permit_empty|integer',\n ]\n ];\n\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488473/"
] |
74,416,460 | <p>How can I get the number of unique words from a <code><textarea></code> in JavaScript?</p>
<p>Not sure how to approach this problem, I can seem to get all the different letters used but don't know how I would get all the unique words.</p>
<pre><code>function uniqueWordCount(text) {
var distinctWords = [];
for (var i = 0; i < text.length; i++) {
if (distinctWords.indexOf(text[i]) === -1) {
distinctWords.push(text[i]);
}
}
alert(distinctWords);
return distinctWords.length;
}
</code></pre>
| [
{
"answer_id": 74416531,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 2,
"selected": false,
"text": "const textarea = document.querySelector('textarea')\nconst count = document.querySelector('p')\n\nhandleInput()\n\ntextarea.addEventListener('input', handleInput)\n\nfunction handleInput() {\n const words = textarea.value.split(/\\s+/g)\n const uniqueWords = new Set(words)\n count.textContent = uniqueWords.size\n}"
},
{
"answer_id": 74416963,
"author": "BenoitB",
"author_id": 20364258,
"author_profile": "https://Stackoverflow.com/users/20364258",
"pm_score": 1,
"selected": false,
"text": "// Return the number of token of an Input string based upon a Separator\nfunction CountToken(Input = \"\", Separator = ' ') {\n return Input == \"\" ? 0 : Input.split(Separator).length;\n}\n\nconsole.log(CountToken()); // Return 0\nconsole.log(CountToken(\"test\")); // Return 1\nconsole.log(CountToken(\"test now\")); // Return 2\nconsole.log(CountToken(\"06-33-545-322-33\", '-')); // Return 5\n"
},
{
"answer_id": 74417344,
"author": "xehpuk",
"author_id": 1178016,
"author_profile": "https://Stackoverflow.com/users/1178016",
"pm_score": 2,
"selected": false,
"text": "<textarea>"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20085772/"
] |
74,416,471 | <p>I am trying to create an iterative DFS but I can't seem to add items to the visited set?
After, I will try to do a recursive DFS. I'm not uite sure what I am doing wrong here. Assistance would be greatly appreciated. <3</p>
<pre><code>const adjList = {
1: [2, 5],
2: [1, 3, 5],
3: [2, 4],
4: [3, 5, 6],
5: [1, 2, 4],
6: [4]
}
</code></pre>
<pre><code>function printDepthFirst(start, visited = new Set()) {
// your code here
let adj = adjList;
const stack = [];
stack.push(start);
visited.add(start)
let visitedArr = [];
while(stack.length) {
let Node = stack.pop();
visitedArr.push(Node)
console.log(" Visited Node: " + Node)
let neighbors = adj[Node]
for (let i = 0; i < neighbors.length; i++) {
if (!visited.has(neighbors[i])) {
stack.push(neighbors[i]);
}
}
neighbors.forEach(neighbor => visited.add(neighbor))
}
console.log("Visited Nodes: " + JSON.stringify([...visited]))
console.log("VisstedArr: " + visitedArr)
return false;
}
</code></pre>
<pre><code>console.log("First Test:")
printDepthFirst(3); // Prints 1 through 6 in Depth-first order, starting with 3
// One possible solution: 3, 4, 6, 5, 1, 2
console.log("Second Test:")
printDepthFirst(6); // Prints 1 through 6 in Depth-first order, starting with 6
// One possible solution: 6, 4, 5, 2, 1, 3
console.log("Third Test:")
printDepthFirst(4); // Prints 1 through 6 in Depth-first order, starting with 4
// One possible solution: 4, 6, 5, 2, 1, 3
</code></pre>
| [
{
"answer_id": 74416531,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 2,
"selected": false,
"text": "const textarea = document.querySelector('textarea')\nconst count = document.querySelector('p')\n\nhandleInput()\n\ntextarea.addEventListener('input', handleInput)\n\nfunction handleInput() {\n const words = textarea.value.split(/\\s+/g)\n const uniqueWords = new Set(words)\n count.textContent = uniqueWords.size\n}"
},
{
"answer_id": 74416963,
"author": "BenoitB",
"author_id": 20364258,
"author_profile": "https://Stackoverflow.com/users/20364258",
"pm_score": 1,
"selected": false,
"text": "// Return the number of token of an Input string based upon a Separator\nfunction CountToken(Input = \"\", Separator = ' ') {\n return Input == \"\" ? 0 : Input.split(Separator).length;\n}\n\nconsole.log(CountToken()); // Return 0\nconsole.log(CountToken(\"test\")); // Return 1\nconsole.log(CountToken(\"test now\")); // Return 2\nconsole.log(CountToken(\"06-33-545-322-33\", '-')); // Return 5\n"
},
{
"answer_id": 74417344,
"author": "xehpuk",
"author_id": 1178016,
"author_profile": "https://Stackoverflow.com/users/1178016",
"pm_score": 2,
"selected": false,
"text": "<textarea>"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19677744/"
] |
74,416,494 | <p>So I was given a computer science problem to write a function which accepts two natural numbers and returns their product. The rules are that I am only allowed to use the addition of 1 (variable + 1), assigning and comparison operation. I end up with this code in python:</p>
<pre><code>def multiplication_of_ab(a, b):
placeholder = 0
result = 0
for counter in range(b):
while (placeholder < a):
placeholder += 1
result += placeholder
placeholder = 0
return result
if __name__ == "__main__":
print(mulitplication_of_ab(3, 4))
</code></pre>
<p>Maybe there is a solution that better fills the conditions?</p>
| [
{
"answer_id": 74416562,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "def multiply(a, b):\n c = 0\n for i in range(a):\n for j in range(b):\n c += 1\n return c\n"
},
{
"answer_id": 74416878,
"author": "Oli",
"author_id": 6744133,
"author_profile": "https://Stackoverflow.com/users/6744133",
"pm_score": 1,
"selected": true,
"text": "range"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11313947/"
] |
74,416,496 | <p>I need to return the count of first N natural numbers using a while loop.</p>
<p>My code is:</p>
<pre><code>def count_until(seconds):
cnt=seconds
while(cnt):
cnt-=1
return str(cnt)
print(count_until(10))
</code></pre>
<p>It is returning <code>9</code>
but I want the result to be like this: <code>9 8 7 6 5 4 3 2 1</code></p>
<p>My other similar code with a <code>print</code> statement works perfectly fine:</p>
<pre><code>def count_until(seconds):
cnt=seconds
while(cnt):
cnt-=1
print(str(cnt))
count_until(10)
</code></pre>
<p>Can I make the code with a return statement?</p>
| [
{
"answer_id": 74416532,
"author": "Kedar U Shet",
"author_id": 13542152,
"author_profile": "https://Stackoverflow.com/users/13542152",
"pm_score": 1,
"selected": false,
"text": "def count_until(seconds):\n cnt=seconds\n out = \"\"\n while(cnt-1):\n cnt-=1\n out+=\" \" + str(cnt)\n return out\n\nprint(count_until(10))\n"
},
{
"answer_id": 74416547,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "def count_until(seconds):\n s=\"\"\n for i in range(seconds):\n s+=str(seconds-i)+\" \"\n return s\n"
},
{
"answer_id": 74416551,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 0,
"selected": false,
"text": "return"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488468/"
] |
74,416,517 | <p>I have created a simple demo page for learning firebase,</p>
<p>here I have a textfield, searchbutton and StreamBuilder for showing all records</p>
<p>I have placed a condition for showing all records when textfield is empty...</p>
<p>here I have used a button which just rebuild...just used setState inside it onpressed</p>
<p>everything working well, but I just want to improve that record should be filter while typing on textfield so that no need of button there.</p>
<p>how to call StreamBuilder's stream in textfield change.... and in addition, I have created customTextField,,so how to pass function as onChange requires a value...</p>
<p>here is my coding</p>
<pre><code>Column(
children: [
SizedBox(
height: 40,
),
CustomTextField(
hint: 'Search Email', controller: txtsearchcontroller),
SizedBox(
height: 20,
),
CupertinoButton(
child: Text('Search'),
onPressed: () {
setState(() {});
}),
SizedBox(
height: 30,
),
StreamBuilder(
stream: txtsearchcontroller.text == ''
? FirebaseFirestore.instance
.collection('chatusers')
.snapshots()
: FirebaseFirestore.instance
.collection('chatusers')
.where(
"email",
isEqualTo: txtsearchcontroller.text,
isNotEqualTo: widget.usermodel.email,
)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
if (snapshot.hasData) {
QuerySnapshot querysnapshot =
snapshot.data as QuerySnapshot;
if (querysnapshot.docs.length > 0) {
//and suggest me if any better way instead of this following
List<Map<String, dynamic>> maplist = [];
for (int x = 0; x < querysnapshot.docs.length; x++) {
Map<String, dynamic> usermap = querysnapshot.docs[x]
.data() as Map<String, dynamic>;
maplist.add(usermap);
}
return Expanded(
child: CustomListView(maplist:maplist),
);
} else {
return Text('Has Data but No user Found');
}
} else {
if (snapshot.hasError) {
return Text('error found');
} else {
return Text('empty..');
}
}
} else {
return CircularProgressIndicator();
}
}),
</code></pre>
<p>here is my CustomTextField</p>
<pre><code>class CustomTextField extends StatelessWidget {
final String hint;
final bool isitpassword;
final TextEditingController controller;
const CustomTextField({Key? key,required this.hint,this.isitpassword=false,required this.controller}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(20),
),
child: TextField(
style: TextStyle(
fontSize: 20,color: Colors.white,),
controller: controller,
obscureText: isitpassword,
decoration: InputDecoration(
border: InputBorder.none,
hintText: hint,
suffixIcon: IconButton(icon: Icon(Icons.close,color: Colors.white,),onPressed: (){
controller.text='';
},),
),
)),
);
}
}
</code></pre>
| [
{
"answer_id": 74416675,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": "TextField"
},
{
"answer_id": 74416699,
"author": "samedhrmn",
"author_id": 13077944,
"author_profile": "https://Stackoverflow.com/users/13077944",
"pm_score": 1,
"selected": false,
"text": "enum SearchState {\n INITIAL,\n LOADING,\n LOADED,\n}\n\nStreamController<SearchState> searchController = StreamController.broadcast()..add(SearchState.INITIAL);\n\nList<ChatUser?> searchResult = []; // your filtered results\n List<ChatUser?> users = []; // all users\n\nvoid searchOperation({required String searchText}) { \n searchController.add(SearchState.LOADING); // User is typing\n\n searchResult.clear();\n for (var element in users) {\n final word = element?.username?.trim();\n if (word?.toLowerCase().contains(searchText.toLowerCase()) == true) { // your equality logic here\n searchResult.add(element);\n }\n }\n\n searchController.add(SearchState.LOADED);\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,416,557 | <p>When I recall this function, its output is zero. The x in output should be a vector containing 365 values based on timepoints from 1 to 365. Maybe there is something wrong with the function definition or returning values.</p>
<pre><code>vax_fun = function(timepoint, parms1){
with (
as.list (parms1),
{
if (timepoint < T0){
v_t = 0
return((v_t))
} else if (timepoint <= T1){
v_t = timepoint * (exp(tetha)-C_0)/(T1-T0) + C_0 - T0 * (exp(tetha)-C_0)/(T1-T0)
return((v_t))
}else if (timepoint <= T2){
v_t = (exp(tetha)* timepoint)
return((v_t))
} else if (timepoint <= T3){
v_t = -timepoint * (exp(tetha)-C_1)/(T3-T2) + C_1 - T3 * (exp(tetha)-C_1)/(T3-T2)
return((v_t))
} else {
v_t=0
return((v_t))
}
}
)
}
</code></pre>
<pre><code>parms1=c(
T0=55,
T1=115,
T2=175,
T3=235,
threshold = 275,
tetha = 5,
C_0 = 100,
C_1 = 100
)
for (timepoint in 1:365){
x = vax_fun(timepoint, parms1)
x
}
</code></pre>
| [
{
"answer_id": 74418565,
"author": "dcarlson",
"author_id": 1580645,
"author_profile": "https://Stackoverflow.com/users/1580645",
"pm_score": 0,
"selected": false,
"text": "y <- NULL\nfor (timepoint in 1:365){\n x = vax_fun(timepoint, parms1)\n y <- c(y, x)\n}\nstr(y)\n# num [1:365] 0 0 0 0 0 0 0 0 0 0 ...\nsummary(y)\n# Min. 1st Qu. Median Mean 3rd Qu. Max. \n# -279.2 0.0 0.0 3528.5 123.4 25972.3 \n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488525/"
] |
74,416,561 | <p>The program receives an input of a number containing 6 symbols, and if the sum of the first three digits is the same as the sum of the second three digits, then the number is considered lucky.</p>
<p>This is the code I have now, and it works with every number except those that start with 0 and I'm not sure how to fix it:</p>
<pre><code>a = int(input())
n = str(a)
m = (n[0]), (n[1]), (n[2])
s = (n[3]), (n[4]), (n[5])
if str(sum(int(x) for x in m)) == str(sum(int(x) for x in s)):
print('Lucky')
else:
print('Regular')
</code></pre>
| [
{
"answer_id": 74418565,
"author": "dcarlson",
"author_id": 1580645,
"author_profile": "https://Stackoverflow.com/users/1580645",
"pm_score": 0,
"selected": false,
"text": "y <- NULL\nfor (timepoint in 1:365){\n x = vax_fun(timepoint, parms1)\n y <- c(y, x)\n}\nstr(y)\n# num [1:365] 0 0 0 0 0 0 0 0 0 0 ...\nsummary(y)\n# Min. 1st Qu. Median Mean 3rd Qu. Max. \n# -279.2 0.0 0.0 3528.5 123.4 25972.3 \n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20352757/"
] |
74,416,563 | <p>I have the following DF</p>
<pre><code>Cod Category N
1 A 1
1 A 2
1 A 3
1 B 1
1 B 2
1 B 3
1 B 4
1 B 5
2 D 1
3 Z 1
3 Z 2
3 Z 3
3 Z 4
</code></pre>
<p>I need to filter this DF to, when N > 3, then all values for the category should be retrieved. My expected output to simplify the example:</p>
<pre><code>Cod Category N
1 B 1
1 B 2
1 B 3
1 B 4
1 B 5
3 Z 1
3 Z 2
3 Z 3
3 Z 4
</code></pre>
<p>How Can I Implement this type of filter? I tried to use window functions to generate another column with a Flag indicating to filter, but with no success.</p>
| [
{
"answer_id": 74416657,
"author": "vinsce",
"author_id": 3811895,
"author_profile": "https://Stackoverflow.com/users/3811895",
"pm_score": 3,
"selected": true,
"text": "N"
},
{
"answer_id": 74417249,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 1,
"selected": false,
"text": "df =spark.createDataFrame([(1 , 'A', 1 ),\n(1 , 'A' , 2),\n(1 , 'A' , 3),\n(1 ,'B' , 1),\n(1 , 'B' , 2),\n(1 , 'B' , 3),\n(1 , 'B' , 4),\n(1 , 'B' , 5),\n(2 , 'D' , 1),\n(3 , 'Z' , 1),\n(3 , 'Z' , 2)],\n('Cod', 'Category', 'N'))\n\n\n\n\nnew = (df.withColumn('check', collect_list('N').over(Window.partitionBy('cod','Category')))#create array per group and keep in column check\n \n .where(expr(\"exists(check, c -> array_contains(check,3))\"))#Filter arrays that do not contaiin 3\n .drop('check')#drop column check\n ).show()\n"
},
{
"answer_id": 74418891,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 1,
"selected": false,
"text": "isin()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16459035/"
] |
74,416,643 | <p>Im developing a website and one of the requests is a division with an image, like below: <a href="https://i.stack.imgur.com/3ylVj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3ylVj.png" alt="" /></a></p>
<p>But this is what i got:
<a href="https://i.stack.imgur.com/AzsH6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AzsH6.png" alt="" /></a></p>
<p>Is it possible to make it in CSS?</p>
<p>I already inserted the image and set the background colors, the one thing left on this is that wave effect on the image.</p>
<p>The CSS code, ive only set its position:
`</p>
<pre><code>/* Format coffepic */
img#coffee{
position: absolute;
top: 1200px;
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74416657,
"author": "vinsce",
"author_id": 3811895,
"author_profile": "https://Stackoverflow.com/users/3811895",
"pm_score": 3,
"selected": true,
"text": "N"
},
{
"answer_id": 74417249,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 1,
"selected": false,
"text": "df =spark.createDataFrame([(1 , 'A', 1 ),\n(1 , 'A' , 2),\n(1 , 'A' , 3),\n(1 ,'B' , 1),\n(1 , 'B' , 2),\n(1 , 'B' , 3),\n(1 , 'B' , 4),\n(1 , 'B' , 5),\n(2 , 'D' , 1),\n(3 , 'Z' , 1),\n(3 , 'Z' , 2)],\n('Cod', 'Category', 'N'))\n\n\n\n\nnew = (df.withColumn('check', collect_list('N').over(Window.partitionBy('cod','Category')))#create array per group and keep in column check\n \n .where(expr(\"exists(check, c -> array_contains(check,3))\"))#Filter arrays that do not contaiin 3\n .drop('check')#drop column check\n ).show()\n"
},
{
"answer_id": 74418891,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 1,
"selected": false,
"text": "isin()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20427057/"
] |
74,416,646 | <p>I'm working on a Cypress test for the Polish Wikipedia plugin, and I have this code in my cypress test:</p>
<pre class="lang-js prettyprint-override"><code>Cypress.Commands.overwrite('visit', (orig, path, options) => {
return orig(`https://pl.wikipedia.org/${path}`);
});
Cypress.Commands.add('login', (pass) => {
cy.visit('/w/index.php?title=Specjalna:Zaloguj');
cy.get('#wpName1').type('<username>');
cy.get('#wpPassword1').type(pass);
cy.get('#userloginForm form').submit();
});
Cypress.Commands.add('dark_vector_wait', (pass) => {
cy.get('.vector-menu-content-list > li:nth-child(7)', { timeout: 10000 }).should('be.visible');
});
</code></pre>
<p>And in my spec:</p>
<pre class="lang-js prettyprint-override"><code>describe('dark vector test', () => {
beforeEach('login', () => {
cy.login(Cypress.env('WIKI_PASSWORD'));
});
it('test discussion', () => {
cy.visit('/wiki/Dyskusja_wikipedysty:<username>');
cy.dark_vector_wait();
cy.matchImageSnapshot('discussion');
});
it('testing-page page', () => {
cy.visit('/wiki/Wikipedysta:<username>/testing-page');
cy.dark_vector_wait();
cy.matchImageSnapshot('testing-page');
});
});
</code></pre>
<p>And the second test is failing because as soon as Cypress type the password it automatically submits a form so <code>cy.get('#userloginForm form').submit();</code> is executing after Cypress visits the home page (default redirect) and fail to find a form.</p>
<p>What's wrong? Why does Cypress auto-submit a form after a second time? This is not what Wikipedia is doing since the login form doesn't have any JavaScript code and you need to click login to be able to login to Wikipedia.</p>
<p><strong>EDIT</strong>:</p>
<p>I've tried to</p>
<ul>
<li>Use BaseURL and remove overwrite of <code>visit</code>.</li>
<li>Add <code>type('{enter}')</code>, but this only shows an error: <code>cy.type() failed because this element is detached from the DOM.</code></li>
</ul>
<p><strong>EDIT 2</strong></p>
<p>This is the screenshot of the action taken by cypress, second test has a page load without <code>{enter}</code> action and without form submit.</p>
<p><a href="https://i.stack.imgur.com/gXg9z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gXg9z.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74416899,
"author": "TesterDick",
"author_id": 18366749,
"author_profile": "https://Stackoverflow.com/users/18366749",
"pm_score": 1,
"selected": false,
"text": "Cypress.Commands.overwrite('visit')"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387194/"
] |
74,416,667 | <p>I am trying to integrate a second click listener on recyclerview but I could not do it.</p>
<p>I am developing a checklist and I created recyclerview. Inside the recyclerview, there are a checkbox and textview. I can handle the click listener on textview or on itemclick.</p>
<p>But I can not handle the checkbox, check or uncheck event?</p>
<p>I am storing the data on Firebase but this is not a problem. I just can not handle second click listener on adapter class.</p>
<p>Thank you very much for your answers in advance.</p>
<p>adapter class</p>
<pre><code>package com.example.shoppinglist
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class CheckListRecyclerViewAdapterClass (
var checkList: List<CheckListModelClass>,
private val clickListener: (CheckListModelClass) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var checkListTotalList: List<CheckListModelClass> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val myView = LayoutInflater.from(parent.context).inflate(R.layout.check_list_rec_view_model_layout, parent, false)
return CheckListViewHolder(myView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as CheckListViewHolder).bind(checkListTotalList[position], clickListener)
}
override fun getItemCount(): Int {
return checkListTotalList.size
}
fun submitList(checkList: List<CheckListModelClass>) {
checkListTotalList = checkList
}
fun updateList(checkList: List<CheckListModelClass>) {
checkListTotalList = checkList
notifyDataSetChanged()
}
class CheckListViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val checkListCheckBox: CheckBox = itemView.findViewById(R.id.check_list_rec_view_model_layout_checkBox)
private val checkListTextView: TextView = itemView.findViewById(R.id.check_list_rec_view_model_layout_textView)
fun bind(
checkListModelClass: CheckListModelClass,
clickListener: (CheckListModelClass) -> Unit
) {
checkListTextView.text = checkListModelClass.checkListItemName
val checkListCheckBoxPosition = checkListModelClass.checkListItemCheckListPosition
checkListCheckBox.isChecked = checkListCheckBoxPosition
checkListTextView.setOnClickListener { clickListener(checkListModelClass) }
}
}
}
</code></pre>
<p>main activity;</p>
<pre><code>package com.example.shoppinglist
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.Source
class MainActivity : AppCompatActivity() {
private var checkListTotalListArray = ArrayList<CheckListModelClass>()
private lateinit var checkListRecyclerViewAdapterClass: CheckListRecyclerViewAdapterClass
private lateinit var checkListModelClass: CheckListModelClass
private lateinit var addItemToListEditText: EditText
private lateinit var firebaseFirestore: FirebaseFirestore
private lateinit var collectionReference: CollectionReference
private lateinit var source: Source
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
firebaseFirestore = FirebaseFirestore.getInstance()
collectionReference = firebaseFirestore.collection("shoppingList")
checkListTotalListArray = arrayListOf()
checkListRecyclerViewAdapterClass =
CheckListRecyclerViewAdapterClass(checkListTotalListArray) { checkListModelClassItem: CheckListModelClass ->
checkListClickListener(checkListModelClassItem)
}
takeDataFromFireStore()
//recyclerview
val checkListRecyclerView = findViewById<RecyclerView>(R.id.check_list_recycler_view)
val checkListTotalListLayoutManager = LinearLayoutManager(this)
checkListTotalListLayoutManager.orientation = LinearLayoutManager.VERTICAL
checkListRecyclerView.layoutManager = checkListTotalListLayoutManager
checkListRecyclerView.adapter = checkListRecyclerViewAdapterClass
addItemToListEditText = findViewById(R.id.check_list_fragment_item_enter_edit_text)
addItemToListEditText.imeOptions = EditorInfo.IME_ACTION_DONE
addItemToListEditText.isSingleLine = true
addItemToList()
}
private fun checkListClickListener(checkListModelClass: CheckListModelClass) {
//handle click listener
Toast.makeText(this, "first click listener", Toast.LENGTH_LONG).show()
}
private fun checkListClickListenerTwo(checkListModelClass: CheckListModelClass) {
//handle click listener
Toast.makeText(this, "first click listener two", Toast.LENGTH_LONG).show()
}
private fun takeDataFromFireStore(){
checkListTotalListArray.clear()
collectionReference.get().addOnSuccessListener { documents ->
if (!documents.isEmpty) {
for (document in documents){
val resultForCheckListItems: CheckListModelClass = document.toObject<CheckListModelClass>(CheckListModelClass::class.java)
checkListTotalListArray.add(resultForCheckListItems)
}
checkListRecyclerViewAdapterClass.submitList(checkListTotalListArray)
checkListRecyclerViewAdapterClass.notifyDataSetChanged()
}
}
.addOnFailureListener { exception ->
Log.w("listen_data", "Error getting documents: ", exception)
}
}
private fun saveDataToFireStore(){
collectionReference.document()
.set(checkListModelClass, SetOptions.merge())
.addOnSuccessListener {
takeDataFromFireStore()
Log.d("TAG", "DocumentSnapshot successfully written!")
}
.addOnFailureListener { e -> Log.w("TAG", "Error writing document", e) }
}
private fun addItemToList(){
addItemToListEditText.onDone { addItemToListEditText.hideKeyboard() }
}
private fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
private fun EditText.onDone(callback: () -> Unit) {
// These lines optional if you don't want to set in Xml
imeOptions = EditorInfo.IME_ACTION_DONE
maxLines = 1
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Your action on done
if(addItemToListEditText.text.toString() != "") {
checkListModelClass =
CheckListModelClass(false, addItemToListEditText.text.toString())
saveDataToFireStore()
//checkListTotalListArray.add(checkListModelClass)
//checkListRecyclerViewAdapterClass.updateList(checkListTotalListArray)
addItemToListEditText.text.clear()
}
callback.invoke()
true
}
false
}
}
}
</code></pre>
<p>model class;</p>
<pre><code>package com.example.shoppinglist
class CheckListModelClass(
var checkListItemCheckListPosition: Boolean = false,
var checkListItemName: String = ""
)
</code></pre>
| [
{
"answer_id": 74416899,
"author": "TesterDick",
"author_id": 18366749,
"author_profile": "https://Stackoverflow.com/users/18366749",
"pm_score": 1,
"selected": false,
"text": "Cypress.Commands.overwrite('visit')"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9645476/"
] |
74,416,686 | <p><a href="https://i.stack.imgur.com/ZThtq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZThtq.png" alt="error" /></a></p>
<p>I keep getting the name error repeatedly, though I do not understand what I should do further please help</p>
<p>Edit: <a href="https://i.stack.imgur.com/zcFF2.png" rel="nofollow noreferrer">code before error part</a>
so when i remove these four lines, the error is resolved, what was the problem?</p>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488648/"
] |
74,416,689 | <p>How can I regroup all the symbols like <code>"!@#$%^&*()_+[]{}'\"|./?><"</code> and use them, if the variable contains the symbols it will return <code>False</code>?</p>
<p>I'm trying to create a code for the password, and if the password contains only symbols like <code>"!@#$%^&*()_+[]{}'\"|./?><"</code>, return <code>False</code>.</p>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488647/"
] |
74,416,690 | <p>I am creating a <code>tf.data.Dataset</code> where I start with <code>list_files</code> to get all paths to my images. The annotations are stored on disc as json files. The structure of the json file is</p>
<pre><code>{
"img1.png": {
data ...
},
"img2.png": ...
}
</code></pre>
<p>Hence the key-value is the image name.</p>
<p>I can easily extract the image names from the paths provided by <code>list_files</code>. However, that is <code>tf.string</code>, which cannot be used directly(?) to access the values in the annotation.</p>
<p>Is there an easy way to convert the <code>tf.string</code> to a python string so I can read the groundtruth data from the json file?</p>
<p>Alternatively convert the annotation to a proper <code>tf type</code>.</p>
<pre><code>from typing import Mapping
from numpy import ndarray
import tensorflow as tf
import cv2 as cv
from pathlib import Path
from typing import Any, Mapping, NamedTuple
import json
class Point:
x: float
y: float
def __init__(self, x: float, y: float):
self.x = x
self.y = y
class BoundingBox(NamedTuple):
top: float
left: float
bottom: float
right: float
class Annotation:
image: tf.Tensor
bounding_box: tf.Tensor
is_visible: bool
def __init__(self, image, bounding_box, is_visible):
self.image = image
self.bounding_box = bounding_box
self.is_visible = is_visible
LABELS = {
"NO_CLUB": 0,
"CLUB": 1,
"bbox": BoundingBox,
}
def is_in_split(image_path: tf.string, is_training: bool) -> bool:
hash = tf.strings.to_hash_bucket_fast(image_path, 10)
if is_training:
return hash < 8
else:
return hash >= 8
def create_image_and_annotation(image_path: tf.string, annotation: Mapping[str, Any]):
bits = tf.io.read_file(image_path)
file_split = tf.strings.split(image_path, "/")
image_name = file_split[-1]
suffix = tf.strings.split(image_name, ".")[-1]
jpeg = [
tf.convert_to_tensor("jpg", dtype=tf.string),
tf.convert_to_tensor("JPG", dtype=tf.string),
tf.convert_to_tensor("jpeg", dtype=tf.string),
tf.convert_to_tensor("JPEG", dtype=tf.string),
]
is_jpeg = [tf.math.equal(suffix, s) for s in jpeg]
png = [
tf.convert_to_tensor("png", dtype=tf.string),
tf.convert_to_tensor("PNG", dtype=tf.string),
]
is_png = [tf.math.equal(suffix, s) for s in png]
if tf.math.reduce_any(is_jpeg):
image = tf.io.decode_jpeg(bits, channels=3)
else:
image = tf.io.decode_png(bits, channels=3)
# Here I want to use image_name to access the annotation for the specific image! <---
bounding_box = BoundingBox(0,0,10,10)
return image, (bounding_box, True)
def createDataset(dir: Path, annotation: Mapping[str, Any], is_training: bool) -> tf.data.Dataset:
image_path_png = str(dir / "images" / "*.png")
image_path_PNG = str(dir / "images" / "*.PNG")
image_path_jpg = str(dir / "images" / "*.jpg")
image_path_JPG = str(dir / "images" / "*.JPG")
image_path_jpeg = str(dir / "images" / "*.jpeg")
image_path_JPEG = str(dir / "images" / "*.JPEG")
image_dirs = [image_path_png, image_path_PNG, image_path_jpg, image_path_JPG, image_path_jpeg, image_path_JPEG]
dataset = (tf.data.Dataset.list_files(image_dirs)
.shuffle(1000)
.map(lambda x: create_image_and_annotation(x, annotation))
)
for d in dataset:
pass
return dataset
def getDataset(data_root_path: Path, is_training: bool) -> tf.data.Dataset:
dirs = [x for x in data_root_path.iterdir() if x.is_dir()]
datasets = []
for dir in dirs:
json_path = dir / "annotations.json"
with open(json_path) as json_file:
annotation = json.load(json_file)
createDataset(dir, annotation, is_training=is_training)
training_data = getDataset(Path("/home/erik/Datasets/ClubHeadDetection"), True)
</code></pre>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2225895/"
] |
74,416,693 | <p>If I have a Python3 <code>xml.etree.Element</code> (<a href="https://docs.python.org/3.6/library/xml.etree.elementtree.html#element-objects" rel="nofollow noreferrer">doc</a>), is it possible to get a list (or iterable, or whatever) of child elements to that <code>Element</code>, but <strong><em>only</em></strong> one level deep? If so, how can I do this?</p>
<p>(Note: it appears the <code>xml.etree.Element</code> library is essentially the same for the version of Python I'm using (3.6.8) and the latest version (3.11).)</p>
<hr />
<p>For example, say I have this xml:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Document>
<name>myName</name>
<SomeLevel1Element>
<SomeLevel2Element>foo</SomeLevel2Element>
</SomeLevel1Element>
<SomeLevel1Element>
<SomeLevel2Element>bar</SomeLevel2Element>
</SomeLevel1Element>
<AnotherLevel1Element>
</AnotherLevel1Element>
</Document>
</code></pre>
<p>I want to do something like:</p>
<pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ET
tree = ET.parse(PATH_TO_XML_FILE)
root = tree.getroot()
direct_children_of_root = <something>
for child in direct_children_of_root:
print(child)
"""
<Element 'name' at 0x123abc>
<Element 'SomeLevel1Element' at 0x123bbc>
<Element 'SomeLevel1Element' at 0x123cbc>
<Element 'AnotherLevel1Element' at 0x123dbc>
"""
</code></pre>
<hr />
<p>I cannot use <code>findall()</code>, <code>find()</code>, <code>findtext()</code>, since I may not know the amount or kinds of child elements of <code>root</code>.</p>
<hr />
<p>I cannot use <code>iter()</code>, since that method appears to give <strong><em>all</em></strong> children of <strong><em>all</em></strong> children elements.</p>
<p>For example, using the same xml as above:</p>
<pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ET
tree = ET.parse(PATH_TO_XML_FILE)
root = tree.getroot()
elems = root.iter()
for e in elems:
print(e)
"""
<Element 'Document' at 0x123abc>
<Element 'name' at 0x123bbc>
<Element 'SomeLevel1Element' at 0x123cbc>
<Element 'SomeLevel2Element' at 0x123dbc>
<Element 'SomeLevel1Element' at 0x123ebc>
<Element 'SomeLevel2Element' at 0x123fbc>
<Element 'AnotherLevel1Element' at 0x124abc>
"""
</code></pre>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274086/"
] |
74,416,707 | <p>Given a string that can only be <strong>a single ASCII character</strong> or <strong>an emoji char sequence</strong>.
How can I tell one from another?</p>
<p>The idea is to separate emojis from plain text, by the spec if you are given a string of chars mixed with emojis then by doing <code>for (..of)</code> you can get substrings of ASCII chars and Emojis sparately</p>
<pre><code>const text = 'ascii and emojis mixed'
for (const char of text) {
// ... here, a char would be either an ASCII char or an emoji sequence string
if (seeIfAscii(char)) {
console.log('ASCII', char);
} else {
console.log('Emoji', char);
}
}
function seeIfAscii(char) {
// what comes here? <--- QUESTION!!!
}
</code></pre>
<p>As to why, I need to clump ASCII chars together and keep emojis one by one separate.</p>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139667/"
] |
74,416,710 | <p>I try to deploy <strong>debian containers</strong> to allow users to connect to them over SSH (for students for exemple).</p>
<p>I managed to do this but when I am connected to the container I have a <strong>pseudo-TTY</strong> and it's not the expected result I want. I want to have a complete interactive shell like when we connect to a reel server or machine.</p>
<p>I tried several ideas like :</p>
<ul>
<li><p>change the docker add options in my <code>docker run</code> commands like : <code>docker run -d -it CONAINER_ID</code></p>
</li>
<li><p>change the <code>sshd_config</code> in the debian container to allow TTY</p>
</li>
<li><p>change my dockerfile many times</p>
</li>
<li><p>add <code>ssh</code> options when I connect : <code>ssh -t</code> or <code>ssh -tt</code></p>
</li>
</ul>
<p>But any of theses ideas seems to help me. I show you my current Dockerfile it can be helpfull.</p>
<pre><code>FROM debian:latest
RUN apt-get update && apt-get install -y openssh-server && apt-get install -y sudo nano
RUN mkdir /var/run/sshd
RUN service ssh start
RUN useradd -m john && echo "john:john" | chpasswd && adduser john sudo
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
</code></pre>
<p>So can any one tell me if I can change or do something to resolve this problem please ? Thanks</p>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488534/"
] |
74,416,720 | <p>I want to make automated login to router web GUI, but if I use
input_tags.send_keys("PASSWORD"), then I get error</p>
<blockquote>
<p>AttributeError: 'list' object has no attribute 'send_keys'.</p>
</blockquote>
<p>Here is my code example</p>
<pre><code>#imports
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
#login
driver = webdriver.Chrome()
driver.get('http://ROUTER_IP')
password = driver.find_elements(By.ID, "login_password")
password.send_keys("PASSWORD")
</code></pre>
<p>Here is webpage inspect picture:</p>
<p><a href="https://i.stack.imgur.com/5p3OC.png" rel="nofollow noreferrer">webpage inspect picture</a></p>
<p>Here is my output:</p>
<blockquote>
<p>AttributeError: 'list' object has no attribute 'send_keys'</p>
</blockquote>
<p>I tried to Google this, but I found nothing.</p>
| [
{
"answer_id": 74416709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "image_numbers = range(len(os.listdir(“YOUR_DIR”)))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488583/"
] |
74,416,729 | <p>I’m sure many have come across this problem because I can’t be the only one.</p>
<p>In Visual Studio code I work with Kubernetes and Azure Devops YAML. Both have complete different formatting. To work with each I find I have to uninstall the others extension.</p>
<p>Has anyone worked out, how to have both together where VSCode can work out when your coding an Azure DevOps pipeline or a Kubernetes cluster?</p>
| [
{
"answer_id": 74462369,
"author": "flyx",
"author_id": 347964,
"author_profile": "https://Stackoverflow.com/users/347964",
"pm_score": 0,
"selected": false,
"text": "\"files.associations\""
},
{
"answer_id": 74464686,
"author": "Jason",
"author_id": 15469962,
"author_profile": "https://Stackoverflow.com/users/15469962",
"pm_score": 2,
"selected": true,
"text": "http://www.schemastore.org/json/composer"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15469962/"
] |
74,416,758 | <p>I want end="" to stop after it has removed all the spaces between integers.</p>
<p>The result I get is this:</p>
<pre><code>106111104110word
</code></pre>
<p>but I want to get this:</p>
<pre><code>106111104110
word
</code></pre>
<p>Code:</p>
<pre><code>name = 'john'
for char in name:
print(ord(char), end="")
print("word")
</code></pre>
| [
{
"answer_id": 74416775,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 1,
"selected": false,
"text": "\\n"
},
{
"answer_id": 74416799,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 0,
"selected": false,
"text": "name = 'john' \n\nfor char in name:\n print(ord(char), end=\"\")\nprint()\nprint(\"word\")\n"
},
{
"answer_id": 74416829,
"author": "Dodo",
"author_id": 20488733,
"author_profile": "https://Stackoverflow.com/users/20488733",
"pm_score": 3,
"selected": true,
"text": "name = 'john' \nresult = \"\"\n\nfor char in name:\n result += str(ord(char))\n\nprint(result)\nprint(\"word\")\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15179155/"
] |
74,416,770 | <p>can anybody help me to create a Dataframe in python with for loop: I want to create a Dataframe from two lists:
list1 and list of lists (list2) where the length of list1 = the number of sublists in list2:
an example:
list1= ["A", "B", "C", "D"]
list2= [[1, 2, 3, 4], [1, 3, 4, 6, 7], [2, 3, 4, 5, 6], [2, 4, 5, 7, 8]]=></p>
<pre><code>my goal is to add/ iterate the values in list1 to matching the values in each sublist in list2 attached (and see belwo) is my final target/wished table:
| Col1 | Col2 |
| -------- | -------- |
| A | 1
| A | 2
A 3
A 4
B 1
B 3
B 4
B 6
B 7
</code></pre>
<p>Thank you in advance for answering my questions.</p>
| [
{
"answer_id": 74416793,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "list1 = [\"A\", \"B\", \"C\", \"D\"]\nlist2 = [[1, 2, 3, 4], [1, 3, 4, 6, 7], [2, 3, 4, 5, 6], [2, 4, 5, 7, 8]]\n\ndf = pd.DataFrame(zip(list1, list2), columns=[\"Col1\", \"Col2\"]).explode(\"Col2\")\nprint(df)\n"
},
{
"answer_id": 74416809,
"author": "Omar",
"author_id": 9289463,
"author_profile": "https://Stackoverflow.com/users/9289463",
"pm_score": 0,
"selected": false,
"text": "df = pd.DataFrame(list(zip(list1, list2)),\n columns =['list1_name', 'list2_name'])\n"
},
{
"answer_id": 74416876,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "numpy.repeat"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12861707/"
] |
74,416,827 | <p>So, I am trying to output folder & file structure to a txt file, using the below code. But I want to get relative paths outputed instead of absolute paths.</p>
<pre><code>
import os
absolute_path = os.path.dirname(__file__)
with open("output.txt", "w", newline='') as a:
for path, subdirs, files in os.walk(absolute_path):
a.write(path + os.linesep)
for filename in files:
a.write('\t%s\n' % filename)
</code></pre>
<p>For now this gives me something like this</p>
<pre><code>C:\Users\User\OneDrive\bla\bla
C:\Users\User\OneDrive\bla\bla\folder1
file1.xxx
file2.xxx
file3.xxx
C:\Users\User\OneDrive\bla\bla\folder2
test1.txt
</code></pre>
<p>but I want to show only relative paths to where the script ran, not more</p>
<pre><code>.\bla
.\bla\folder1
file1.xxx
file2.xxx
file3.xxx
.\bla\folder2
test1.txt
</code></pre>
<p>I have fiddled around a bit, but not getting to the solution, nor finding it here (or maybe I am not searching for the correct thing)</p>
<p>Any help would be appreciated</p>
<pre><code></code></pre>
| [
{
"answer_id": 74416793,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "list1 = [\"A\", \"B\", \"C\", \"D\"]\nlist2 = [[1, 2, 3, 4], [1, 3, 4, 6, 7], [2, 3, 4, 5, 6], [2, 4, 5, 7, 8]]\n\ndf = pd.DataFrame(zip(list1, list2), columns=[\"Col1\", \"Col2\"]).explode(\"Col2\")\nprint(df)\n"
},
{
"answer_id": 74416809,
"author": "Omar",
"author_id": 9289463,
"author_profile": "https://Stackoverflow.com/users/9289463",
"pm_score": 0,
"selected": false,
"text": "df = pd.DataFrame(list(zip(list1, list2)),\n columns =['list1_name', 'list2_name'])\n"
},
{
"answer_id": 74416876,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "numpy.repeat"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488737/"
] |
74,416,833 | <p>file <strong>tools.h</strong>:</p>
<pre><code>//some macro definitions
struct name;
//other function prototypes
</code></pre>
<hr />
<p>file <strong>tools.c</strong>:</p>
<pre><code>#include "tools.h"
struct name
{
FILE *src;
int value;
}
//definitions of functions declared in tools.h
</code></pre>
<hr />
<p>file <strong>main.c</strong>:</p>
<pre><code>#include <stdio.h>
#include "tools.h"
int main()
{
struct name *ptr;
ptr = malloc(sizeof(struct name));
ptr->FILE = fopen(filename, "r");
ptr->value = 12;
...
}
</code></pre>
<hr />
<ol>
<li><p>At first, I built tools.o by using:<br />
<code>$ gcc tools.c -c</code><br />
Without any error or warning, <code>tools.o</code> was built in the current directory.</p>
</li>
<li><p>Now, I tried to build executable by using:<br />
<code>$ gcc main.c tools.o -o exe</code><br />
and I got errors of same type (all the errors were of same type, caused due to accessing the struct element). Here's the sample of that error I got:</p>
</li>
</ol>
<pre><code>main.c: In function ‘main’:
main.c:17:22: error: invalid use of undefined type ‘struct name’
17 | buffer = malloc(ptr->value+1);
</code></pre>
<hr />
<p>Please explain why this happened and what wrong I did while linking or in my code.</p>
| [
{
"answer_id": 74416942,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": true,
"text": "#ifndef TOOLS_H\n#define TOOLS_H\n\n#include <stdio.h>\n\nstruct name\n{\n FILE *src;\n int value;\n};\n\nint foo(struct name*);\nstruct name *bar(double, FILE*, const char *); //prototypes of functions defined in tools.c\n#endif\n"
},
{
"answer_id": 74420879,
"author": "H.S.",
"author_id": 8542346,
"author_profile": "https://Stackoverflow.com/users/8542346",
"pm_score": 1,
"selected": false,
"text": "tools.h"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333834/"
] |
74,416,862 | <pre><code>listdict = {
'list_1' : ['1'],
'list_2' : ['1','2'],
'list_3' : ['2'],
'list_4' : ['1', '2', '3', '4']
}
print(len(listdict))
</code></pre>
<p>This is my code for example. I want it to print:</p>
<pre><code>8
</code></pre>
<p>I have tried length as u can see but it prints 4 of course the amount of lists but I want it to print
the amount of items in the lists. Is there a way where I can do this with one statement instead of doing them all seperately? Thanks in advance.</p>
<p>I tried using len(dictionaryname) but that did not work</p>
| [
{
"answer_id": 74416942,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 3,
"selected": true,
"text": "#ifndef TOOLS_H\n#define TOOLS_H\n\n#include <stdio.h>\n\nstruct name\n{\n FILE *src;\n int value;\n};\n\nint foo(struct name*);\nstruct name *bar(double, FILE*, const char *); //prototypes of functions defined in tools.c\n#endif\n"
},
{
"answer_id": 74420879,
"author": "H.S.",
"author_id": 8542346,
"author_profile": "https://Stackoverflow.com/users/8542346",
"pm_score": 1,
"selected": false,
"text": "tools.h"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20323201/"
] |
74,416,867 | <p>I searched the web for this very simple question but I didn´t find a simple answer.</p>
<p>Tried next lines with error but I´d like to know if there is a simplest way.</p>
<pre><code>List<string> listaStr = new List<string> {"cero","uno","dos","tres","cuatro"};
List<int> indices = new List<int> {0,4};
var valores = new List<object>();
foreach (var i in indices)
{
valores.Add(listaStr[i]);
}
foreach (var i in valores)
{
Console.WriteLine(valores[i]);
}
</code></pre>
<p>Expecting as output: "cero","cuatro" in a new list (valores)</p>
| [
{
"answer_id": 74416907,
"author": "Gabriel Stancu",
"author_id": 8187400,
"author_profile": "https://Stackoverflow.com/users/8187400",
"pm_score": 2,
"selected": true,
"text": " List<string> listaStr = new List<string> {\"cero\",\"uno\",\"dos\",\"tres\",\"cuatro\"};\n List<int> indices = new List<int> {0,4};\n var selectedStrings = new List<object>();\n \n foreach(var index in indices)\n {\n selectedStrings.Add(listaStr[index]);\n }\n \n foreach(var value in selectedStrings)\n {\n Console.WriteLine(value);\n }\n"
},
{
"answer_id": 74416956,
"author": "Bouke",
"author_id": 6864688,
"author_profile": "https://Stackoverflow.com/users/6864688",
"pm_score": 0,
"selected": false,
"text": "var listaStr = new List<string> { \"cero\", \"uno\", \"dos\", \"tres\", \"cuatro\" };\nvar indices = new List<int> { 0, 4 };\nvar selectedStrings = new List<string>();\n\nforeach (var i in indices)\n{\n selectedStrings.Add(listaStr[i]);\n}\n\nforeach (var s in selectedStrings)\n{\n Console.WriteLine(s);\n}\n"
},
{
"answer_id": 74417130,
"author": "Bouke",
"author_id": 6864688,
"author_profile": "https://Stackoverflow.com/users/6864688",
"pm_score": 0,
"selected": false,
"text": "var listaStr = new List<string> { \"cero\", \"uno\", \"dos\", \"tres\", \"cuatro\" };\nvar indices = new List<int> { 0, 4 };\n\nvar selectedStrings = listaStr.Where(x => indices.Contains(listaStr.IndexOf(x))).ToList();\n\nforeach (var s in selectedStrings)\n{\n Console.WriteLine(s);\n}\n"
},
{
"answer_id": 74513317,
"author": "jptrujillol",
"author_id": 20373528,
"author_profile": "https://Stackoverflow.com/users/20373528",
"pm_score": 0,
"selected": false,
"text": "var listaStr = new List<string> { \"cero\", \"uno\", \"dos\", \"tres\", \"cuatro\" };\nvar indices = new List<int> { 0, 4 };\n\nvar selectedStrings = listaStr.Where((x,i) => indices.Contains(i)).ToList();\n\nforeach (var s in selectedStrings)\n{\n Console.WriteLine(s);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373528/"
] |
74,416,886 | <p>I have a problem of the form:</p>
<p>min (x1 - k1) + (x2 -k2) + ...</p>
<p>k are constants</p>
<p>with linear constraints:</p>
<p>A*x = B</p>
<p>B's size is 3x1, A is 3xn and x is nx1</p>
<p>I also have linear bounds inequalities in the form</p>
<p>l1 <= x1 <= u1</p>
<p>l2 <= x2 <= u2 ...etc</p>
<p>I'm trying to resolve it in python with scipy :</p>
<pre><code>import numpy as np
from scipy.optimize import Bounds, minimize, fmin_cobyla
A = \
np.array([[ 0.11, 0.1333, 0.1333, 0.01],
[ 0.02, 6.667, 0.1333, 0.12],
[0.0933, 0.6667, 0.6, 0.01]])
B = \
np.array([[25],
[57],
[28]])
l = \
np.array([[50],
[20],
[5],
[50]])
u = \
np.array([[200],
[80],
[20],
[200]])
def objfun(x):
return np.linalg.norm((x - (u-l)/2))
x0 = \
np.array([[1],
[2],
[3],
[4]])
bounds = Bounds(l, u)
eq_cons = {'type': 'eq', 'fun': lambda x: np.matmul(A,x)-B}
res = minimize(objfun, x0, method='SLSQP',
constraints=[eq_cons], options={'ftol': 1e-9, 'disp': True},
bounds=bounds)
</code></pre>
<p>but it gives me the following error:</p>
<p>all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 74416907,
"author": "Gabriel Stancu",
"author_id": 8187400,
"author_profile": "https://Stackoverflow.com/users/8187400",
"pm_score": 2,
"selected": true,
"text": " List<string> listaStr = new List<string> {\"cero\",\"uno\",\"dos\",\"tres\",\"cuatro\"};\n List<int> indices = new List<int> {0,4};\n var selectedStrings = new List<object>();\n \n foreach(var index in indices)\n {\n selectedStrings.Add(listaStr[index]);\n }\n \n foreach(var value in selectedStrings)\n {\n Console.WriteLine(value);\n }\n"
},
{
"answer_id": 74416956,
"author": "Bouke",
"author_id": 6864688,
"author_profile": "https://Stackoverflow.com/users/6864688",
"pm_score": 0,
"selected": false,
"text": "var listaStr = new List<string> { \"cero\", \"uno\", \"dos\", \"tres\", \"cuatro\" };\nvar indices = new List<int> { 0, 4 };\nvar selectedStrings = new List<string>();\n\nforeach (var i in indices)\n{\n selectedStrings.Add(listaStr[i]);\n}\n\nforeach (var s in selectedStrings)\n{\n Console.WriteLine(s);\n}\n"
},
{
"answer_id": 74417130,
"author": "Bouke",
"author_id": 6864688,
"author_profile": "https://Stackoverflow.com/users/6864688",
"pm_score": 0,
"selected": false,
"text": "var listaStr = new List<string> { \"cero\", \"uno\", \"dos\", \"tres\", \"cuatro\" };\nvar indices = new List<int> { 0, 4 };\n\nvar selectedStrings = listaStr.Where(x => indices.Contains(listaStr.IndexOf(x))).ToList();\n\nforeach (var s in selectedStrings)\n{\n Console.WriteLine(s);\n}\n"
},
{
"answer_id": 74513317,
"author": "jptrujillol",
"author_id": 20373528,
"author_profile": "https://Stackoverflow.com/users/20373528",
"pm_score": 0,
"selected": false,
"text": "var listaStr = new List<string> { \"cero\", \"uno\", \"dos\", \"tres\", \"cuatro\" };\nvar indices = new List<int> { 0, 4 };\n\nvar selectedStrings = listaStr.Where((x,i) => indices.Contains(i)).ToList();\n\nforeach (var s in selectedStrings)\n{\n Console.WriteLine(s);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488787/"
] |
74,416,892 | <p>I have a class for a general Shape, my arguments would be 'name', 'sides' and 'length, and then I have a Square class which is an instance of Shape. it is supposed that a square has 4 equals sides, so I am trying to define in my Square class a constructor with the only argument of length, because a rectangle with the same length in the four sides is a Square.</p>
<p>do I already have 2 predefined values, name = square and sides = 4; the only value I have to input for my Square class is my sideLength but for some reason I can't figure out is logging 'undefined;</p>
<p>the prototype of Square would be shape, and is functioning well in creation of objects, however Square class is not getting sidelenght value, although object is being created, with default values (name and sides) but cannot use method calcArea() for lack of sidelength value;</p>
<pre><code>class Shape {
name;
sides;
sideLength;
constructor(_name, _sides, _sideLength){
this.name = _name;
this.sides = _sides;
this.sideLength = _sideLength;
}
calcArea(){
console.log(this.sides*this.sideLength);
}
}
class Square extends Shape {
constructor(_sideLength) {
super(_sideLength);
this.name = 'square';
this.sides = 4;
}
}
const newShape = new Shape('pentagon', 5, 6);
const newSquare = new Square(5);
</code></pre>
| [
{
"answer_id": 74416923,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 2,
"selected": false,
"text": "sideLength"
},
{
"answer_id": 74416924,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "Shape"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18758297/"
] |
74,416,896 | <p>I am trying to shade every other group of visiable cells.</p>
<p>Each row of my data contains information on a given Order and there can be multiple rows for each order, e.g. Order 1 many have 3 rows while order 2 may have 1 row, etc. The data is sorted by Order Number so all rows for a given order are contiguous.</p>
<p>I have shaded each group vis a helper column (AS) containing the following formula: <code>=IF(ROW()=2,TRUE,IF(A2=A1,AS1,NOT(AS1)))</code>
which results in every other Order group being either TRUE or False. Then I use conditional formatting to shade every "TRUE" row.</p>
<p>This works until I begin filtering my data and then I can end up with either two shaded or to unshaded groups next to each other.</p>
<p>I think what I'm looking for is a VBA function that will compare a cell with previous VISIBLE cell and will return TRUE or FALSE if the match or not.</p>
<p>Any help will be much appreciated.</p>
| [
{
"answer_id": 74416923,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 2,
"selected": false,
"text": "sideLength"
},
{
"answer_id": 74416924,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "Shape"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508937/"
] |
74,416,913 | <p>I got a problem with one fromula.</p>
<p>Two sheets:</p>
<ul>
<li><p><a href="https://docs.google.com/spreadsheets/d/1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4/edit#gid=0" rel="nofollow noreferrer">1st Sheet</a></p>
</li>
<li><p><a href="https://docs.google.com/spreadsheets/d/1QGnFhtWaMUhvvFJFOXzX8UpzgRfkFLbF05F_tbWDrNU/edit#gid=0" rel="nofollow noreferrer">2nd Sheet</a></p>
</li>
</ul>
<p>Look at formula on 2nd sheet B2</p>
<pre><code>=IFERROR(INDEX(Importrange("1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4","Sheet1!A:A"),
MATCH($A2,Importrange("1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4","Sheet1!B:B"), 0)), "Not ordered")
</code></pre>
<p>It is matching my status from 1st spreadsheet but only from B column. My question is how to add C column as well (add another match criteria). I want to have B and C together. Is it possible?</p>
<p>Thanks!</p>
<p>I've tried something like this but it is not working :</p>
<pre><code>=INDEX("1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4","Sheet1!A:A"), MATCH($A2,Importrange("1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4","Sheet1!B:B"),
MATCH($A2,Importrange("1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4","Sheet1!C:C"), 0))
</code></pre>
| [
{
"answer_id": 74417026,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": true,
"text": "=IFERROR(INDEX(Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!A:A\"),MATCH($A2,Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!B:B\"), 0)), IFERROR(INDEX(Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!A:A\"), MATCH($A2,Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!C:C\"), 0)), \"Not ordered\"))\n"
},
{
"answer_id": 74417049,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "OR"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19611595/"
] |
74,416,915 | <p>I am currently learning python and my instructor is telling me to open a text file using the open() meathod. I get the following error each time:</p>
<p><code>FileNotFoundError: [Errno 2] No such file or directory: 'movies.txt'</code></p>
<p>I have tried using online guides but all I could find was for .csv files, whereas I'm trying to open a text file. My complete code is as follows:</p>
<pre><code>with open('movies.txt') as file_object:
contents = file_object.read()
print(contents.strip())
</code></pre>
<p>I've tried writing the file 'movies.txt' in VS code, and in my notepad, and then saving it to the same directory as the code but no use. I have also attempted to use a more exact file source, but still the same error. Sadly, google didn't have too much information for text files so I have to come here. Is there something I have to change in VS settings? I also tried my code in IDLE but not response either.</p>
<p>Thanks,
Stan</p>
| [
{
"answer_id": 74417026,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": true,
"text": "=IFERROR(INDEX(Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!A:A\"),MATCH($A2,Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!B:B\"), 0)), IFERROR(INDEX(Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!A:A\"), MATCH($A2,Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!C:C\"), 0)), \"Not ordered\"))\n"
},
{
"answer_id": 74417049,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "OR"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20432831/"
] |
74,416,925 | <p><strong>PROBLEM STATEMENT:</strong></p>
<p>I'm trying to join multiple pandas data frame columns, based on row index, to a single column already in the data frame. Issues seem to happen when the data in a column is read in as np.nan.</p>
<p><strong>EXAMPLE:</strong></p>
<p><strong>Original Data frame</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>time</th>
<th>msg</th>
<th>d0</th>
<th>d1</th>
<th>d2</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>msg0</td>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>1</td>
<td>msg1</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
<tr>
<td>2</td>
<td>msg0</td>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>3</td>
<td>msg2</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p><strong>What I want, if I were to filter for msg0 and msg2</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>time</th>
<th>msg</th>
<th>d0</th>
<th>d1</th>
<th>d2</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>msg0</td>
<td>abc</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>1</td>
<td>msg1</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
<tr>
<td>2</td>
<td>msg0</td>
<td>abc</td>
<td>NaN</td>
<td>Nan</td>
</tr>
<tr>
<td>3</td>
<td>msg2</td>
<td>123</td>
<td>NaN</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
<p><strong>MY ATTEMPT:</strong></p>
<pre><code>df = pd.DataFrame({'time': ['0', '1', '2', '3'],
'msg': ['msg0', 'msg1', 'msg0', 'msg2'],
'd0': ['a', 'x', 'a', '1'],
'd1': ['b', 'x', 'b', '2'],
'd2': ['c', 'x', np.nan, '3']})
mask = df.index[((df['msg'] == "msg0") |
(df['msg'] == "msg1") |
(df['msg'] == "msg3"))].tolist()
# Is there a better way to combine all columns after a certian point?
# This works fine here but has issues when importing large data sets.
# the 'd0' will be set to NaN too, I think this is due to np.nan
# being set to some columns values when imported.
df.loc[mask, 'd0'] = df['d0'] + df['d1'] + df['d2']
df.iloc[mask, 3:] = "NaN"
</code></pre>
| [
{
"answer_id": 74417026,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": true,
"text": "=IFERROR(INDEX(Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!A:A\"),MATCH($A2,Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!B:B\"), 0)), IFERROR(INDEX(Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!A:A\"), MATCH($A2,Importrange(\"1sj7FlrO5ZbHkIUwtpkJdU3tokEBwEXRvyIpi6eVHig4\",\"Sheet1!C:C\"), 0)), \"Not ordered\"))\n"
},
{
"answer_id": 74417049,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "OR"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10097026/"
] |
74,416,981 | <p>When I try to build for production, this error comes up. I'm using React Native Firebase. This error happens on android.</p>
<p>Here is the error</p>
<pre><code>* What went wrong:
Execution failed for task ':react-native-firebase_app:generateReleaseRFile'.
> Could not resolve all files for configuration ':react-native-firebase_app:releaseCompileClasspath'.
> Failed to transform react-native-0.71.0-rc.0-release.aar (com.facebook.react:react-native:0.71.0-rc.0) to match attributes {artifactType=android-symbol-with-package-name, com.android.build.api.attributes.BuildTypeAttr=release, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-api}.
> Could not find react-native-0.71.0-rc.0-release.aar (com.facebook.react:react-native:0.71.0-rc.0).
Searched in the following locations:
https://repo.maven.apache.org/maven2/com/facebook/react/react-native/0.71.0-rc.0/react-native-0.71.0-rc.0-release.aar
</code></pre>
<p>Here are my packages</p>
<pre><code>[tag: "@react-native-async-storage/async-storage": "^1.17.10",
"@react-native-firebase/analytics": "^16.4.3",
"@react-native-firebase/app": "^16.4.3",
"@react-navigation/bottom-tabs": "^6.4.0",
"@react-navigation/native": "^6.0.13",
"@react-navigation/native-stack": "^6.9.1",
"@rneui/base": "^4.0.0-rc.7",
"@rneui/themed": "^4.0.0-rc.7",
"meilisearch": "^0.29.1",
"native-base": "^3.4.21",
"picomatch": "^2.3.1",
"react": "18.1.0",
"react-native": "0.70.3",
"react-native-firebase": "^5.6.0",
"react-native-google-mobile-ads": "^8.2.1",
"react-native-navigation-bar-color": "^2.0.1",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.18.2",
"react-native-svg": "^13.5.0",
"react-native-vector-icons": "^9.2.0"]
</code></pre>
<p>If you can help, thanks!</p>
<p>I have tried everything I could find online =(</p>
<p>I have also tried <code>npx jetify</code></p>
| [
{
"answer_id": 74432935,
"author": "karim elsaidy",
"author_id": 8553678,
"author_profile": "https://Stackoverflow.com/users/8553678",
"pm_score": 0,
"selected": false,
"text": " \"react-native\": \"0.70.5\"\n"
},
{
"answer_id": 74470449,
"author": "Pranavan",
"author_id": 13606876,
"author_profile": "https://Stackoverflow.com/users/13606876",
"pm_score": 3,
"selected": false,
"text": "allprojects {\n repositories {\n google()\n\n exclusiveContent {\n filter {\n includeGroup \"com.facebook.react\"\n }\n forRepository {\n maven {\n url \"$rootDir/../node_modules/react-native/android\"\n }\n }\n }\n \n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74416981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19354777/"
] |
74,417,007 | <p>I just realized that Git is ignoring whitespaces during merge by default. However, I would like that Git would consider whitespace during merge. Is there someone that knows how can I configure it?</p>
<p>I tried to install older versions, but I could not find. The steps to install older version on Ubuntu would be nice.</p>
| [
{
"answer_id": 74417835,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "-Xignore-all-space"
},
{
"answer_id": 74423427,
"author": "GLEIPH GHIOTTO LIMA DE MENEZES",
"author_id": 20488885,
"author_profile": "https://Stackoverflow.com/users/20488885",
"pm_score": 0,
"selected": false,
"text": " selfconfig.setEnabled(true);\n }\n\n<<<<<<< HEAD\n private void performPropertyMapping() {\n Configuration config = Configuration.getInstance();\n config.getSource().properties.clear();\n config.getTarget().properties.clear();\n PropertyMapper propMapper = new PropertyMapper();\n String classSource = config.getSource().getClassOfendpoint();\n String classTarget = config.getTarget().getClassOfendpoint();\n if(classSource != null && classTarget != null) {\n showErrorMessage(\"Getting property mapping...\");\n propMapping = propMapper.getPropertyMapping(config.getSource().endpoint,\n config.getTarget().endpoint, classSource, classTarget);\n for(String s : propMapping.map.keySet())\n for(Entry<String, Double> e : propMapping.map.get(s).entrySet()) {\n System.out.println(s + \" - \" + e.getKey());\n String s_abr=PrefixHelper.abbreviate(s);\n sourceProps.add(s_abr);\n config.getSource().properties.add(s_abr);\n config.getSource().prefixes.put(PrefixHelper.getPrefixFromURI(s_abr), PrefixHelper.getURI(PrefixHelper.getPrefixFromURI(s_abr)));\n System.out.println(\"Adding source property: \"+s_abr+\"::::\"+PrefixHelper.getPrefixFromURI(s_abr)+\" -- \"+PrefixHelper.getURI(PrefixHelper.getPrefixFromURI(s_abr)));\n targetProps.add(PrefixHelper.abbreviate(e.getKey()));\n String t_abr=PrefixHelper.abbreviate(e.getKey());\n config.getTarget().properties.add(t_abr);\n config.getTarget().prefixes.put(PrefixHelper.getPrefixFromURI(t_abr), PrefixHelper.getURI(PrefixHelper.getPrefixFromURI(t_abr)));\n System.out.println(\"Adding target property: \"+t_abr+\"::::\"+PrefixHelper.getPrefixFromURI(t_abr)+\" -- \"+PrefixHelper.getURI(PrefixHelper.getPrefixFromURI(t_abr)));\n=======\n\n /**\n * Little helper function to retrieve classes out of restrictions of the LIMES SPEC. Whereas, a\n * class is in a restriction of the format \"?var rdf:type <class>\".\n * @param ep\n * @return\n */\n private String getClassOfEndpoint(KBInfo ep) {\n for(String rest : ep.restrictions) {\n if(rest.matches(\".* rdf:type .*\"))\n return rest.substring(rest.indexOf(\"rdf:type\")+8).replaceAll(\"<\", \"\").replaceAll(\">\", \"\").trim();\n }\n return null;\n }\n\n private void showErrorMessage(String message) {\n layout.setComponentError(new UserError(message));\n }\n\n public boolean isValid() {\n manualMetricForm.validate();\n if(manualMetricForm.isValid()) {\n Configuration.getInstance().setMetricExpression(manualMetricForm.metricTextField.getValue().toString());\n Configuration.getInstance().setAcceptanceThreshold(Double.parseDouble(manualMetricForm.thresholdTextField.getValue().toString()));\n return true;\n } else {\n manualMetricForm.setComponentError(new UserError(\"Please insert something...\"));\n }\n return false;\n }\n\n public class SelfConfigClickListener implements Button.ClickListener {\n Layout l;\n public SelfConfigClickListener(Layout l) {\n this.l=l;\n }\n @Override\n public void buttonClick(ClickEvent event) {\n // add all properties\n for(String s : sourceProps) {\n Configuration.getInstance().getSource().properties.add(s);\n Configuration.getInstance().getSource().prefixes.put(PrefixHelper.getPrefixFromURI(s), PrefixHelper.getURI(PrefixHelper.getPrefixFromURI(s)));\n Configuration.getInstance().getSource().functions.put(s, \"\");\n }\n for(String s : targetProps) {\n Configuration.getInstance().getTarget().properties.add(s);\n Configuration.getInstance().getTarget().prefixes.put(PrefixHelper.getPrefixFromURI(s), PrefixHelper.getURI(PrefixHelper.getPrefixFromURI(s)));\n Configuration.getInstance().getTarget().functions.put(s, \"\");\n }\n // run selfconfig\n l.removeAllComponents();\n Refresher refresher = new Refresher();\n SelfConfigRefreshListener listener = new SelfConfigRefreshListener();\n refresher.addListener(listener);\n addComponent(refresher);\n\n final ProgressIndicator indicator = new ProgressIndicator();\n indicator.setCaption(\"Progress\");\n l.addComponent(indicator);\n indicator.setImmediate(true);\n\n final Panel stepPanel = new Panel(\"Starting self configuration\");\n l.addComponent(stepPanel);\n\n new Thread() {\n public void run() {\n\n float steps = 5f;\n indicator.setValue(new Float(1f/steps));\n indicator.requestRepaint();\n stepPanel.setCaption(\"Getting source cache...\");\n HybridCache sourceCache = HybridCache.getData(Configuration.getInstance().getSource());\n indicator.setValue(new Float(2f/steps));\n indicator.requestRepaint();\n stepPanel.setCaption(\"Getting target cache...\");\n HybridCache targetCache = HybridCache.getData(Configuration.getInstance().getTarget());\n indicator.setValue(new Float(3f/steps));\n stepPanel.setCaption(\"Performing self configuration...\");\n MeshBasedSelfConfigurator bsc = new MeshBasedSelfConfigurator(sourceCache, targetCache, 0.6, 0.5);\n List<SimpleClassifier> cp = bsc.getBestInitialClassifiers(); \n indicator.setValue(new Float(4f/steps));\n stepPanel.setCaption(\"Performed self configuration:\");\n for(SimpleClassifier cl : cp) {\n System.out.println(cl);\n>>>>>>> bbb3f6b\n }\n\n }\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20488885/"
] |
74,417,019 | <p>I would like to chain strings together. This is my code:</p>
<pre><code>let mut string_to_send = String::new();
string_to_send.push_str("<hi,");
string_to_send.push_str(&some_int.to_string());
string_to_send.push_str(",");
string_to_send.push_str(&another_int.to_string());
string_to_send.push_str(">");
</code></pre>
<p>Something tells me there is a nicer way to do it, but I just don't see it.</p>
| [
{
"answer_id": 74417036,
"author": "Lee",
"author_id": 152602,
"author_profile": "https://Stackoverflow.com/users/152602",
"pm_score": 4,
"selected": true,
"text": "format!"
},
{
"answer_id": 74417428,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 0,
"selected": false,
"text": "+"
},
{
"answer_id": 74418070,
"author": "pigeonhands",
"author_id": 2691759,
"author_profile": "https://Stackoverflow.com/users/2691759",
"pm_score": 1,
"selected": false,
"text": "let string_to_send = [\n \"<hi\",\n &10.to_string(),\n \",\",\n &11.to_string(),\n \">\"\n].concat();\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13419097/"
] |
74,417,078 | <p>I'm trying to return the teacher's name based on what classroom the students name is in.
teacher[0] is responsible for rooms[0] and teacher[1] is responsible for rooms[1] and so on.</p>
<pre><code>let teachers = ["Arrington", "Kincart", "Alberts", "Pickett"]
</code></pre>
<pre><code>let rooms = [
["Andy", "Rodolfo", "Lynn", "Talia"],
["Al", "Ross", "Jorge", "Dante"],
["Nick", "Kim", "Jasmine", "Dorothy"],
["Adam", "Grayson", "Aliyah", "Alexa"]
]
</code></pre>
<pre><code>let whichTeacher = (student) => {
return rooms.findIndex(row => row.indexOf(student) !== - 1)
}
console.log(`The teacher who has Jorge is ${whichTeacher("Jorge")}.`)
console.log(`The teacher who has Alexa is ${whichTeacher("Alexa")}.`)
</code></pre>
<p>the current output is</p>
<pre><code>The teacher who has Jorge is 1.
The teacher who has Alexa is 3.
</code></pre>
<p>so I know im close but I cant figure out how to output the teachers name instead of its index number.</p>
| [
{
"answer_id": 74417095,
"author": "LeoDog896",
"author_id": 7589775,
"author_profile": "https://Stackoverflow.com/users/7589775",
"pm_score": 3,
"selected": true,
"text": "let teachers = [\"Arrington\", \"Kincart\", \"Alberts\", \"Pickett\"]\n\n\nlet rooms = [\n [\"Andy\", \"Rodolfo\", \"Lynn\", \"Talia\"],\n [\"Al\", \"Ross\", \"Jorge\", \"Dante\"],\n [\"Nick\", \"Kim\", \"Jasmine\", \"Dorothy\"],\n [\"Adam\", \"Grayson\", \"Aliyah\", \"Alexa\"]\n]\n\nlet whichTeacher = (student) => {\n return teachers[rooms.findIndex(row => row.indexOf(student) !== - 1)]\n // ^ use the found index to index the teachers array\n}\n\n\nconsole.log(`The teacher who has Jorge is ${whichTeacher(\"Jorge\")}.`)\nconsole.log(`The teacher who has Alexa is ${whichTeacher(\"Alexa\")}.`)"
},
{
"answer_id": 74417113,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "teachers"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,417,085 | <p>I'm looking for some guidance here. I have a project and I'm looking to sort a char vector inside a struct.</p>
<p>I have the next struct and the main:</p>
<pre class="lang-cpp prettyprint-override"><code>struct employee
{
long Id;
char name[20]
};
int main ()
{
employee data[5]
for(int i=0; i<5; i++)
{
for(int x=i+1; x<5; x++)
{
if(data[i].name[0]> data[x].name[0])
{
data[i].Id = data[x].Id;
data[i].name = data[x].name;
}
}
}
}
</code></pre>
<p>I'm stuck in this part. What I am trying to do is to basically sort the vector alphabetically by the name. For example: <code>brayan</code> should be first and <code>carlos</code> next.</p>
<p>It should look like this:</p>
<pre><code>Employee #1
Id: 123
Name: brayan
Employee #2
Id: 121
Name: Carlos
</code></pre>
<p>I would appreciate any kind of help.
The only requirement for this program is not to use std::string.</p>
| [
{
"answer_id": 74417236,
"author": "AdamSE",
"author_id": 20489090,
"author_profile": "https://Stackoverflow.com/users/20489090",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <vector>\n#include <algorithm>\n\nstruct Test\n{\n int id;\n std::string name;\n};\n\nint main()\n{\n std::vector<Test> tab(5);\n std::sort(std::begin(tab), std::end(tab), []\n (const Test& lhs, const Test& rhs)\n {return lhs.name > rhs.name;});\n}\n"
},
{
"answer_id": 74417292,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 2,
"selected": true,
"text": "std::sort"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16079517/"
] |
74,417,087 | <p>This has been giving me a headache, im just trying to put a Textfield on the bottom of my screen. I have the following code, trying to wrap it in a Positioned:</p>
<pre><code>return Scaffold(
//set a textField to add a reply
appBar: TopAppBar(title: 'bruh'),
body: SingleChildScrollView(
controller: _scrollController,
child: Column(
children: [
FocalWaveTile(
wave: widget.waveTile.wave,
user: profileState.user,
poster: widget.waveTile.poster,
),
ListView.builder(
shrinkWrap: true,
itemCount: waves.length,
itemBuilder: (BuildContext context, int index) {
},
),
//poisition on the bottom
Positioned(
bottom: MediaQuery.of(context).viewInsets.bottom,
child: Container(
height: 50,
width: MediaQuery.of(context).size.width,
color: Colors.white,
child: Row(
children: [
Expanded(
child: Container(
margin: EdgeInsets.only(left: 10),
child: TextField(
decoration: InputDecoration(
hintText: 'Reply to this wave'),
onChanged: (value) {
if (value.length > 0) {
setState(() {
isTyping = true;
});
} else {
setState(() {
isTyping = false;
});
}
},
),
),
),
],
),
),
)
],
),
));
</code></pre>
<p>And it looks like this:</p>
<p><a href="https://i.stack.imgur.com/FjXxE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FjXxE.png" alt="enter image description here" /></a></p>
<p>Any idea what im doing wrong? Ive tried a few things like a bottomnavbar and adding a spacer, but neither of these work in the way i would like them too. Thanks!</p>
| [
{
"answer_id": 74417352,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": " return Scaffold(\n //set a textField to add a reply\n\n appBar: TopAppBar(title: 'bruh'),\n body: Stack(\n children: [\n SingleChildScrollView(\n controller: _scrollController,\n child: Column(\n children: [\n FocalWaveTile(\n wave: widget.waveTile.wave,\n user: profileState.user,\n poster: widget.waveTile.poster,\n ),\n ListView.builder(\n shrinkWrap: true,\n itemCount: waves.length,\n itemBuilder: (BuildContext context, int index) {},\n ),\n //poisition on the bottom\n ],\n ),\n ),\n Positioned(\n bottom: MediaQuery.of(context).viewInsets.bottom,\n child: Container(\n height: 50,\n width: MediaQuery.of(context).size.width,\n color: Colors.white,\n child: Row(\n children: [\n Expanded(\n child: Container(\n margin: EdgeInsets.only(left: 10),\n child: TextField(\n decoration:\n InputDecoration(hintText: 'Reply to this wave'),\n onChanged: (value) {\n if (value.length > 0) {\n setState(() {\n isTyping = true;\n });\n } else {\n setState(() {\n isTyping = false;\n });\n }\n },\n ),\n ),\n ),\n ],\n ),\n ),\n )\n ],\n ),\n);\n"
},
{
"answer_id": 74418715,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "bottomNavigationBar"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19097292/"
] |
74,417,135 | <p>Write a function that changes letters given in an array to '*' in a given string.</p>
<p>'Irisk' ['i','k'] -> *r * s *</p>
<p>I have tried using:</p>
<pre><code>def filter(word, lett):
new_word = ''
for c in word:
if c == lett:
new_word += '*'
else:
new_word += c
return new_word
</code></pre>
| [
{
"answer_id": 74417167,
"author": "Dodo",
"author_id": 20488733,
"author_profile": "https://Stackoverflow.com/users/20488733",
"pm_score": 0,
"selected": false,
"text": "def filter(word, lett):\n new_word = \"\"\n for c in word:\n if c in lett:\n new_word += \"*\"\n else:\n new_word += c\n return new_word\n"
},
{
"answer_id": 74417169,
"author": "Daniel Sepulveda",
"author_id": 20450970,
"author_profile": "https://Stackoverflow.com/users/20450970",
"pm_score": 0,
"selected": false,
"text": "String.replace"
},
{
"answer_id": 74417234,
"author": "J4SON",
"author_id": 10485181,
"author_profile": "https://Stackoverflow.com/users/10485181",
"pm_score": 0,
"selected": false,
"text": " def filter(s: str, c: list) -> str:\n n = s\n for i in c:\n n = n.replace(i, '*')\n\n return n\n"
},
{
"answer_id": 74417240,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 1,
"selected": false,
"text": "my_string = 'Irisk'\nmy_list = ['i', 'k']\nnew_string = ''.join(\"*\" if (c.lower() in my_list) else c for c in my_string)\n"
},
{
"answer_id": 74417245,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 0,
"selected": false,
"text": "word"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18702533/"
] |
74,417,151 | <p>I have a bitmap image, myImage.png say. The png has been saved with pixel format Format8bppIndexed, which is something I specifically chose to do. But when I open it in C# using new Bitmap("myImage.png"), I find that it is provided to me as a bitmap in format Format32bppRgb. This isn't what I want, which is why I didn't save it in that format.</p>
<p>I've written code specifically to do turtle-graphics manipulation of a 256-colour indexed raster image; I don't want to rewrite that code to do it with a 32bpp image; I don't see why I should have to. How do I force C# to open my image and just give it to me as it comes, without converting it to a different pixel format? I need an overload of the Bitmap constructor that tells it, "don't try to be helpful, I know what I'm doing". But I can't see one.</p>
<p>If I load an image that's in Format1bppIndexed, C# doesn't do this - I get the binary PNG just as it is, not converted at all.</p>
| [
{
"answer_id": 74417167,
"author": "Dodo",
"author_id": 20488733,
"author_profile": "https://Stackoverflow.com/users/20488733",
"pm_score": 0,
"selected": false,
"text": "def filter(word, lett):\n new_word = \"\"\n for c in word:\n if c in lett:\n new_word += \"*\"\n else:\n new_word += c\n return new_word\n"
},
{
"answer_id": 74417169,
"author": "Daniel Sepulveda",
"author_id": 20450970,
"author_profile": "https://Stackoverflow.com/users/20450970",
"pm_score": 0,
"selected": false,
"text": "String.replace"
},
{
"answer_id": 74417234,
"author": "J4SON",
"author_id": 10485181,
"author_profile": "https://Stackoverflow.com/users/10485181",
"pm_score": 0,
"selected": false,
"text": " def filter(s: str, c: list) -> str:\n n = s\n for i in c:\n n = n.replace(i, '*')\n\n return n\n"
},
{
"answer_id": 74417240,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 1,
"selected": false,
"text": "my_string = 'Irisk'\nmy_list = ['i', 'k']\nnew_string = ''.join(\"*\" if (c.lower() in my_list) else c for c in my_string)\n"
},
{
"answer_id": 74417245,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 0,
"selected": false,
"text": "word"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340819/"
] |
74,417,170 | <p>This answer <a href="https://emacs.stackexchange.com/questions/28981/finding-files-by-names">https://emacs.stackexchange.com/questions/28981/finding-files-by-names</a> mentions</p>
<p>"If you are running Dired with a 'ls' implemented in elisp, 'ls-lisp' or 'eshell-ls', then you can recursively list all the files matching a wildcard".</p>
<p>But I do not know how to achieve that.</p>
<p>Is there a way (customization or setting in init.el) to ask dired to use eshell commands where available?</p>
| [
{
"answer_id": 74417167,
"author": "Dodo",
"author_id": 20488733,
"author_profile": "https://Stackoverflow.com/users/20488733",
"pm_score": 0,
"selected": false,
"text": "def filter(word, lett):\n new_word = \"\"\n for c in word:\n if c in lett:\n new_word += \"*\"\n else:\n new_word += c\n return new_word\n"
},
{
"answer_id": 74417169,
"author": "Daniel Sepulveda",
"author_id": 20450970,
"author_profile": "https://Stackoverflow.com/users/20450970",
"pm_score": 0,
"selected": false,
"text": "String.replace"
},
{
"answer_id": 74417234,
"author": "J4SON",
"author_id": 10485181,
"author_profile": "https://Stackoverflow.com/users/10485181",
"pm_score": 0,
"selected": false,
"text": " def filter(s: str, c: list) -> str:\n n = s\n for i in c:\n n = n.replace(i, '*')\n\n return n\n"
},
{
"answer_id": 74417240,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 1,
"selected": false,
"text": "my_string = 'Irisk'\nmy_list = ['i', 'k']\nnew_string = ''.join(\"*\" if (c.lower() in my_list) else c for c in my_string)\n"
},
{
"answer_id": 74417245,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 0,
"selected": false,
"text": "word"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2767348/"
] |
74,417,195 | <p>I have a section of code that used to utilize Optional<Department>, but due to some errors I worked out I am now converting it to List<Department>. Obviously this means I now have to change the return types and other method calls. Here are my questions:</p>
<ul>
<li><p>I changed my returns to "new LinkedList<>()" (indicated in the code below) but is that correct?</p>
</li>
<li><p>There is a red error under ".isPresent" (indicated in the code below) with error message "The method isPresent() is undefined for the type List<Department>". What should I be changing that to?</p>
</li>
</ul>
<p>Below is the updated code with comments indicating where errors are now occurring. Any help and explanations would be GREATLY appreciated!</p>
<pre><code>public List<Department> delete(String department_ID) {
if ((department_ID == null) || (department_ID.isEmpty())) {
return new LinkedList<>(); //<<<<<<<<<<<<<<< used to be "return Optional.empty();"
}
List<Department> existing = get(department_ID);
if (existing.isPresent()) { //<<<<<<<<<<< red error under ".isPresent()"
String sql = "DELETE employee.*, department.* " + "FROM employee, department "
+ "WHERE employee.department_ID = :department_ID AND department.department_ID = :department_ID;";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("department_ID", department_ID);
int rows = jdbcTemplate.update(sql, parameters);
if (rows > 0) {
return existing;
}
}
return new LinkedList<>(); //<<<<<<<<<<<<<<< used to be "return Optional.empty();"
}
</code></pre>
<ul>
<li>I changed my returns to "new LinkedList<>()" (indicated in the code below) but is that correct?</li>
<li>I have googled the error message for my ".isPresent" error and cant find any explanations that fit</li>
</ul>
| [
{
"answer_id": 74417235,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 0,
"selected": false,
"text": "new LinkedList<>()"
},
{
"answer_id": 74417258,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 1,
"selected": false,
"text": "if (existing.isPresent()) { …\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489017/"
] |
74,417,204 | <p>Is there a way in notepad ++ to delete all rows which contain 2 or more @ characters on the same row? I have a big list of email addresses. Some email addresses are incorrect because there are multiple @ characters in it. I want to delete these lines from the file.</p>
<p>If not possible, is this maybe possible in another app?</p>
<p>Thanks you</p>
| [
{
"answer_id": 74417235,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 0,
"selected": false,
"text": "new LinkedList<>()"
},
{
"answer_id": 74417258,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 1,
"selected": false,
"text": "if (existing.isPresent()) { …\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5953578/"
] |
74,417,212 | <p>I have a list of lists <code>property_lists</code> which is structured as follows:</p>
<pre><code>property_lists = [['Semi-Detached', '|', '', '2', '|', '', '2'], ['Detached', '|', '', '5', '|', '', '3'], ['Detached', '|', '', '5', '|', '', '5']]
</code></pre>
<p>and so on.</p>
<p>I am attempting list indexing in order to put all the elements into separate lists of their own.</p>
<p>For example:</p>
<pre><code>typeOfProperty = [item[0] for item in property_lists]
</code></pre>
<p>returns</p>
<pre><code>['Semi-Detached', 'Detached', 'Detached']
</code></pre>
<p>However, the below results in an <code>index list out of range</code> error:</p>
<pre><code>bedrooms = [item[3] for item in property_lists]
</code></pre>
<p>But I don't understand why as each 'sub' list has 7 elements?</p>
<p>To be clear, i am trying to output:</p>
<pre><code>['2', '5', '5']
</code></pre>
| [
{
"answer_id": 74417235,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 0,
"selected": false,
"text": "new LinkedList<>()"
},
{
"answer_id": 74417258,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 1,
"selected": false,
"text": "if (existing.isPresent()) { …\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6562240/"
] |
74,417,215 | <p>How to get the rows of the longest consecutive same value?</p>
<p>Table <code>Learning</code>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>rowID</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>4</td>
<td>0</td>
</tr>
<tr>
<td>5</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>1</td>
</tr>
<tr>
<td>7</td>
<td>0</td>
</tr>
<tr>
<td>8</td>
<td>1</td>
</tr>
<tr>
<td>9</td>
<td>1</td>
</tr>
<tr>
<td>10</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Longest consecutive value is 1 (<code>rowID</code> 8-10 as <code>rowID</code> 1-2 is 2 and <code>rowID</code> 6-6 is 1). How to query to get the actual rows of consecutive values (not just <code>rowStart</code> and <code>rowEnd</code> values) like :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>rowID</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>8</td>
<td>1</td>
</tr>
<tr>
<td>9</td>
<td>1</td>
</tr>
<tr>
<td>10</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>And for longest consecutive values of <em>both</em> 1 and 0?</p>
<p><a href="https://www.db-fiddle.com/f/kzTjXmHMdndrnytP7SstK2/0" rel="nofollow noreferrer">DB Fiddle</a></p>
| [
{
"answer_id": 74417285,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "WITH cte AS (\n SELECT *, ROW_NUMBER() OVER (ORDER BY rowID) rn1,\n ROW_NUMBER() OVER (PARTITION BY values ORDER BY rowID) rn2\n FROM yourTable\n),\ncte2 AS (\n SELECT *,\n MIN(rowID) OVER (PARTITION BY values, rn1 - rn2) AS minRowID,\n MAX(rowID) OVER (PARTITION BY values, rn1 - rn2) AS maxRowID\n FROM cte1\n),\ncte3 AS (\n SELECT *, RANK() OVER (PARTITION BY values ORDER BY maxRowID - minRowID DESC) rnk\n FROM cte2\n)\n\nSELECT rowID, values\nFROM cte3\nWHERE rnk = 1\nORDER BY values, rowID;\n"
},
{
"answer_id": 74417338,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select min(valueid) grp_start, max(valueid) grp_end \nfrom (select t.*, sum(value = 0) over(order by valueid) grp from testing t) t\nwhere value = 1\ngroup by grp\norder by count(*) desc limit 1\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20381410/"
] |
74,417,268 | <p>I'm trying to create a pascal's triangle generator, but for some reason it's not giving me the correct output. I should get:</p>
<pre><code>[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
</code></pre>
<p>But instead I'm getting:</p>
<pre><code>[1, 1]
[1, 2, 1]
[1, 3, 4, 1]
[1, 4, 8, 9, 1]
</code></pre>
<p>Here's the code:</p>
<pre class="lang-py prettyprint-override"><code>length = 4
lst = [1]
for i in range(length):
for j in range(i):
lst[j+1] = temp[j] +temp[j+1]
lst.append(1)
temp = lst
print(lst)
</code></pre>
<p>I've been looking at it for hours and I couldn't spot anything wrong with it. I even wrote down the first couple of iterations on paper and it all seems just fine. But somehow it's still not working? It might be me being blind again but I've really got no clue.</p>
<p>I'm so confused, why is it adding the entries from the current list when I created a temporary list to get values from?</p>
| [
{
"answer_id": 74417285,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "WITH cte AS (\n SELECT *, ROW_NUMBER() OVER (ORDER BY rowID) rn1,\n ROW_NUMBER() OVER (PARTITION BY values ORDER BY rowID) rn2\n FROM yourTable\n),\ncte2 AS (\n SELECT *,\n MIN(rowID) OVER (PARTITION BY values, rn1 - rn2) AS minRowID,\n MAX(rowID) OVER (PARTITION BY values, rn1 - rn2) AS maxRowID\n FROM cte1\n),\ncte3 AS (\n SELECT *, RANK() OVER (PARTITION BY values ORDER BY maxRowID - minRowID DESC) rnk\n FROM cte2\n)\n\nSELECT rowID, values\nFROM cte3\nWHERE rnk = 1\nORDER BY values, rowID;\n"
},
{
"answer_id": 74417338,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select min(valueid) grp_start, max(valueid) grp_end \nfrom (select t.*, sum(value = 0) over(order by valueid) grp from testing t) t\nwhere value = 1\ngroup by grp\norder by count(*) desc limit 1\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15323416/"
] |
74,417,270 | <p>I have a laravelapi that fetches posts from the database and another one that fetches upvotes.
Now I want to display posts on my react component and show the length of upvotes for every particular post.</p>
<p>Here is how I have tried it out. But im getting the value as undefined on the console. Please help. Here is my code</p>
<pre class="lang-javascript prettyprint-override"><code>import React, { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom";
import Menubar from "../../components/menubar/Menubar"
import PostSkeleton from '../../components/skeleton/PostSkeleton';
import PostWidget from '../../components/widgets/PostWidget';
import axios from 'axios';
function Community() {
let navigate = useNavigate();
const [posts, setPosts] = useState([]);
const [upvotes, setUpvotes] = useState([]);
const [limit, setLimit] = useState(4);
const [isLoading, setIsLoading] = useState(true);
const [loading, setLoading] = useState(false);
function handleClick() {
navigate("/add-post");
}
useEffect(() => {
let isMounted = true;
axios.get(`/api/posts?page=1&limit=` + limit).then(res => {
if (isMounted) {
if (res.data.status === 200) {
setPosts(res.data.posts);
setIsLoading(false);
setLoading(false);
}
}
});
return () => {
isMounted = false
};
}, [limit]);
const loadMore = () => {
setLimit(limit + 4)
setLoading(true);
}
useEffect(() => {
let isMounted = true;
axios.get(`/api/upvotes`).then(res => {
if (isMounted) {
if (res.data.status === 200) {
setUpvotes(res.data.upvotes);
}
}
});
return () => {
isMounted = false
};
}, []);
return (
<div>
<Menubar />
<div className="appHeader bg-primary text-light">
<div className="left">
<a onClick={() => navigate(-1)} className="headerButton goBack">
<i className="fi fi-rr-angle-left"></i> </a>
</div>
<div className="pageTitle">Community</div>
<div className="right">
<a href="#" className="headerButton">
<i className="fi fi-rr-paper-plane"></i> </a>
</div>
</div>
<div id="appCapsule">
<div className="section">
<div className="post-input mt-3">
<form>
<a href="profile.php" className="btn btn-icon btn-secondary rounded mr-1" >
<img src="assets/img/sample/avatar/avatar4.jpg" alt="avatar" className="avatar imaged rounded" />
</a>
<div className="form-group boxed">
<div className="input-wrapper">
<input type="text" onClick={handleClick} className="form-control" placeholder="Tell the World Something" />
</div>
</div>
</form>
</div>
</div>
<div className="section mt-2 mb-3">
{isLoading && <PostSkeleton cards={4} />}
{posts.map((post) => (<PostWidget post={post} upvotes={upvotes.find(upvotes =>posts.postid === upvotes.post_id)} key={post.postid} />))}
<div className="text-center">
<a onClick={loadMore} className={limit <= posts.length ? 'btn btn-text-primary mr-1' : 'btn btn-text-primary mr-1 disabled'} >{loading ? <><span className="spinner-border spinner-border-sm mr-05" role="status" aria-hidden="true"></span>Loading More</> : <>{limit <= posts.length ? <>Load More <i className="fi fi-rr-angle-small-right"></i></> : 'All Posts Loaded'} </>}</a>
</div>
</div>
</div>
</div>
);
}
export default Community;
</code></pre>
<p>The <code>PostWidget</code> Component</p>
<pre class="lang-javascript prettyprint-override"><code>import React, { useState, useEffect } from 'react';
import { Link } from "react-router-dom";
import { LazyLoadImage } from "react-lazy-load-image-component";
import axios from 'axios';
import toast, { Toaster } from 'react-hot-toast';
const PostWidget = ( {post, upvotes}) => {
console.warn(upvotes && upvotes.length)
const formatDate = (dateString) => {
const options = { year: "numeric", month: "long", day: "numeric" }
return new Date(dateString).toLocaleDateString(undefined, options)
}
return (
<div>
<Toaster />
<div className="comment-block mb-3 pb-1">
<div className="comment-header">
<div className="avatar">
<img src="assets/img/sample/avatar/avatar1.jpg" alt="avatar" className="imaged w32 rounded mr-1" />
</div>
<div className="comment-other">
<h4 className="title">{post.user && post.user.firstname} {post.user && post.user.lastname}</h4>
<span className="time">{formatDate(post.created_at)}</span>
</div>
</div>
<div className="item">
<div className="in">
<div className="post-image mt-1">
<Link to={"/post-details/" + post.postid}>
<LazyLoadImage src={`http://localhost:8000/${post.postimage}`} alt="avatar" className="imaged w-100" />
</Link>
<Link to={"/fruit-details/" + post.fruit.id}>
<div className="chip mt-1 mr-1">
<span className="chip-label">{post.fruit.name}</span>
</div>
</Link>
</div>
<Link to={"/post-details/" + post.postid}>
<div className="text mt-1">
{post.postcontent}
</div>
</Link>
<div className="comment-footer">
<a href="" className="comment-button">
<i className="fi fi-rr-check"></i>
Upvote (5)
</a>
<a href="" className="comment-button">
<i className="fi fi-rr-arrow-down"></i>
Downvote
</a>
<Link to={"/post-details/" + post.postid} className="comment-button" >
<i className="fi fi-rr-comment"></i>
Comment
</Link>
</div>
</div>
</div>
</div>
</div>
);
}
export default PostWidget;
</code></pre>
| [
{
"answer_id": 74417285,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "WITH cte AS (\n SELECT *, ROW_NUMBER() OVER (ORDER BY rowID) rn1,\n ROW_NUMBER() OVER (PARTITION BY values ORDER BY rowID) rn2\n FROM yourTable\n),\ncte2 AS (\n SELECT *,\n MIN(rowID) OVER (PARTITION BY values, rn1 - rn2) AS minRowID,\n MAX(rowID) OVER (PARTITION BY values, rn1 - rn2) AS maxRowID\n FROM cte1\n),\ncte3 AS (\n SELECT *, RANK() OVER (PARTITION BY values ORDER BY maxRowID - minRowID DESC) rnk\n FROM cte2\n)\n\nSELECT rowID, values\nFROM cte3\nWHERE rnk = 1\nORDER BY values, rowID;\n"
},
{
"answer_id": 74417338,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select min(valueid) grp_start, max(valueid) grp_end \nfrom (select t.*, sum(value = 0) over(order by valueid) grp from testing t) t\nwhere value = 1\ngroup by grp\norder by count(*) desc limit 1\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19223350/"
] |
74,417,331 | <p>In Visual Studio 2019 I have two C++ projects contained in the same Solution: <code>ProjectA</code> and <code>ProjectB</code>.</p>
<p>How to define a <code>C/C++ Preprocessor Definition</code> in <code>ProjectB</code> ( let's call it: <code>THE_OTHER_FILE_NAME</code> ), which <strong>is equal to</strong> the string returned by the VS macro <code>$(TargetFileName)</code> in the <code>ProjectA</code> ?</p>
<p><strong>NOTE</strong>: <em>Hardcoding paths in the C/C++ source files is outside the scope of this question.</em></p>
| [
{
"answer_id": 74417636,
"author": "Abdallah",
"author_id": 19486032,
"author_profile": "https://Stackoverflow.com/users/19486032",
"pm_score": -1,
"selected": false,
"text": "#define _CRT_SECURE_NO_WARNINGS\n#include <stdio.h>\n#include <Windows.h>\n#include \"../p2/Header.h\"\nint main(){\n print();\n system(\"PAUSE\");\n}\n"
},
{
"answer_id": 74431020,
"author": "Pavel Stepanek",
"author_id": 20137151,
"author_profile": "https://Stackoverflow.com/users/20137151",
"pm_score": 0,
"selected": false,
"text": "$(TargetFileName)"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20137151/"
] |
74,417,383 | <p>I am trying to make a type guard that narrows the <code>string</code> type but doesn't narrow it all the way to an explicit list of strings.</p>
<p>Here is an example of the type of code I am writing:</p>
<pre class="lang-js prettyprint-override"><code>
type Node = { type: string, content: string };
type Macro extends Node { type: "macro" };
function generateGuard(filter: Set<string>) {
function strGuard(s: any): s is Macro & {content: unknown} {
return typeof s === "object" &&
s.type === "macro" &&
filter.has(s.content);
}
return strGuard;
}
const isMacro = (s: any) => typeof s === "object" &&
s.type === "macro"
const specialMacro = generateGuard(new Set(["x"]));
let xxx: Node = {type: "macro", content: "some string" };
function task1(){
if (isMacro(xxx)) {
if (specialMacro(xxx)) {
// Do something for special `Macro`
xxx;
// ?^ Macro
} else {
// Do something for non-special `Macro`
xxx;
// ?^ never
}
} else {
// code for non-macro `Node`
}
}
function task2(){
if (specialMacro(xxx)) {
// Do something for special `Macro`
xxx;
// ^? Macro
}
}
</code></pre>
<p>The issue is that <code>xxx</code> has type <code>never</code> in the <code>else</code> block. I want it to have some sort of <code>T extends Macro</code> type instead (or a the full <code>Macro</code> type would be fine, it just cannot be <code>never</code>). The <code>& {content: unknown}</code> doesn't narrow the type because <code>{content: string}</code> is already more specific.</p>
<p>Is there some way to type <code>generateGuard</code> such that it narrows <code>{content: string}</code> by some "unknown" amount?</p>
| [
{
"answer_id": 74417466,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "function hasPrefix<P extends string>(str: string, prefix: P): str is `${P}${string}` {\n return typeof str === 'string' && str.startsWith(prefix);\n}\ndeclare const Brand: unique symbol;\ntype Id = string & {[Brand]?: 'id'}\nfunction isId(str: string): str is Id {\n return !!str.match(/^\\w+$/);\n}\n\nlet xxxx = \"some string\" as const;\nif (hasPrefix(xxxx, 'some')) {\n xxxx;\n // ^?\n} else {\n xxxx;\n // ^?\n}\nif (hasPrefix(xxxx, 'soon')) {\n xxxx;\n // ^?\n} else {\n xxxx;\n // ^?\n}\nlet xxxy = \"some string\";\nif (hasPrefix(xxxy, 'wasd')) {\n xxxy;\n // ^?\n} else {\n xxxy;\n // ^?\n}\nif (isId(xxxy)) {\n xxxy;\n // ^?\n} else {\n xxxy;\n // ^?\n}\n"
},
{
"answer_id": 74418101,
"author": "Sean Vieira",
"author_id": 135978,
"author_profile": "https://Stackoverflow.com/users/135978",
"pm_score": 2,
"selected": false,
"text": "content"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016529/"
] |
74,417,408 | <p>I am using os.system("python game2.py") to run different parts of my code.</p>
<p>Every time I try this it gives me an import error for example "no module named pygame" even though when I game2 itself, it works fine.</p>
<p>What can I do?</p>
| [
{
"answer_id": 74417466,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "function hasPrefix<P extends string>(str: string, prefix: P): str is `${P}${string}` {\n return typeof str === 'string' && str.startsWith(prefix);\n}\ndeclare const Brand: unique symbol;\ntype Id = string & {[Brand]?: 'id'}\nfunction isId(str: string): str is Id {\n return !!str.match(/^\\w+$/);\n}\n\nlet xxxx = \"some string\" as const;\nif (hasPrefix(xxxx, 'some')) {\n xxxx;\n // ^?\n} else {\n xxxx;\n // ^?\n}\nif (hasPrefix(xxxx, 'soon')) {\n xxxx;\n // ^?\n} else {\n xxxx;\n // ^?\n}\nlet xxxy = \"some string\";\nif (hasPrefix(xxxy, 'wasd')) {\n xxxy;\n // ^?\n} else {\n xxxy;\n // ^?\n}\nif (isId(xxxy)) {\n xxxy;\n // ^?\n} else {\n xxxy;\n // ^?\n}\n"
},
{
"answer_id": 74418101,
"author": "Sean Vieira",
"author_id": 135978,
"author_profile": "https://Stackoverflow.com/users/135978",
"pm_score": 2,
"selected": false,
"text": "content"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74417408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489210/"
] |
74,417,476 | <p>The goal is to get all the news articles from this page by clicking the load more button programmatically: <a href="https://money.tmx.com/en/quote/AMK/news" rel="nofollow noreferrer">https://money.tmx.com/en/quote/AMK/news</a></p>
<p>Here's what I have tried so far:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib3
from selenium import webdriver
import re
import time
import random
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument("--headless")
chrome_driver = webdriver.Chrome(r"\chromedriver.exe", chrome_options=chrome_options)
chrome_driver.get(url)
while True:
try:
WebDriverWait(chrome_driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'LOAD MORE')]"))).click()
except Exception as e:
print(i)
break
bs = BeautifulSoup(chrome_driver.page_source, features="lxml")
chrome_driver.close()
</code></pre>
<p>But this always loads only 10 items and breaks, as it can't locate the load more button after a click apparently. Any suggestion will be highly appreciated. Thanks</p>
| [
{
"answer_id": 74418637,
"author": "Smooth Carlito",
"author_id": 9151446,
"author_profile": "https://Stackoverflow.com/users/9151446",
"pm_score": 0,
"selected": false,
"text": "//button[contains(., 'LOAD MORE')]"
},
{
"answer_id": 74419433,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 0,
"selected": false,
"text": "Load more"
},
{
"answer_id": 74419758,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 1,
"selected": false,
"text": "load more button"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9875416/"
] |
74,417,478 | <p>I have two numpy arrays which look like this:</p>
<pre><code>x = [v1, v2, v3, ..., vm]
y = [w1, w2, w3, ..., wn]
</code></pre>
<p>where <code>vi, wj</code> are numpy arrays of length 3.</p>
<p>I want to perform a pairwise <em>summation</em> of v's and w's and get a final array</p>
<pre><code>z = [v1+w1, v1+w2,...,v1+wn,v2+w1, ..., vi+wj, ..., vm+wn]
</code></pre>
<p>A simple way of obtaining <code>z</code> is as follows:</p>
<pre><code>z = np.zeros ((m*n, 3))
for i in range(m):
for j in range(n):
z[n*i+j] = x[i] + y[j]
</code></pre>
<p>This computation is not feasible is <code>m, n</code> are very large.</p>
<p>I know scipy.spatial has methods to enumerate pairwise distances using distance_matrix in a vectorized fashion.</p>
<p>I want to ask if there is a vectorized version of performing such pairwise <em>additions</em> for numpy arrays?</p>
| [
{
"answer_id": 74418637,
"author": "Smooth Carlito",
"author_id": 9151446,
"author_profile": "https://Stackoverflow.com/users/9151446",
"pm_score": 0,
"selected": false,
"text": "//button[contains(., 'LOAD MORE')]"
},
{
"answer_id": 74419433,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 0,
"selected": false,
"text": "Load more"
},
{
"answer_id": 74419758,
"author": "Fazlul",
"author_id": 12848411,
"author_profile": "https://Stackoverflow.com/users/12848411",
"pm_score": 1,
"selected": false,
"text": "load more button"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11833842/"
] |
74,417,493 | <p>I'm trying to make a basic interest income calculator using GUI tkinker in Python. However, after entering all the values, the label at the end doesn't update.</p>
<p><strong>Please note that calculations is just printing the variables for now</strong></p>
<pre><code>import tkinter as tk
frame = tk.Tk()
frame.title("Interest Income Calculator")
frame.geometry('800x450')
label = tk.Label(text="Enter Balance (number, no symbols)")
entry = tk.Entry(fg="Black", bg="White", width=50)
label.pack()
entry.pack()
def update1():
global balance
balance = entry.get()
buttonupdate1 = tk.Button(
text = "Save")
buttonupdate1.pack()
buttonupdate1.config(command = update1())
label2 = tk.Label(text="Enter Standard Interest (percentage but no symbol)")
entry2 = tk.Entry(fg="Black", bg="White", width=50)
label2.pack()
entry2.pack()
def update2():
global sinterest
sinterest = entry2.get()
buttonupdate2 = tk.Button(
text = "Save")
buttonupdate2.pack()
buttonupdate2.config(command = update2())
label3 = tk.Label(text="Enter Bonus Interest (percentage but no symbol)")
entry3 = tk.Entry(fg="Black", bg="White", width=50)
label3.pack()
entry3.pack()
def update3():
global binterest
binterest = entry3.get()
buttonupdate3 = tk.Button(
text = "Save")
buttonupdate3.pack()
buttonupdate3.config(command = update3())
button = tk.Button(
text="Calculate",
width=25,
height=1,
background="white",
foreground="black",
)
button.pack()
calculations = (balance, sinterest, binterest)
label4 = tk.Label(
text = (calculations),
foreground = "black",
background="white",
width=25,
height=10
)
def cont():
label4.pack()
button.config(command=cont())
frame.mainloop()
</code></pre>
<p>I've tried so many things, like moving around the functions etc. with no luck. please help</p>
| [
{
"answer_id": 74417715,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 2,
"selected": true,
"text": "command = func()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19439374/"
] |
74,417,495 | <p>In the pandas package of python, how would one do the following the most easily?</p>
<pre><code>df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
'Parrot', 'Parrot'],
'Max Speed': [380., 370., 24., 26.]})
</code></pre>
<p>Resulting in:</p>
<pre><code> Animal Max Speed
0 Falcon 380.0
1 Falcon 370.0
2 Parrot 24.0
3 Parrot 26.0
</code></pre>
<p>Converting this into:</p>
<pre><code> Falcon Parrot
0 380 24
1 370 26
</code></pre>
<p>I would have expected to able to use the groupby method, but I cannot seem to figure out how to create a new dataframe out of that.</p>
<p>df.groupby('Animal').to_frame() or something along those lines</p>
<p>edit: okay after some messing about I managed to find a solution in the form of:</p>
<pre><code>df.groupby('Animal')['Max Speed'].apply(pd.DataFrame).apply(lambda x: pd.Series(x.dropna().to_numpy()))
</code></pre>
<p>But that seems to be quite clumsy, there is bound to be a better way right?</p>
| [
{
"answer_id": 74417715,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 2,
"selected": true,
"text": "command = func()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489277/"
] |
74,417,512 | <p>I am creating a solution in TypeScript/Javascript with an extension mechanism. The extensions will all be classes extending a provided abstract class and a configuration
file will contain the class name and JSON to pass to the constructor. The extensions to be loaded will be defined in a configuration file.</p>
<p>However, I can't find a way to instantiate an instance of a class from the name of the class.</p>
| [
{
"answer_id": 74417561,
"author": "pilchard",
"author_id": 13762301,
"author_profile": "https://Stackoverflow.com/users/13762301",
"pm_score": 2,
"selected": false,
"text": "class Class1 {\n constructor(val) {\n this.val = val;\n }\n}\n\nconst classes = {\n Class1\n}\n\nconst class1Instance = new classes[\"Class1\"]('val1');\n\nconsole.log(class1Instance.val)"
},
{
"answer_id": 74417573,
"author": "Alexey Zelenin",
"author_id": 6290921,
"author_profile": "https://Stackoverflow.com/users/6290921",
"pm_score": -1,
"selected": false,
"text": "class c1 {\n constructor(m) {\n this.message = m;\n }\n showme() {\n console.log(`It's class c1! Message: ${this.message}.`);\n }\n}\n\nconst className = 'c1';\nconst constructorParams = '\"instance B of class c1\"';\n\nconst b = eval(`new ${className}(${constructorParams })`);\nb.showme();"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281159/"
] |
74,417,530 | <p>After updating to Xcode 14.0 (happens still for 14.0.1, and 14.1) I felt massive slowdown in incremental build times even if changing just a single property. For my project it's 3x, but read about 10x or more.</p>
| [
{
"answer_id": 74417531,
"author": "dziobaczy",
"author_id": 5892635,
"author_profile": "https://Stackoverflow.com/users/5892635",
"pm_score": 3,
"selected": true,
"text": "SWIFT_USE_INTEGRATED_DRIVER"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5892635/"
] |
74,417,532 | <p>I'm trying to host a Node.js/Express server for the first time, and I'm currently attempting to use Digital Ocean's App Platform. I have it up and running, but my routes aren't working correctly. Digital Ocean allows me to set HTTP Request Routes, and I have "/" and "/test" set for two of them. No matter what route I hit, it only ever responds with the "/" route.</p>
<p>Here is my code for reference:</p>
<pre><code>require("dotenv").config();
const { SERVER_PORT } = process.env;
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.status(200).send("This is the / route")
})
app.get("/test", (req, res) => {
res.status(200).send("This the /test route");
})
app.listen(SERVER_PORT, () => {
console.log(`Server running on port ${SERVER_PORT}`);
});
</code></pre>
<p>When I make a GET request to <code>"https://{DigitalOceanURL}/"</code>, I get the correct response of "This is the / route", however when I make a GET request to <code>"https://{DigitalOceanURL}/test"</code>, I still get the response of "This is the / route" and not "This the /test route" as is in my code.</p>
<p>If I try and make request to a route that doesn't exist, however, such as <code>"https://{DigitalOceanURL}/doesntexist"</code> I get the response <code>"Cannot GET /doesntexist"</code>. To me this suggests that the routes I'm entering into DigitalOcean are registering, but for some reason it's not seeing anything past the initial "/" in the route.</p>
<p>I've been trying to Google for a while now and I can't seem to diagnose what's wrong. I thought it might be something with app.use vs app.get, <a href="https://stackoverflow.com/a/58343450">as on this answer on a SO post it says</a> that app.use "...will match all requests <strong>beginning with</strong>..." your route, whereas app.get "...matches only GET request with <strong>exact match</strong>.". So it seems that, since I'm hitting the exact route, it should be working? But it feels like the general area of my problem, as it seems to only be registering the "/" in the route and nothing else?</p>
<p>Both the endpoints work when running the server on localhost, so it seems like there must be some disconnect with DigitalOcean.</p>
<p>Any help would be greatly appreciated - as I mentioned this is my first time trying to host and it's a bit overwhelming.</p>
<p>Thank you!</p>
| [
{
"answer_id": 74417560,
"author": "O. Jones",
"author_id": 205608,
"author_profile": "https://Stackoverflow.com/users/205608",
"pm_score": 0,
"selected": false,
"text": "/"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489238/"
] |
74,417,534 | <p>I'm trying to create a row of images and I have a container that uses half the width of the page and each image takes up a quarter of that half like this:</p>
<pre class="lang-html prettyprint-override"><code><div key={index} class="w-full mt-10 mb-16 md:mt-0 md:absolute md:top-[50%] md:-translate-y-[50%] md:flex md:space-x-10 space-y-5 md:space-y-0 items-start">
{/* Images */}
<div class="w-full sm:w-4/5 md:w-1/2 mx-auto md:mx-0">
<img src={row.image} alt="Product"></img>
<div class="mt-4 w-full flex space-x-5">
<img src="../images/placeholder.svg" alt="Product" class="w-1/4"></img>
<img src="../images/placeholder.svg" alt="Product" class="w-1/4"></img>
<img src="../images/placeholder.svg" alt="Product" class="w-1/4"></img>
<img src="../images/placeholder.svg" alt="Product" class="w-1/4"></img>
</div>
</div>
</div>
</code></pre>
<p>As you can see I have one large image above and 4 smaller images which I would like to align underneath. This currently gives this effect:
<a href="https://i.stack.imgur.com/sxG6U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sxG6U.png" alt="enter image description here" /></a></p>
<p>As you can see the bottom images overflow into the right-hand column. I don't want to overflow hidden or add a scrollbar but instead, I would like the images to be even sizes across this space, with a small gap inbetween. Like this example:
<a href="https://i.stack.imgur.com/iZJQZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iZJQZ.png" alt="enter image description here" /></a></p>
<p>As you can see there's no overflow and the 4 images are even sizes and spaced underneath the image. This is the effect I would like to replicate. I'm currently using Tailwind CSS but a regular CSS explanation would work fine if anyone is unfamiliar with Tailwind.</p>
<p>From my understanding, there's nothing directly wrong with the code as each image does take up a 1/4, however, when I apply some margins to space them apart the images can shrink because they must maintain their 1/4 width. This then pushes the images to one side. I would like any suggestions for a clear approach to achieve the design in image two.</p>
| [
{
"answer_id": 74417560,
"author": "O. Jones",
"author_id": 205608,
"author_profile": "https://Stackoverflow.com/users/205608",
"pm_score": 0,
"selected": false,
"text": "/"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19366108/"
] |
74,417,544 | <p>I'm using activeadmin and in a form associated with a model I would need to add a checkbox that is not tied to any of the model attributes. It should be just a checkbox that won't allow to submit the form until it's checked - I'll also add some Javascript to achieve this.</p>
<p>I've checked the documentation of ActiveAdmin and Formtastic but I want to be able to find anything for this purpose. How to add the custom checkbox and where I should add the Javascript functionality?</p>
| [
{
"answer_id": 74417560,
"author": "O. Jones",
"author_id": 205608,
"author_profile": "https://Stackoverflow.com/users/205608",
"pm_score": 0,
"selected": false,
"text": "/"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1387241/"
] |
74,417,582 | <p>I want to create a procedure that receives two ids, makes two selects in a table and returns the data, after that I want to perform an update in another table using the result that was returned to me earlier, how to do that?</p>
<p>This is an example of how it is at the moment</p>
<pre><code>create or replace procedure transfer(
origin int,
destination int,
amount dec
)
language plpgsql
as $$
begin
select id as id_user_origin
from users
where id = origin
select id as id_user_destination
from users
where id = destination
-- subtracting the amount from the sender's account
update wallets
set balance = balance - amount
where id = id_user_origin;
-- adding the amount to the receiver's account
update wallets
set balance = balance + amount
where id = id_user_destination;
commit;
end;$$
</code></pre>
| [
{
"answer_id": 74423606,
"author": "kofemann",
"author_id": 1356883,
"author_profile": "https://Stackoverflow.com/users/1356883",
"pm_score": 2,
"selected": true,
"text": "declare\n id_user_origin int;\nbegin\n select id into id_user_origin from users where id = origin ;\n \n .....\n update... ;\n"
},
{
"answer_id": 74425623,
"author": "Belayer",
"author_id": 7623856,
"author_profile": "https://Stackoverflow.com/users/7623856",
"pm_score": 0,
"selected": false,
"text": "create or replace procedure transfer(\n origin int\n , destination int \n , amount dec\n)\nlanguage plpgsql \nas $$\nbegin\n update wallets \n set balance = case when id = origin \n then balance - amount\n else balance + amount\n end \n where id in (origin, destination) \n and exists (select null from wallets where id = destination)\n and exists (select null from wallets where id = origin and balance >= amount);\n \n commit; \nend ;\n$$;\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17235816/"
] |
74,417,590 | <p>I have the template code like this:</p>
<pre><code>treatment.colors <- unlist(lapply(GSE8823.qc.rma$status,
function (x) {if (x == "smoker") "red" else "navy"}))
</code></pre>
<p>This code makes the two groups: smoker and non-smoker into different colors. As the code says, if the x==smoker, the color is red, else the color is navy.</p>
<p>Now, I have four groups: G1,G2,G3,G4. I want to define 4 different colors correspondingly. Let us say, I want to G1=red, G2=navy, G3=yellow, G4=green.</p>
<p>My question is how can I rewrite this code to achieve this goal? Should I use another else if in the else part of template code? Should the code look like something this?</p>
<pre><code>treatment.colors <- unlist(lapply(GSE8823.qc.rma$status,
function (x) {if (x == "G1") "red" else if (x=="G2", "navy"), else if (x=="G3", "yellow"), else "green"}))
</code></pre>
<p>Thanks for helping~~!</p>
| [
{
"answer_id": 74417651,
"author": "SpikyClip",
"author_id": 16745699,
"author_profile": "https://Stackoverflow.com/users/16745699",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74417756,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "factor"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16808528/"
] |
74,417,619 | <p>For instance, whenever my count is equal to 4294967295 + 1 I want that the count restart from 0.
Basically I`m trying to simulate a unsigned 32 bits in java that has range [0, 4294967295]. The methods that I'm trying to create is ADD and MULTIPLE.</p>
<p>For example, if I have the number 4294967295 and I multiple by 2, I will get the result 4294967294.</p>
<p>Since Java does not have a unsigned int, I need to create that class to "simulate" the C int uint32_t in Java.</p>
<p>If I multiple 1103527590 * 1103515245 the result should be 4294967294, but my code is giving the result 2524872877</p>
<pre><code>public class Unsigned32BitsInt {
private long limit; // Upper bound 4294967295
public Unsigned32BitsInt(long limit) {
this.limit = limit;
}
public long add(long x, long y) {
long result = 0L;
if (x + y < this.limit) {
if ((x + y) % this.limit == 0) {
result = (x + y) / 2;
} else {
result = (x + y) % this.limit;
}
} else {
if ((x + y) % this.limit == 0) {
result = (x + y) / (Math.max(x, y) / Math.min(x, y)) - 1;
} else {
result = (x + y) % this.limit - 1;
}
}
return result;
}
public long multiple(long x, long y) {
long result = 1L;
long r = x*y;
long c = result = (x * y) % this.limit;
if (x * y < this.limit) {
if ((x * y) % this.limit == 0) {
result = (x + y) / 2;
} else {
result = (x * y) % this.limit;
}
} else {
if ((x * y) % this.limit == 0) {
result = (x * y) / 2 - 1;
} else {
result = (x * y) % this.limit - 1;
}
}
return result;
}
}
</code></pre>
| [
{
"answer_id": 74417815,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 2,
"selected": false,
"text": "4294967295"
},
{
"answer_id": 74418196,
"author": "Old Dog Programmer",
"author_id": 5103317,
"author_profile": "https://Stackoverflow.com/users/5103317",
"pm_score": 1,
"selected": false,
"text": "The answer from @WJS makes a good point: \n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16075374/"
] |
74,417,624 | <p>I admit the answer to this may be 'some very specific magic', but I'm kind of shocked by what I've observed here. I was wondering if anyone had insight to how these types of optimizations work. I find compiler design to be quite interesting, and I really can't imagine how this works. I'm sure the answer is somewhere in the clang source code, but I don't even know where I would look.</p>
<p>I'm a TA for a class at college, and I was recently asked to help with a simple homework question. This led me down an interesting path...</p>
<p>The question is simple enough: In x86_64 assembly, write a function which given a (positive) integer n returns <code>1^2 + 2^2 + 3^2 + ... + n^2</code>.</p>
<p>I decided to play around a bit, and after helping them write this in x86_64 assembly, I, having an M1 macbook, decided to see if I could create a nice solution in arm64 assembly. I came up with the relatively simple and straightforward solution:</p>
<pre><code>_sum_squares:
mov x1, x0 ; Do multiplication from x1
mov x0, xzr ; Clear x0
Lloop:
; x0 <-- (x1 * x1) + x0
madd x0, x1, x1, x0
; Loop until x1 == 0
subs x1, x1, #1
bne Lloop
ret
</code></pre>
<p>(I wish there was some sort of nice way to do branch if <code>--x1 == 0</code> in one instruction, but I couldn't think of any)</p>
<p>Note: There is a simple formula for this from any basic number theory class, which is <code>[n(n + 1)(2n + 1)] / 6</code>, but I decided this wasn't really in the spirit of the question.</p>
<p>I then was wondering how clang would generate assembly for a simple C version. Upon writing the simple C implementation, I found that clang with <code>-Og</code> generates assembly which seems a bit verbose, but generally works as expected with a loop and accumulator (although it is very inefficient):</p>
<pre><code>int sum_squares(int n)
{
int a = 0;
while (n--)
a += (n * n);
return a;
}
</code></pre>
<p>(<code>clang -Og -S</code>, annotated myself, cfi removed, labels renamed)</p>
<pre><code>_sum_squares:
sub sp, sp, #16 ; create stack space
str w0, [sp, #12] ; store n
str wzr, [sp, #8] ; store 0
b Ldec ; silly clang, this just falls through...
Ldec: ; n-- and return if n == 0
ldr w8, [sp, #12] ; load n
subs w9, w8, #1 ; w9 = (n - 1)
str w9, [sp, #12] ; store (n - 1) over n
subs w8, w8, #0 ; w8 = n - 0 (set flags based on n)
cset w8, eq ; set w8 = 1 if n == 0 else w8 = 0
tbnz w8, #0, Lret ; branch to return if n == 0, else fall through
b Ladd ; silly clang, this falls through again...
Ladd: ; a += n^2
ldr w8, [sp, #12] ; load n
ldr w9, [sp, #12] ; load n
mul w9, w8, w9 ; w9 = n * n
ldr w8, [sp, #8] ; load a
add w8, w8, w9 ; a += w9
str w8, [sp, #8] ; store a
b Ldec ; go back to start of look
Lret: ; return a from top of stack
ldr w0, [sp, #8] ; w0 = a
add sp, sp, #16 ; cleanup temp stack
ret ; back to caller
</code></pre>
<p>This is altogether reasonable for a direct translation of the C code to arm64 assembly. After some optimization (O1 uses a similar formula, O2 and O3 are identical), clang comes up with some magic. I have no clue how it came up with this code, it appears to be somewhat similar to the basic formula for this summation, except with bit magic. I didn't imagine the compiler would be able to derive a formula for this without a loop, but it appears I was wrong. The generated code is as follows (with my best attempt at a commentary, n is the input in <code>w0</code>):</p>
<pre><code>_sum_squares:
cbz w0, Lret ; return if n == 0
sub w8, w0, #1 ; w8 = (n - 1)
mul w9, w8, w8 ; w9 = (n - 1)^2
orr w9, w9, #0x2 ; w9 = ((n - 1)^2) | 2
sub w9, w9, w0 ; w9 = [((n - 1)^2) | 2] - n
mov w10, #5 ; w10 = 5
sub w10, w10, w0, lsl #1 ; w10 = 5 - (n / 2)
sub w11, w0, #2 ; w11 = n - 2
umull x11, w8, w11 ; w11 = (n - 1)(n - 2)
lsr x12, x11, #1 ; x12 = ((n - 1)(n - 2)) / 2
mul w10, w10, w12 ; w10 = (5 - (n / 2))(((n - 1)(n - 2)) / 2)
sub w12, w0, #3 ; w12 = n - 3
mul x11, x11, x12 ; x11 = (n - 1)(n - 2)(n - 3)
lsr x11, x11, #1 ; x11 = ((n - 1)(n - 2)(n - 3)) / 2
mov w12, #21846 ; w12 = 0x5556
movk w12, #21845, lsl #16 ; w12 = 0x55555556
; w8 = ((n - 1)([((n - 1)^2) | 2] - n)) + (5 - (n / 2))(((n - 1)(n - 2)) / 2)
madd w8, w9, w8, w10
; let A = w8 (set in last instruction)
; w0 = (0x55555556 * (((n - 1)(n - 2)(n - 3)) / 2)) + A
madd w0, w11, w12, w8
; somehow, this is the correct result?
; this feels like magic to me...
Lret:
ret ; return. Result already in w0.
</code></pre>
<p>My question: How in the world does this work? How can a C compiler be given a loop like this and deduce a formula not even involving a loop? I expected some loop unwinding perhaps, but nothing like this. Does anyone have references involving this type of optimization?</p>
<p>I especially don't understand what certain steps like <code>orr w9, w9, #0x2</code> or the magic number 0x55555556 does. Any insight into these steps would be extra appreciated.</p>
| [
{
"answer_id": 74419103,
"author": "Nate Eldredge",
"author_id": 634919,
"author_profile": "https://Stackoverflow.com/users/634919",
"pm_score": 4,
"selected": false,
"text": "sum_squares"
},
{
"answer_id": 74420767,
"author": "Peter Cordes",
"author_id": 224132,
"author_profile": "https://Stackoverflow.com/users/224132",
"pm_score": 7,
"selected": true,
"text": "__builtin_memcpy"
},
{
"answer_id": 74669459,
"author": "thatthing",
"author_id": 624493,
"author_profile": "https://Stackoverflow.com/users/624493",
"pm_score": 0,
"selected": false,
"text": "int sum_squares(int n) {\nint a = 0;\nfor (int i = 1; i <= n; i++) {\na += i * i;\n}\nreturn a;\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4897973/"
] |
74,417,631 | <p>How can I print Cypress base Url in the <code>Git bash CLI console</code> while running the Cypress test ? Could someone please advise ?</p>
| [
{
"answer_id": 74417767,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "console.log(Cypress.config().baseUrl)"
},
{
"answer_id": 74418589,
"author": "TesterDick",
"author_id": 18366749,
"author_profile": "https://Stackoverflow.com/users/18366749",
"pm_score": 3,
"selected": true,
"text": "cy.task()"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4826215/"
] |
74,417,729 | <p>Let's say I have the following two classes:</p>
<pre><code>class Literal:
pass
class Expr:
pass
class MyClass:
def __init__(self, Type:OneOf(Literal, Expr)):
pass
</code></pre>
<p>How would I make the type one of the <code>Expr</code> or <code>Literal</code> class? The full example of what I'm trying to do is as follows:</p>
<pre><code>from enum import Enum
PrimitiveType = Enum('PrimitiveType', ['STRING', 'NUMBER'])
class Array:
def __init__(self, Type:OneOf[Array,Struct,PrimitiveType]):
self.type = Type
class Pair:
def __init__(self, Key:str, Type:OneOf[Array,Struct,PrimitiveType]):
self.Key = Key
self.Type = Type
class Struct:
def __init__(self, tuple[Pair])
</code></pre>
| [
{
"answer_id": 74417751,
"author": "Carcigenicate",
"author_id": 3000206,
"author_profile": "https://Stackoverflow.com/users/3000206",
"pm_score": 2,
"selected": true,
"text": "Union"
},
{
"answer_id": 74417768,
"author": "Brijesh Varsani",
"author_id": 14525381,
"author_profile": "https://Stackoverflow.com/users/14525381",
"pm_score": 2,
"selected": false,
"text": "from typing import Union\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651174/"
] |
74,417,740 | <p>Trying to find the respondent in the list g.list with the most words in their response (g.list is a list of respondents with their IDs). However, g.list contains lists within it with the actual response which leads to the lapply(length) giving length 1. I'm struggling to deal with this. I'd ideally like to do this using the lapply() and strsplit() functions.
Here's my code:</p>
<pre><code>head(g.list)
</code></pre>
<p>Output:</p>
<pre><code>$`1590553444`
[1] "Nothing"
$`1590610566`
[1] "Couldn't sit in a lot of them"
$`1590609253`
[1] "N/a"
</code></pre>
<p>Code:</p>
<pre><code>g.split <- lapply(unlist(g.list), strsplit, " ")
head(g.split)
</code></pre>
<p>Output:</p>
<pre><code>$`1590553444`
$`1590553444`[[1]]
[1] "Nothing"
$`1590610566`
$`1590610566`[[1]]
[1] "Couldn't" "sit" "in" "a" "lot" "of" "them"
$`1590609253`
$`1590609253`[[1]]
[1] "N/a"
</code></pre>
<p>Code:</p>
<pre><code> g.count <- lapply(unlist(g.split), length)
head(g.count)
</code></pre>
<p>Output:</p>
<pre><code>$`1590553444`
[1] 1
$`1590610566`
[1] 1
$`1590609253`
[1] 1
</code></pre>
<p>Code:</p>
<pre><code>max(unlist(g.count))
</code></pre>
<p>I was expecting g.count <- lapply(unlist(g.split), length) to give the number of words. However, all of them are 1. I know this is super basic but I'm new to R and would really appreciate some help with this.</p>
| [
{
"answer_id": 74418030,
"author": "SpikyClip",
"author_id": 16745699,
"author_profile": "https://Stackoverflow.com/users/16745699",
"pm_score": 2,
"selected": true,
"text": "[[1]]"
},
{
"answer_id": 74418040,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "list"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8277973/"
] |
74,417,757 | <p>I had the following error in Nov 13th 2022</p>
<pre><code>end = datetime.strptime("2022-11-16", "%Y-%d-%m")
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/_strptime.py", line 352, in _strptime
raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: 6
</code></pre>
<p>but I didn't have the error in the following case,</p>
<pre><code>date_value = datetime.strptime("2022-11-12", "%Y-%d-%m")
</code></pre>
<p>Well, strptime function of datetime module is not support to convert for future date?
If no, let me know the way....please</p>
| [
{
"answer_id": 74417773,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "datetime.strptime(\"2022-11-16\", \"%Y-%d-%m\")\n"
},
{
"answer_id": 74417775,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "datetime.strptime(\"2022-16-11\", \"%Y-%d-%m\")\n"
},
{
"answer_id": 74417795,
"author": "kushaan gulati",
"author_id": 8277973,
"author_profile": "https://Stackoverflow.com/users/8277973",
"pm_score": 1,
"selected": false,
"text": "datetime.strptime(\"2022-11-16\", \"%Y-%m-%d\")\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12758069/"
] |
74,417,779 | <p>Assume that we have a string like:XYYX. I want to get YXXY.How do I do that in python?</p>
<p>couldnt think of anything</p>
| [
{
"answer_id": 74417773,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "datetime.strptime(\"2022-11-16\", \"%Y-%d-%m\")\n"
},
{
"answer_id": 74417775,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "datetime.strptime(\"2022-16-11\", \"%Y-%d-%m\")\n"
},
{
"answer_id": 74417795,
"author": "kushaan gulati",
"author_id": 8277973,
"author_profile": "https://Stackoverflow.com/users/8277973",
"pm_score": 1,
"selected": false,
"text": "datetime.strptime(\"2022-11-16\", \"%Y-%m-%d\")\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489565/"
] |
74,417,791 | <p>Here's what I'm trying to do: When a button is clicked, one paragraph element is replaced by another paragraph element. I'd like it to be seamless, where the one paragraph element just disappears, and the other paragraph element appears in its place.</p>
<p>But no matter what I try I can't seem to get the other paragraph element to appear. The paragraph element to be hidden disappears fine, but the other span element doesn't appear in its place.</p>
<p>I've tried many different approaches, like</p>
<pre><code><p style="display: none;" id="element_to_show">text to show</p>
...
document.getElementById('element_to_show').style.display = "block";
</code></pre>
<p>as well as</p>
<pre><code><p hidden id="element_to_show">text to show</p>
...
document.getElementById('element_to_show').hidden = false;
</code></pre>
<p>as well as</p>
<pre><code><p style="visibility: hidden;" id="element_to_show">text to show</p>
...
document.getElementById('element_to_show').style.visibility = "visible";
</code></pre>
<p>but nothing seems to work.</p>
<p>I'm aware that in Javascript I could create the new paragraph I want by document.createElement() and then using replaceWith(), but there are various other elements inside the paragraph element that I would have to recreate and that would be messy programmatically. That's not to mention the fact that I would have to recreate the original paragraph element when the user clicks another button to bring that paragraph element back. It seems so easy just to code the elements in HTML and show and hide them on the button click, but I just can't get it right.</p>
<p>Note: Please do not show me how to do this in jQuery unless you think it's the only way. I'd like to accomplish it in vanilla Javascript, if possible, please.</p>
<p>Here's the HTML code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome to our website!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="profile">
<p id="profile_first_name_show">
<span class="profile_label">First name:</span>
<span id="profile_first_name_edit">
<span id="profile_first_name_value">{{ request.session.current_user_data.first_name }}</span>
<button onclick="show_hidden()"><span class="glyphicon glyphicon-pencil"></span></button>
</span>
</p>
<p style="visibility: hidden;" id="profile_first_name_edit">
text to show
</p>
</div>
</body>
</html>
</code></pre>
<p>and here's the .js file</p>
<pre><code>function show_hidden() {
document.querySelector("#profile_first_name_edit").style.visibility = "visible"; // this and various other methods don't work!!
document.getElementById('profile_first_name_show').style.display = "none"; // this works!
}
</code></pre>
| [
{
"answer_id": 74417773,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "datetime.strptime(\"2022-11-16\", \"%Y-%d-%m\")\n"
},
{
"answer_id": 74417775,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 0,
"selected": false,
"text": "datetime.strptime(\"2022-16-11\", \"%Y-%d-%m\")\n"
},
{
"answer_id": 74417795,
"author": "kushaan gulati",
"author_id": 8277973,
"author_profile": "https://Stackoverflow.com/users/8277973",
"pm_score": 1,
"selected": false,
"text": "datetime.strptime(\"2022-11-16\", \"%Y-%m-%d\")\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20200247/"
] |
74,417,797 | <p>I want to create a c program that executes commands in a txt file. I read each value of my txt file and put them in an array and then I want to run them one by one using a fork function.
Thank you for your help</p>
<p>I hope a charitable help to tell me where the problem is.
I enclose a part of my code and my data file.</p>
<pre><code>void Execfile(char*filename)
{
char**T;
int nb;
FILE*f;
char buff[MAX_ARG];
f=fopen("data1.txt","rb");
while(fgets(buff,MAX_ARG,f)!=NULL){
T=File2TabArgv(filename,&nb);
}
fclose(f);
execvp(T[0],T);
printf("\n");
printf("END");
}
in txt.file```
sleep20
</code></pre>
| [
{
"answer_id": 74417831,
"author": "cyberbisson",
"author_id": 7257958,
"author_profile": "https://Stackoverflow.com/users/7257958",
"pm_score": 1,
"selected": false,
"text": "execvp"
},
{
"answer_id": 74433936,
"author": "Julien",
"author_id": 7473954,
"author_profile": "https://Stackoverflow.com/users/7473954",
"pm_score": 0,
"selected": false,
"text": "int status;\nmy_pid = fork();\nif (my_pid >= 0) {\n if (my_pid == 0) { /*child*/\n execvp(...);\n printf(\"failed\\n\");\n exit(1);\n } else { /*parent*/\n wait(&status);\n printf(\"child exit code: %d\\n\", WEXITSTATUS(status));\n }\n} else {\n perror(\"fork failed\");\n exit(1);\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489494/"
] |
74,417,800 | <p>I have a string variable which is a point, such as m="(2, 5)" or m="(-6, 7)". I want to extract the x coordinate and y coordinate and store them in different variables. Could someone provide some code in Python for how I could do this? Thanks!</p>
| [
{
"answer_id": 74417832,
"author": "lckcorsi",
"author_id": 20252725,
"author_profile": "https://Stackoverflow.com/users/20252725",
"pm_score": -1,
"selected": false,
"text": "def coords(m):\n for i in range(2, len(m) - 2):\n if m[i] == ',':\n return m[1:i],m[(i+1),(len(m)-1)]\n"
},
{
"answer_id": 74417961,
"author": "Mohammed Chaaraoui",
"author_id": 16760993,
"author_profile": "https://Stackoverflow.com/users/16760993",
"pm_score": 0,
"selected": false,
"text": "m = \"(7, 5)\"\nx, y = m.strip('()').split(',')\nprint(x) # 7\nprint(y) # 5\n"
},
{
"answer_id": 74418007,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 0,
"selected": false,
"text": "ast"
},
{
"answer_id": 74418141,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 0,
"selected": false,
"text": "m = \"(2, 5)\"\nx, y = m.strip('()').split(',')\nx, y\n\n('2', ' 5')\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19386408/"
] |
74,417,814 | <p>I have the following code where I am trying to group the dataframe 'newdata' by the first column and then find the mean of the column '0_happy'.</p>
<p>However, the output is producing me with e numbers, which seem too big/small to be mean values.</p>
<p>I would be so grateful if anybody could point out where I may be going wrong?</p>
<pre><code>newdatahappy = newdata.groupby(newdata.iloc[:,0])[str(0) + '_happy'].mean()
print(newdatahappy)
0_type
fullMiss 3.113534e+20
hit 1.893626e+07
nearMiss 4.149066e+13
Name: 0_happy, dtype: float64
</code></pre>
<p>The first 10 rows of newdata:</p>
<pre><code> 0_type 0_happy 0_motive
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
5 fullMiss 37 66
6 nearMiss 33 67
7 hit 75 60
8 fullMiss 36 63
9 hit 74 42
10 nearMiss 19 45
</code></pre>
| [
{
"answer_id": 74417870,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "float format"
},
{
"answer_id": 74417931,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 1,
"selected": false,
"text": "# to make it easier for other folks trying to check this out\nNaN = np.nan\ndata = [[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[\"fullMiss\",37,66],\n[\"nearMiss\",33,67],\n[\"hit\",75,60],\n[\"fullMiss\",36,63],\n[\"hit\",74,42],\n[\"nearMiss\",19,45]]\nnewdata = pd.DataFrame(data, columns=['0_type', '0_happy', '0_motive'])\n\n# you can use the column name directly in groupy\nnewdata.groupby(\"0_type\")[str(0) + '_happy'].mean()\n"
},
{
"answer_id": 74421625,
"author": "Caledonian26",
"author_id": 12985497,
"author_profile": "https://Stackoverflow.com/users/12985497",
"pm_score": 0,
"selected": false,
"text": "newdatahappy = newdata.groupby(newdata.iloc[:,0])[str(0) + '_happy'].mean()\nnewdata[str(j) + '_happy'] = newdata[str(j) + '_happy'].astype('int')\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12985497/"
] |
74,417,827 | <p>I am writing a language dictionary using Flutter with Firestore.
I have database named ‘Spanish’ and 2 documents ‘easy’ and ‘difficult’.
Each document is a set pairs - a key is original Spanish word and the value is translation of this word.</p>
<p>I want to find which keys (original Spanish words) appears in both ‘easy’ and ‘difficult’ documents.
My query (which is not working) is:</p>
<pre><code>var myResult = await FirebaseFirestore.instance
.collection('Spanish')
.doc('easy')
.get()
.then((snapshot) {
if (snapshot != null) {
snapshot.data()?.forEach((key, value) {
var myData2 = **checkIfSelected**(key);
print(myData2) ;
});
Future<dynamic> checkIfSelected(String key) async {
bool ifSelected = false;
var myResult2 = await FirebaseFirestore.instance
.collection('Spanish')
.doc('difficult')
.get()
.then((snapshot) {
if (snapshot != null) {
snapshot.data()?.forEach((k, v) {
if (k == key) {
ifSelected = true;
}
}
});
return ifSelected;
}
</code></pre>
<p>Why is not working? I made a lot of displays which I removed from quoted code, but function <strong>checkIfSelected</strong> returns <strong>Instance of 'Future'</strong> instead of bool. This is async function with await, so as I understand it should not return Futures.
I tried make a change:</p>
<pre><code>var myData2 = await checkIfSelected(key);
</code></pre>
<p>but got error:</p>
<blockquote>
<p>The await expression can only be used in an async function.
Try marking the function body with either 'async' or 'async*'.dart(await_in_wrong_context)</p>
</blockquote>
<p>But <code>checkIfSelected</code> is already an <code>async</code> function.</p>
<p>Any ideas what I did wrong in my code, or maybe there is another approach to this problem?</p>
| [
{
"answer_id": 74417870,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "float format"
},
{
"answer_id": 74417931,
"author": "D.Manasreh",
"author_id": 7509907,
"author_profile": "https://Stackoverflow.com/users/7509907",
"pm_score": 1,
"selected": false,
"text": "# to make it easier for other folks trying to check this out\nNaN = np.nan\ndata = [[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[NaN,NaN,NaN],\n[\"fullMiss\",37,66],\n[\"nearMiss\",33,67],\n[\"hit\",75,60],\n[\"fullMiss\",36,63],\n[\"hit\",74,42],\n[\"nearMiss\",19,45]]\nnewdata = pd.DataFrame(data, columns=['0_type', '0_happy', '0_motive'])\n\n# you can use the column name directly in groupy\nnewdata.groupby(\"0_type\")[str(0) + '_happy'].mean()\n"
},
{
"answer_id": 74421625,
"author": "Caledonian26",
"author_id": 12985497,
"author_profile": "https://Stackoverflow.com/users/12985497",
"pm_score": 0,
"selected": false,
"text": "newdatahappy = newdata.groupby(newdata.iloc[:,0])[str(0) + '_happy'].mean()\nnewdata[str(j) + '_happy'] = newdata[str(j) + '_happy'].astype('int')\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373986/"
] |
74,417,872 | <p>Getting some trouble with a function in C that basically creates and allocates a temporary array with help of the length of the name parameter + extension length.</p>
<pre><code>int my_func(char *name)
{
char *extension = ".db";
size_t tmp_size = strlen(name) + strlen(extension);
char tmp_name[tmp_size];
return 0;
}
</code></pre>
<p>This does not however seem to work on MSVC but works fine on Clang or GCC. Any idea why I get these errors:</p>
<pre><code>error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'tmp_name': unknown size
</code></pre>
<p>When I use the debugger in Clang on macOS I see that it allocates and work fine. Why not for MSVC?</p>
| [
{
"answer_id": 74417883,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 4,
"selected": true,
"text": "tmp_name"
},
{
"answer_id": 74417889,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 2,
"selected": false,
"text": "#include <stdlib.h>\n#include <string.h>\n\nint my_func(char *name)\n{\n char *extension = \".db\";\n size_t tmp_size = strlen(name) + strlen(extension);\n char *tmp_name;\n\n tmp_name = malloc(sizeof(*tmp_name) * tmp_size + 1 );\n \n \n return 0;\n}\n"
}
] | 2022/11/13 | [
"https://Stackoverflow.com/questions/74417872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16891224/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.