qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,594,671
|
<p>Whenever I try to draw an SFML sprite with a negative position, the sprite will not be drawn to the screen. I have tried with and without a view applied to the window, but the sprite is not rendered either time.</p>
<p>I have a sprite with a texture on it (size 32*64). I try drawing in at position (-1,-1) but it will not work. Is this intentional behaviour. If so how would I go about drawing sprites with negative positions.
thanks</p>
|
[
{
"answer_id": 74638847,
"author": "domon41c",
"author_id": 20140270,
"author_profile": "https://Stackoverflow.com/users/20140270",
"pm_score": 1,
"selected": false,
"text": "sf::Texture texture;\nif (!texture.loadFromFile(\"texture.png\")) {\n std::cout << \"Error rendering Object\";\n return 0;\n}\n\nsf::Sprite Sprite;\nSprite.setTexture(texture);\n\nSprite.setPosition(sf::Vector2f(-5, -5));\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74594671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19737708/"
] |
74,594,738
|
<p>I've been trying to create a connection between two hosts with a POST request sent as JSON using cURL in PHP. My primary objective is to send data from Host A to Host B (labelled for clarity).</p>
<p>First, looking at network tools in the sender browser, the request type is always GET instead of POST, despite using CURLOPT_POSTFIELDS and CURLOPT_POST. Secondly, the data is not printing/echoing in the receiving browser. However, the hardcoded outputs in the receiving script are printing in both browsers. I've tried using CURLOPT_CUSTOMREQUEST 'POST' to no avail.</p>
<p>Sender JSON tab: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 59 of the JSON data</p>
<p>Sender Raw Data tab: {"ChangeType":"renamed","Path":"C:\File1","Param3":"Yes"}receive_jsonpost_test.php is running renamedC:\File1YesObject id #1</p>
<p>Code:</p>
<pre class="lang-php prettyprint-override"><code><?php
// HOST A (sender)
header("Content-Type:application/json");
$testobj = array(
'ChangeType' => 'renamed',
'Path' => 'C:\\File1',
'Param3' => 'Yes'
);
$url = '[redacted].edu/receive_jsonpost_test.php';
$ch = curl_init($url);
$payload = json_encode($testobj);
print($payload);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$result = curl_exec($ch);
curl_close($ch);
print($result);
?>
</code></pre>
<pre class="lang-php prettyprint-override"><code><?php
// HOST B (recipient)
print('receive_jsonpost_test.php is running ');
$json = file_get_contents('php://input');
$data = json_decode($json);
print($data->ChangeType);
print($data->Path);
print($data->Param3);
print($data);
</code></pre>
<p>I know this is probably a pretty basic problem, but I'm fairly new to applied host-to-host communication and any help would be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 74594812,
"author": "Phil",
"author_id": 283366,
"author_profile": "https://Stackoverflow.com/users/283366",
"pm_score": 1,
"selected": false,
"text": "print($result);\n $json = file_get_contents('php://input');\n$data = json_decode($json);\n\n// ...do whatever but no `echo` or `print`\n\nheader('content-type: application/json');\necho json_encode($someDataStructure); // now respond with some JSON\nexit;\n print($payload);\n"
},
{
"answer_id": 74609382,
"author": "Misunderstood",
"author_id": 3813605,
"author_profile": "https://Stackoverflow.com/users/3813605",
"pm_score": 0,
"selected": false,
"text": "print($payload);\n header(\"Content-Type:application/json\"); \n $postdata= array(\n 'ChangeType' => 'renamed',\n 'Path' => 'C:\\\\File1',\n 'Param3' => 'Yes'\n);\n\n\ncurl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_POST, true);\n$result = curl_exec($ch);\necho $response;\n header('Content-Type: text/plain');\n\nforeach($_POST as $key => $value){\n echo \"$key $value\\n\"\n}\n foreach($_REQUEST as $key => $value){\n echo \"$key $value\\n\"\n}\n $postdata= json_encode(array(\n 'ChangeType' => 'renamed',\n 'Path' => 'C:\\\\File1',\n 'Param3' => 'Yes'\n));\n\ncurl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));\ncurl_setopt($ch, CURLOPT_POST, true);\n$result = curl_exec($ch);\necho $response;\n header('content-type: application/json');\necho file_get_contents('php://input');\n header('content-type: text/plain');\necho file_get_contents('php://input');\n header('content-type: text/plain');\nvar_export(json_decode(file_get_contents('php://input'),1);\n https://example.com?ChangeType=renamed'&Path=C:\\\\File1&Param3=Yes\n\nforeach($_REQUEST as $key => $value){\n echo \"$key $value\\n\"\n}\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74594738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20592762/"
] |
74,594,739
|
<p>I'm trying to import SVG icons for each item in a v-for loop, with the filename changing depending on the item's id. The icons are loading, but I get the following error for each icon imported.</p>
<p>Is there a better way to approach this?</p>
<blockquote>
<p>Uncaught (in promise) TypeError: Failed to resolve module specifier '~/assets/img/flags/ar.svg'</p>
</blockquote>
<pre><code><template>
<NavigationItem v-for="item in topCountries">
<template #icon>
<component :is="getIcon(item.id)" />
</template>
<NavigationItem />
</template>
<script setup>
const getIcon = (id) => defineAsyncComponent(() =>
import(`~/assets/img/flags/${id}.svg`));
</script>
</code></pre>
|
[
{
"answer_id": 74594878,
"author": "principal kelvin",
"author_id": 15610959,
"author_profile": "https://Stackoverflow.com/users/15610959",
"pm_score": 0,
"selected": false,
"text": "<template>\n <ul>\n <!-- list rendering -->\n <li v-for=\"item in items\">\n <span class=\"icon\">\n <i :class=\"[faClass(item.icon)]\" \n aria-hidden=\"true\"></i>\n </span>\n </li>\n </ul>\n</template>\n\n<script>\nexport default {\n name: \"navbarMobile\",\n data() {\n return {\n //listItems\n items: [\n {\n icon: 'home',\n },\n \n {\n icon: 'wrench',\n },\n \n {\n icon: 'project-diagram',\n \n },\n {\n icon: 'cogs',\n\n\n },\n {\n icon: 'phone',\n }\n ]\n }\n },\n \n methods: {\n faClass(icon) {\n return `fa fa-${icon}`;\n }\n }\n\n}\n\n</script>\n\n"
},
{
"answer_id": 74600041,
"author": "Tristan",
"author_id": 13001005,
"author_profile": "https://Stackoverflow.com/users/13001005",
"pm_score": 1,
"selected": false,
"text": "npm i --save nuxt-svgo nuxt.config // nuxt.config.ts\nimport { defineNuxtConfig } from 'nuxt'\n\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n modules: ['nuxt-svgo']\n})\n <script setup lang=\"ts\">\nconst getIcon = (id: string) => defineAsyncComponent(() => import(`@/assets/svg/${id}.svg`));\n</script>\n\n<template>\n <div v-for=\"item in ['icon1', 'icon2']\">\n <component :is=\"getIcon(item)\" />\n </div>\n</template>\n custom.d.ts // custom.d.ts\ndeclare module '*.svg' {\n import type { DefineComponent } from 'vue'\n const component: DefineComponent\n export default component\n}\n"
},
{
"answer_id": 74600308,
"author": "Amini",
"author_id": 15351296,
"author_profile": "https://Stackoverflow.com/users/15351296",
"pm_score": 0,
"selected": false,
"text": "?inline <template>\n<NavigationItem v-for=\"item in topCountries\">\n <template #icon>\n <component :is=\"item.icon\" />\n </template>\n<NavigationItem />\n</template>\n <script setup>\nimport Eye from '~/assets/img/flags/Eye.svg?inline';\nimport Balls from '~/assets/img/flags/Balls.svg?inline';\n\nconst topCountries = [\n { icon: 'Eye' },\n { icon: 'Balls' }\n]\n</script>\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74594739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7087551/"
] |
74,594,760
|
<p>I have a list that is filled with a request body. I expect 400 BAD Request response status when No value or Null is passed in request.
is working as expected when No value is being passed. But for Null, it does not throw 400. How can I make it work?</p>
<pre><code>class data{
@NotEmpty
private List<@Valid String> values;
}
</code></pre>
<p>Request body 1 -> getting response status 200. This is expected.</p>
<pre><code>{
"values": [
"randomValue"
]
}
</code></pre>
<p>Request body 2 -> getting response status 400 (VALIDATION_ERROR) . This is expected.</p>
<pre><code>{
}
</code></pre>
<p>Request body 3 -> getting response status 400 (VALIDATION_ERROR) . This is expected.</p>
<pre><code>{
"values": [
]
}
</code></pre>
<p>Request body 4 -> <strong>getting response status 200.</strong> <strong>Expected status 400 (VALIDATION_ERROR).</strong></p>
<pre><code>{
"values": [
null
]
}
</code></pre>
|
[
{
"answer_id": 74594878,
"author": "principal kelvin",
"author_id": 15610959,
"author_profile": "https://Stackoverflow.com/users/15610959",
"pm_score": 0,
"selected": false,
"text": "<template>\n <ul>\n <!-- list rendering -->\n <li v-for=\"item in items\">\n <span class=\"icon\">\n <i :class=\"[faClass(item.icon)]\" \n aria-hidden=\"true\"></i>\n </span>\n </li>\n </ul>\n</template>\n\n<script>\nexport default {\n name: \"navbarMobile\",\n data() {\n return {\n //listItems\n items: [\n {\n icon: 'home',\n },\n \n {\n icon: 'wrench',\n },\n \n {\n icon: 'project-diagram',\n \n },\n {\n icon: 'cogs',\n\n\n },\n {\n icon: 'phone',\n }\n ]\n }\n },\n \n methods: {\n faClass(icon) {\n return `fa fa-${icon}`;\n }\n }\n\n}\n\n</script>\n\n"
},
{
"answer_id": 74600041,
"author": "Tristan",
"author_id": 13001005,
"author_profile": "https://Stackoverflow.com/users/13001005",
"pm_score": 1,
"selected": false,
"text": "npm i --save nuxt-svgo nuxt.config // nuxt.config.ts\nimport { defineNuxtConfig } from 'nuxt'\n\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n modules: ['nuxt-svgo']\n})\n <script setup lang=\"ts\">\nconst getIcon = (id: string) => defineAsyncComponent(() => import(`@/assets/svg/${id}.svg`));\n</script>\n\n<template>\n <div v-for=\"item in ['icon1', 'icon2']\">\n <component :is=\"getIcon(item)\" />\n </div>\n</template>\n custom.d.ts // custom.d.ts\ndeclare module '*.svg' {\n import type { DefineComponent } from 'vue'\n const component: DefineComponent\n export default component\n}\n"
},
{
"answer_id": 74600308,
"author": "Amini",
"author_id": 15351296,
"author_profile": "https://Stackoverflow.com/users/15351296",
"pm_score": 0,
"selected": false,
"text": "?inline <template>\n<NavigationItem v-for=\"item in topCountries\">\n <template #icon>\n <component :is=\"item.icon\" />\n </template>\n<NavigationItem />\n</template>\n <script setup>\nimport Eye from '~/assets/img/flags/Eye.svg?inline';\nimport Balls from '~/assets/img/flags/Balls.svg?inline';\n\nconst topCountries = [\n { icon: 'Eye' },\n { icon: 'Balls' }\n]\n</script>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13809107/"
] |
74,594,798
|
<p>I have <code>ggplot2</code> 3.4.0 installed on Ubuntu 22.04, but for some reasons I would like to use older version <code>ggplot2</code> 3.3.6.</p>
<pre><code>library(ggplot2, lib.loc="~/R/ggplot336/")
</code></pre>
<p>I worked fine when I started with a clean script file. However, when I use an existing script file like:</p>
<pre><code>library(ggplot2, lib.loc="~/R/ggplot336/")
ggimage::geom_image()
</code></pre>
<p>I got the following error massage:</p>
<blockquote>
<p>Error in value[3L] :
Package ‘ggplot2’ version 3.4.0 cannot be unloaded:
Error in unloadNamespace(package) : namespace ‘ggplot2’ is imported by ‘ggfun’, ‘ggplotify’, ‘ggimage’ so cannot be unloaded</p>
</blockquote>
<h1>Edit</h1>
<ol>
<li>Fresh start Rstudio</li>
<li>Open my R script file with following 3 lines:</li>
</ol>
<pre><code>sessionInfo()
library(ggplot2, lib.loc="~/R/ggplot336/")
ggimage::geom_image()
</code></pre>
<p>When I run the first line, <code>sessionInfo()</code> before doing anything else. We can see <code>ggplot2_3.4.0</code> there. Could this be a Rstudio feature or an issue?</p>
<pre class="lang-r prettyprint-override"><code>R version 4.2.2 Patched (2022-11-10 r83330)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.1 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
locale:
[1] LC_CTYPE=en_AU.UTF-8 LC_NUMERIC=C LC_TIME=en_AU.UTF-8
[4] LC_COLLATE=en_AU.UTF-8 LC_MONETARY=en_AU.UTF-8 LC_MESSAGES=en_AU.UTF-8
[7] LC_PAPER=en_AU.UTF-8 LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] Rcpp_1.0.9 highr_0.9 pillar_1.8.1 compiler_4.2.2
[5] R.utils_2.12.2 R.methodsS3_1.8.2 yulab.utils_0.0.5 tools_4.2.2
[9] digest_0.6.30 evaluate_0.18 jsonlite_1.8.3 lifecycle_1.0.3
[13] tibble_3.1.8 gtable_0.3.1 ggimage_0.3.1 R.cache_0.16.0
[17] pkgconfig_2.0.3 rlang_1.0.6 reprex_2.0.2 DBI_1.1.3
[21] cli_3.4.1 ggplotify_0.1.0 rstudioapi_0.14 magick_2.7.3
[25] yaml_2.3.6 xfun_0.35 fastmap_1.1.0 knitr_1.41
[29] withr_2.5.0 dplyr_1.0.10 styler_1.8.1 generics_0.1.3
[33] vctrs_0.5.1 fs_1.5.2 gridGraphics_0.5-1 grid_4.2.2
[37] tidyselect_1.2.0 glue_1.6.2 R6_2.5.1 processx_3.8.0
[41] fansi_1.0.3 rmarkdown_2.18 clipr_0.8.0 callr_3.7.3
[45] ggplot2_3.4.0 purrr_0.3.5 magrittr_2.0.3 ps_1.7.2
[49] htmltools_0.5.3 scales_1.2.1 assertthat_0.2.1 colorspace_2.0-3
[53] utf8_1.2.2 munsell_0.5.0 ggfun_0.0.9 R.oo_1.25.0
</code></pre>
|
[
{
"answer_id": 74607303,
"author": "Dave2e",
"author_id": 5792244,
"author_profile": "https://Stackoverflow.com/users/5792244",
"pm_score": 1,
"selected": false,
"text": "sessionInfo()\nR version 4.2.2 (2022-10-31)\nPlatform: x86_64-apple-darwin17.0 (64-bit)\nRunning under: macOS Monterey 12.6.1\n\nMatrix products: default\nLAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib\n\nlocale:\n[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8\n\nattached base packages:\n[1] stats graphics grDevices utils datasets methods base \n\nloaded via a namespace (and not attached):\n[1] compiler_4.2.2 tools_4.2.2 \n"
},
{
"answer_id": 74607872,
"author": "Zhiqiang Wang",
"author_id": 11741943,
"author_profile": "https://Stackoverflow.com/users/11741943",
"pm_score": 1,
"selected": true,
"text": ":: ggplot2 ggimage :: library() geom_image :: ::"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11741943/"
] |
74,594,806
|
<p>I'm trying to webscrape multiple webpages of similar HTML code. I can already get the HTML of each page and I can manually find the part of the code's string where the information I need is placed - I just don't know how to properly extract it. I believe my problem might be solved with REGEX, actually, but I don't know how.</p>
<p>I'm using Python 3</p>
<p>This is how I extract the page's HTML code:</p>
<pre><code>import requests
resp = requests.get("https://statusinvest.com.br/fundos-imobiliarios/knri11",headers={'User-Agent': 'Mozilla/5.0'})
from bs4 import BeautifulSoup
soup = BeautifulSoup(resp.content, features="html.parser")
</code></pre>
<p>Below is the string of the HTML code ( code -> str(soup) ). I want to extract the list between those two pink brackets. This block is always after the line between blue parenthesis (the text in green is different at each page)
<a href="https://i.stack.imgur.com/wat4U.png" rel="nofollow noreferrer">part of page's HTML code I want to extract</a></p>
|
[
{
"answer_id": 74594827,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "beautifulsoup json import json\nimport requests\nfrom bs4 import BeautifulSoup\n\nresp = requests.get(\n \"https://statusinvest.com.br/fundos-imobiliarios/knri11\",\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n)\nsoup = BeautifulSoup(resp.content, \"html.parser\")\n\ndata = json.loads(soup.select_one(\"#results\")[\"value\"])\n\nprint(data)\n [\n {\n \"y\": 0,\n \"m\": 0,\n \"d\": 0,\n \"ad\": None,\n \"ed\": \"31/10/2022\",\n \"pd\": \"16/11/2022\",\n \"et\": \"Rendimento\",\n \"etd\": \"Rendimento\",\n \"v\": 0.91,\n \"ov\": None,\n \"sv\": \"0,91000000\",\n \"sov\": \"-\",\n \"adj\": False,\n },\n {\n \"y\": 0,\n \"m\": 0,\n \"d\": 0,\n \"ad\": None,\n \"ed\": \"30/09/2022\",\n \"pd\": \"17/10/2022\",\n \"et\": \"Rendimento\",\n \"etd\": \"Rendimento\",\n \"v\": 0.91,\n \"ov\": None,\n \"sv\": \"0,91000000\",\n \"sov\": \"-\",\n \"adj\": False,\n },\n\n\n...and so on.\n"
},
{
"answer_id": 74594899,
"author": "Leo Ward",
"author_id": 20421592,
"author_profile": "https://Stackoverflow.com/users/20421592",
"pm_score": 0,
"selected": false,
"text": "import json\nimport requests\n\nresp = requests.get(\"https://statusinvest.com.br/fundos-imobiliarios/knri11\", headers={'User-Agent': 'Mozilla/5.0'})\n\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(resp.content, features=\"html.parser\")\ndata = json.loads(soup.find(\"input\", {\"id\": \"results\"}).get(\"value\")\nprint(data)\n print(data[0][\"y\"])\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9803483/"
] |
74,594,809
|
<p>im trying to let the user input a number for each person. the console then outputs the maximum value in the array. everything works fine but the max always outputs as -858993460. i tried multiple combinations but i cant seem to figure it out</p>
<p>im new to arrays so any help would be appreciated as well as an feedback on how to improve my code</p>
<pre><code>#include <iostream>
int main()
{
int people[10];
int max = people[0];
std::cout << "please enter number of pancakes eaten by each person.\n";
//lets the user input values for each element
for (int i = 0; i < 10; ++i) {
std::cin >> people[i];
}
//outputs all the elements of the array
for (int i = 0; i < 10; ++i) {
std::cout << people[i] << " ";
}
//finds the largest element in the array
for (int i = 0; i > 10; ++i) {
if (people[i] > max) {
max = people[i];
}
}
std::cout << "\nmax: " << max;
return 0;
}
</code></pre>
<p>also i keep getting a warning saying: ill-defined for-loop. loop body not executed. i tried looking this warning up but the warning seems very broad and i couldnt find anything that helped</p>
|
[
{
"answer_id": 74594856,
"author": "Sam Varshavchik",
"author_id": 3943312,
"author_profile": "https://Stackoverflow.com/users/3943312",
"pm_score": 3,
"selected": true,
"text": "int people[10];\n int int max = people[0];\n max people people max max"
},
{
"answer_id": 74594857,
"author": "wigi426",
"author_id": 12518633,
"author_profile": "https://Stackoverflow.com/users/12518633",
"pm_score": 0,
"selected": false,
"text": "int max = people[0] int max = people[0]"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410786/"
] |
74,594,830
|
<p>In a weather application on which I'm working I have three components, one <code>App.js</code> component which holds the other two components (<code>search.js</code> and <code>Main.js</code>). User searches the city, and <code>main.js</code> components display the relevant weather data.</p>
<p>Now I want to change the background dynamically for the full screen but for that, I need to access the API-data function in my <code>App.js</code> component, which will provide the icon id then I can change the background, but I am confused now about how to do? I have attached the code below.</p>
<p>Component App.js</p>
<pre><code>import React, { useState } from "react";
import "./App.css";
import Maindata from "./Components/Maindata";
import Search from "./Components/Search";
function App() {
const [location, setLocation] = useState();
return (
<div className="mainpage"
style={{
backgroundImage: `url("./pics/01n.jpg")`,
backgroundSize: "cover",
}}
>
<div className="searchComp">
<Search {...{ location, setLocation }} />
</div>
<Maindata city={location} />
</div>
);
}
export default App;
</code></pre>
<p>Search.js</p>
<pre><code>import React, { useState } from "react";
import "../Componentstyle/search.css";
export default function Search({ setLocation }) {
const [city, setCity] = useState("");
const handlesubmit = (e) => {
e.preventDefault();
setLocation(city );
};
return (
<div className="main">
<nav className="istclass">
<form className="form" onSubmit={handlesubmit}>
<div className="search">
<input
value={city}
placeholder="Search your location..."
className="searchbox"
onChange={(e) => setCity(e.target.value)}
/>
<button className="nd" type="button" onClick={handlesubmit}>
<i class="fa fa-search" aria-hidden="true"></i>
</button>
</div>
</form>
</nav>
</div>
);
}
</code></pre>
<p>Main. jsx</p>
<pre><code>import React, { useState, useEffect } from "react";
// import Time from "./Time";
import moment from "moment";
import "../Componentstyle/Main.css";
export default function Maindata({ city = "mansehra" }) {
const [data, setData] = useState();
const [cityvalid, setCityvalid] = useState(false);
const Dweather = async (city) => {
const key = "24f4cabc9b1a10af6e3eeb4cc150a9ef";
await fetch(
`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${key}&units=metric&formatted=0`
)
.then((response) => response.json())
.then((actualData) => {
if (actualData.city) {
setCityvalid(true);
setData(actualData);
} else {
setCityvalid(false);
}
});
};
useEffect(() => {
Dweather(city);
}, [city]);
if (!data) {
return <div>Loading...</div>;
}
// if (!data.weather) {
// return <div>City "{city}" not recognized</div>;
// }
const icons = `./icons/${data.list[0].weather[0].icon}.svg`;
const icond1 = `./icons/${data.list[7].weather[0].icon}.svg`;
const icond2 = `./icons/${data.list[15].weather[0].icon}.svg`;
const icond3 = `./icons/${data.list[23].weather[0].icon}.svg`;
const icond4 = `./icons/${data.list[31].weather[0].icon}.svg`;
const icond5 = `./icons/${data.list[39].weather[0].icon}.svg`;
const sunrise = data.city.sunrise;
const sunset = data.city.sunset;
const timezone = data.city.timezone;
return (
<>
<div
className="newpage"
style={{
// backgroundImage: `url("./pics/${data.list[0].weather[0].icon}.jpg")`,
// backgroundSize: "cover",
flexWrap: "wrap",
padding: "1% 10% 0 10%",
height: "53rem",
}}
>
<div className="city">
<span className="name">{data.city.name}</span>
<br />
<span className="citydate">
{moment
.utc(new Date().setTime(data.list[0].dt * 1000))
.add(timezone, "seconds")
.format("dddd, MMMM Do YYYY, ")}
</span>
</div>
<div className="maindata">
{/* {!cityValid && <span>City "{city}" not found</span>} */}
<div className="temper">
<img src={icons} alt="not found" />
<div className="temp">
<span className="display">
{" "}
{data.list[0].main.temp.toFixed(1)}&deg;
</span>{" "}
<br />{" "}
<span className="display1">
{" "}
{data.list[0].weather[0].description}
</span>
</div>
</div>
<div className="icon">
{/* <img src={link} alt="not found" />{" "} */}
<div className="acloudy">
<span className="icon1">
{data.list[0].main.temp_max.toFixed(1)} C&deg;
</span>{" "}
<br /> <span className="icon2">High </span>
</div>
<div className="bcloudy">
<span className="icon1">
{" "}
{data.list[0].wind.speed.toFixed()} Km/h
</span>{" "}
<br /> <span className="icon2">Wind Speed</span>
</div>
<div className="ccloudy">
<span className="icon1">
{moment
.utc(sunrise, "X")
.add(timezone, "seconds")
.format("h:mm a")}{" "}
</span>
<br />
<span className="icon2">Sunrise</span>
</div>
<div className="dcloudy">
<span className="icon1">
{data.list[0].main.temp_min.toFixed(1)} C&deg;
</span>{" "}
<br /> <span className="icon2">Low</span>
</div>
<div className="ecloudy">
<span className="icon1">{data.list[0].main.humidity}%</span>{" "}
<br /> <span className="icon2">Humadity</span>
</div>
<div className="fcloudy">
<span className="icon1">
{moment
.utc(sunset, "X")
.add(timezone, "seconds")
.format("h:mm a")}{" "}
</span>
<br /> <span className="icon2">Sunset</span>
</div>
</div>
</div>
<div className="dailyweather">
<div className="day">
<span className="wday">
{moment(new Date().setTime(data.list[7].dt * 1000)).format("ddd")}
</span>
<br /> <img src={icond1} alt="not found" />
<br />
<span className="head">Temp </span>{" "}
<span className="val">
{data.list[7].main.temp.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Feel like </span>{" "}
<span className="val">
{data.list[7].main.feels_like.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Moist </span>{" "}
<span className="val">
{data.list[7].main.humidity.toFixed()} %
</span>{" "}
<br />
<br />
<span className="head">{data.list[7].weather[0].main}</span>
</div>
<div className="day">
<span className="wday">
{moment(new Date().setTime(data.list[15].dt * 1000)).format(
"ddd"
)}
</span>{" "}
<br />
<img src={icond2} alt="not found" />
<br /> <span className="head">Temp </span>{" "}
<span className="val">
{data.list[15].main.temp.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Feel like </span>{" "}
<span className="val">
{data.list[15].main.feels_like.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Moist</span>{" "}
<span className="val">
{" "}
{data.list[15].main.humidity.toFixed()} %
</span>{" "}
<br />
<br />
<span className="head">{data.list[15].weather[0].main}</span>
</div>
<div className="day">
<span className="wday">
{moment(new Date().setTime(data.list[23].dt * 1000)).format(
"ddd"
)}
</span>
<br /> <img src={icond3} alt="not found" />
<br /> <span className="head">Temp</span>{" "}
<span className="val">
{" "}
{data.list[23].main.temp.toFixed(1)} C&deg;
</span>
<br /> <br />
<span className="head">Feel like </span>{" "}
<span className="val">
{data.list[23].main.feels_like.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Moist </span>{" "}
<span className="val">
{data.list[23].main.humidity.toFixed()} %
</span>{" "}
<br />
<br />
<span className="head">{data.list[23].weather[0].main}</span>
</div>
<div className="day">
<span className="wday">
{moment(new Date().setTime(data.list[31].dt * 1000)).format(
"ddd"
)}
</span>{" "}
<br /> <img src={icond4} alt="not found" />
<br /> <span className="head">Temp</span>{" "}
<span className="val">
{" "}
{data.list[31].main.temp.toFixed(1)} C&deg;
</span>
<br /> <br />
<span className="head">Feel like </span>{" "}
<span className="val">
{data.list[31].main.feels_like.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Moist </span>{" "}
<span className="val">
{data.list[31].main.humidity.toFixed()} %
</span>{" "}
<br />
<br />
<span className="head">{data.list[31].weather[0].main}</span>
</div>
<div className="day">
<span className="wday">
{moment(new Date().setTime(data.list[39].dt * 1000)).format(
"ddd"
)}
</span>
<br />
<img src={icond5} alt="not found" />
<br /> <span className="head">Temp </span>{" "}
<span className="val">
{data.list[39].main.temp.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Feel like </span>{" "}
<span className="val">
{data.list[39].main.feels_like.toFixed(1)} C&deg;
</span>{" "}
<br />
<br />
<span className="head">Moist </span>{" "}
<span className="val">
{data.list[39].main.humidity.toFixed()} %
</span>{" "}
<br />
<br />
<span className="head">{data.list[39].weather[0].main}</span>
</div>
</div>
</div>
</>
);
}
</code></pre>
|
[
{
"answer_id": 74594860,
"author": "m_wb",
"author_id": 20617744,
"author_profile": "https://Stackoverflow.com/users/20617744",
"pm_score": 0,
"selected": false,
"text": "useDispatch"
},
{
"answer_id": 74595148,
"author": "George",
"author_id": 4375751,
"author_profile": "https://Stackoverflow.com/users/4375751",
"pm_score": 0,
"selected": false,
"text": "useContext"
},
{
"answer_id": 74618795,
"author": "yousoumar",
"author_id": 15288641,
"author_profile": "https://Stackoverflow.com/users/15288641",
"pm_score": 1,
"selected": false,
"text": "props setBackgroundImageURL App Maindata App function App() {\n const [location, setLocation] = useState();\n const [backgroundImageURL, setBackgroundImageURL] = useState(\"/pics/01n.jpg\");\n\n return (\n <div\n className=\"mainpage\"\n style={{\n backgroundImage: `url(${backgroundImageURL})`,\n backgroundSize: \"cover\",\n }}\n >\n <div className=\"searchComp\">\n <Search {...{ location, setLocation }} />\n </div>\n\n <Maindata city={location} setBackgroundImageURL={setBackgroundImageURL} />\n </div>\n );\n}\n\nexport default App;\n export default function Maindata({ city = \"mansehra\", setBackgroundImageURL }) {\n //....\n const icons = `./icons/${data.list[0].weather[0].icon}.svg`;\n setBackgroundImageURL(icons);\n //....\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16762504/"
] |
74,594,834
|
<p>I have a design where I have 3 items. 2 items should be placed vertically and 1 item has to be in it's own cell. So, 2 items should be placed in 1 cell vertically and 1 item takes it's own whole cell. To demonstrate, below is the image</p>
<p><a href="https://i.stack.imgur.com/n9i7X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n9i7X.png" alt="enter image description here" /></a></p>
<p>How can I achieve this design using tailwind?</p>
|
[
{
"answer_id": 74594956,
"author": "ChenBr",
"author_id": 17718587,
"author_profile": "https://Stackoverflow.com/users/17718587",
"pm_score": 1,
"selected": false,
"text": "grid flex grid-cols-3 grid-rows-2 col-span-n row-span-n grid-cols grid-row <div class=\"border-2 grid grid-cols-3 grid-rows-2\">\n <div class=\"border-2 col-span-1\">1</div>\n <div class=\"border-2 col-span-2 row-span-2\">2</div>\n <div class=\"border-2 col-span-1\">3</div>\n<div>\n flex flex-col flex-row w-[30%] w-[70%] <div class=\"flex border-2\">\n <div class=\"flex w-[30%] flex-col\">\n <div class=\"border-2\">1</div>\n <div class=\"border-2\">2</div>\n </div>\n <div class=\"w-[70%] border-2\">3</div>\n <div></div>\n</div>\n"
},
{
"answer_id": 74598345,
"author": "Ihar Aliakseyenka",
"author_id": 14305076,
"author_profile": "https://Stackoverflow.com/users/14305076",
"pm_score": 3,
"selected": true,
"text": "<div class=\"border-2 grid grid-cols-3 grid-rows-2\">\n <div class=\"border-2 col-span-1\">1</div>\n <div class=\"border-2 col-span-2 row-span-2\">2</div>\n <div class=\"border-2 col-span-1\">3</div>\n<div>\n grid-rows-2 .grid-rows-2 {\n grid-template-rows: repeat(2, minmax(0, 1fr));\n}\n 1fr grid-rows-[min-content_1fr] <div class=\"grid grid-cols-3 grid-rows-[min-content_1fr]\">\n <div>1</div>\n <div class=\"col-span-2 row-span-2\">2</div>\n <div>3</div>\n<div>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19313557/"
] |
74,594,844
|
<p>I have read multiple posts about how to instantiate one object of the type of the inner class after instantiating one from the outer class; for example: <a href="https://stackoverflow.com/questions/29530354/how-to-instantiate-multiple-nested-non-static-inner-classes-java">here</a> and <a href="https://stackoverflow.com/questions/29530354/how-to-instantiate-multiple-nested-non-static-inner-classes-java">here</a>.<br />
However, non of them actually explain if you can have multiple instances of the inner class with a single outer class instance and, if so, what the use cases are.</p>
<p>For example, would it be beneficial to have a controller/handler class be an outer class and the class we want to handle the inner class? What are the pros and cons of this or similar approaches with not one but multiple instances of the inner classes over the pillars of OOP (using inheritance, abstraction, polymorphism, and encapsulation)?<br />
I am specifically asking about multiple instances; all of this is covered for single objects of the inner classes <a href="https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class?rq=1">here</a>.</p>
<p>ps* all of the links are StackOverflow questions.</p>
|
[
{
"answer_id": 74595134,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 0,
"selected": false,
"text": "interator Iterable public class MyDataDemo {\n public static void main(String[] args) {\n MyDataStructure<Integer> mds = new MyDataStructure<>(new Integer[] {1,2,3,4,5});\n\n for(int val :mds) {\n System.out.println(val);\n }\n System.out.println();\n \n // or via an iterator instance.\n Iterator<Integer> iter = mds.iterator();\n while(iter.hasNext()) {\n System.out.println(iter.next());\n }\n }\n}\n\n\nclass MyDataStructure<T> implements Iterable<T> {\n private T[] values;\n public MyDataStructure(T[] values) {\n this.values = values;\n }\n \n public class MyIterator implements Iterator<T>{\n int index = 0;\n @Override\n public boolean hasNext() {\n return index < values.length;\n }\n \n @Override\n public T next() {\n return values[index++];\n }\n }\n \n \n @Override\n public Iterator<T> iterator() {\n return new MyIterator();\n }\n\n}\n 1\n2\n3\n4\n5\n\n1\n2\n3\n4\n5\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7334828/"
] |
74,594,909
|
<p>I'm sorry if the tittle is a bit confusing.</p>
<p>I have an array-sorting webapp in Blazor.</p>
<p>This is the important piece of code:</p>
<pre><code><MudButton OnClick="Sort" Disabled="Sorting" Variant="Variant.Outlined" >Sort</MudButton>
<MudButton OnClick="Accelerate" Disabled="@(!Sorting)" Variant="Variant.Outlined">Finish</MudButton>
@code{
public bool Sorting { get; set; } = false;
public bool Accelerating { get; set; } = default!;
public void Sort()
{
Sorting = true;
Bubble();
}
public void Accelerate()
{
Accelerating = true;
}
public async void Bubble()
{
while (!IsSorted(List))
{
//algorithm
StateHasChanged();
if (!Accelerating)
{
await Task.Delay((Speed - MAX_SPEED) * -1 == 0 ? 1 : (Speed - MAX_SPEED) * -1);
}
}
Sorting = false;
Accelerating = false;
StateHasChanged();
}
}
</code></pre>
<p>The sorting part works just fine.
When I click the Accelerate button the await Task.Delay should be skipped.
But when I do, the whole application freezes like this:</p>
<p><a href="https://i.stack.imgur.com/YDUOI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YDUOI.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/sfPYp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sfPYp.png" alt="enter image description here" /></a></p>
<p>It won't respond. Nothing in console.</p>
<p>Where is the problem? Thanks</p>
|
[
{
"answer_id": 74595008,
"author": "Jim G.",
"author_id": 109941,
"author_profile": "https://Stackoverflow.com/users/109941",
"pm_score": 0,
"selected": false,
"text": "Accelerating = false;\n"
},
{
"answer_id": 74595166,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 2,
"selected": false,
"text": "Accelerating true Accelerating true"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74594909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16032218/"
] |
74,595,012
|
<p>I have the following two dataframes. I'm trying to combine the two using a <code>left_join</code> by <code>Key</code>, however I'm getting an error</p>
<pre><code>df <- structure(list(Key = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L,
6L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L,
10L, 10L, 11L, 11L, 11L, 11L), levels = c("GC23", "GC24", "GC25",
"GC26", "GC27", "GC28", "GC30", "GC35", "GC45", "GC48", "GC50"
), class = "factor"), Quartile = structure(c(1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), levels = c("1", "2", "3", "4"
), class = "factor"), min = c(0.800000000000001, 70.2, 102.9,
124.4, -108.1, -0.200000000000067, 63.2, 124.4, -70.9999999999999,
5.29999999999999, 67.0999999999999, 144.3, -52.1000000000001,
16, 37.1, 51.6999999999999, -19.2, 75.0999999999999, 92.7999999999999,
161.8, -45.5, -3.80000000000003, 12.7000000000001, 31.3000000000001,
3.30000000000013, 107.9, 120.2, 143.4, 29.7000000000001, 102.1,
138.3, 172.3, 83.9, 183.6, 216.6, 240.3, 202.1, 258.6, 290.9,
321.9, 107.5, 201.1, 247.1, 290.1), max = c(70.1, 102.8, 124.3,
342.6, -0.200000000000067, 63.1, 124.4, 190.2, 4.79999999999992,
67.0999999999999, 144.2, 209.7, 16, 37.1, 51.3999999999999, 131.7,
75, 92.7000000000001, 161.3, 250.3, -4.70000000000006, 12.5999999999999,
30.1, 62.9, 107.8, 119.8, 143.2, 192.3, 102, 138.2, 172.3, 258,
183.5, 216.6, 240.3, 349.4, 258.5, 290.9, 321.9, 374.5, 201.1,
247, 289.6, 400.9)), row.names = c(NA, -44L), class = c("tbl_df",
"tbl", "data.frame"))
df2 <- structure(list(Key = structure(1:11, levels = c("GC23", "GC24",
"GC25", "GC26", "GC27", "GC28", "GC30", "GC35", "GC45", "GC48",
"GC50"), class = "factor"), Quartile = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = "Today", class = "factor"),
min = c(131.8, -47.2, -12.2, 36.1000000000001, 67.3, 27.4999999999999,
119, 133, 235.3, 287.6, 303.3), max = c(131.8, -47.2, -12.2,
36.1000000000001, 67.3, 27.4999999999999, 119, 133, 235.3,
287.6, 303.3)), row.names = c(NA, -11L), class = c("tbl_df",
"tbl", "data.frame"))
left_join(df,df2, by = Key)
</code></pre>
<pre><code>Error in standardise_join_by(by, x_names = x_names, y_names = y_names, :
object 'Key' not found
</code></pre>
<p>Is there any way around this issue?</p>
|
[
{
"answer_id": 74595008,
"author": "Jim G.",
"author_id": 109941,
"author_profile": "https://Stackoverflow.com/users/109941",
"pm_score": 0,
"selected": false,
"text": "Accelerating = false;\n"
},
{
"answer_id": 74595166,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 2,
"selected": false,
"text": "Accelerating true Accelerating true"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388534/"
] |
74,595,039
|
<p>I have a nested list like this: datelist = [["2019/04/12", 7.0], ["2019/02/09", 7.3], ["2018/08/14", 6.1]]
I need to change the date format from yyyy/mm/dd/ to yyyy.mm.dd and then return the list as it is.
So the result should be [["12.04.2019", 7.0], ["09.02.2019", 7.3], ["14.08.2018", 6.1]].</p>
<p>I'm a beginner, so I'm really not sure how to do it.</p>
<p>I tried the following:</p>
<pre><code>import datetime
datelist = [datetime.datetime.strptime(str(i[0]), "%Y/%m/%d").strftime('%d.%m.%Y') for i in datelist]
print(datelist)
</code></pre>
<p>and the output was:</p>
<p>['12.04.2019', '09.02.2019', '14.08.2016']</p>
<p>So the change of the data format worked, but how do I return the the original nested list with the corrected data format?</p>
<p>I need to implement this as a function which takes lists like datelist as an input.</p>
|
[
{
"answer_id": 74595008,
"author": "Jim G.",
"author_id": 109941,
"author_profile": "https://Stackoverflow.com/users/109941",
"pm_score": 0,
"selected": false,
"text": "Accelerating = false;\n"
},
{
"answer_id": 74595166,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 2,
"selected": false,
"text": "Accelerating true Accelerating true"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618564/"
] |
74,595,074
|
<p>My code looks like this</p>
<pre><code>let! statementData = page.EvaluateAsync("() => this.window._StatementLinesData")
let sValue =
JObject.Parse(statementData.Value.GetRawText()).Last.Last
|> (fun item -> item.Children() )
|> Seq.map(fun item -> item.ToObject<StatementLine>())
</code></pre>
<p>Is it possible to make those 2 into one statement without using .Result?</p>
|
[
{
"answer_id": 74595142,
"author": "Abel",
"author_id": 111575,
"author_profile": "https://Stackoverflow.com/users/111575",
"pm_score": 0,
"selected": false,
"text": "page.EvaluateAsync(\"() => this.window._StatementLinesData\").Result\n|> fun x -> JObject.Parse(x.Value.GetRawText()).Last.Last\n|> fun item -> item.Children()\n|> Seq.map(fun item -> item.ToObject<StatementLine>())\n .Result task Task.map"
},
{
"answer_id": 74597673,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 2,
"selected": true,
"text": "|> item let! statementData = page.EvaluateAsync(\"() => this.window._StatementLinesData\")\nlet item = JObject.Parse(statementData.Value.GetRawText()).Last.Last\nreturn item.Children() |> Seq.map(fun item -> item.ToObject<StatementLine>())\n let! Result map module Task =\n let map f (t:Task<_>) = task { \n let! r = t\n return f r }\n |> map page.EvaluateAsync(\"() => this.window._StatementLinesData\")\n|> Task.map (fun statementData ->\n JObject.Parse(statementData.Value.GetRawText()).Last.Last\n |> (fun item -> item.Children() )\n |> Seq.map(fun item -> item.ToObject<StatementLine>())) \n |>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4537346/"
] |
74,595,102
|
<p>Getting multiple errors while archiving the project but app build/run fine. Tried many solutions related to cleaning derived data, deintegrate/integrate/install pods, pod clean etc.(<a href="https://stackoverflow.com/questions/66809424/googleutilities-gulurlsessiondataresponse-h-file-not-found">'GoogleUtilities/GULURLSessionDataResponse.h' file not found</a>) (<a href="https://github.com/firebase/firebase-ios-sdk/issues/2233" rel="nofollow noreferrer">https://github.com/firebase/firebase-ios-sdk/issues/2233</a>)</p>
<p><a href="https://i.stack.imgur.com/EBkkV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EBkkV.png" alt="enter image description here" /></a></p>
<p>Podfile :</p>
<pre><code>
source 'https://github.com/CocoaPods/Specs.git'
install! 'cocoapods', :deterministic_uuids => false
target 'Test' do
platform :ios, '14.3'
use_frameworks!
inhibit_all_warnings!
pod 'SwiftLint'
pod 'KeychainAccess'
pod 'AEXML'
pod 'GooglePlaces'
pod 'Firebase/Analytics'
pod 'Firebase/Crashlytics'
pod 'Firebase/RemoteConfig'
pod 'CocoaDebug', :configurations => ['Debug']
pod 'atlantis-proxyman'
target 'TestTests' do
inherit! :search_paths
end
end
</code></pre>
<p>Podfile.lock</p>
<pre><code>
PODS:
- AEXML (4.6.1)
- atlantis-proxyman (1.20.0)
- CocoaDebug (1.7.2)
- Firebase/Analytics (10.2.0):
- Firebase/Core
- Firebase/Core (10.2.0):
- Firebase/CoreOnly
- FirebaseAnalytics (~> 10.2.0)
- Firebase/CoreOnly (10.2.0):
- FirebaseCore (= 10.2.0)
- Firebase/Crashlytics (10.2.0):
- Firebase/CoreOnly
- FirebaseCrashlytics (~> 10.2.0)
- Firebase/RemoteConfig (10.2.0):
- Firebase/CoreOnly
- FirebaseRemoteConfig (~> 10.2.0)
- FirebaseABTesting (10.2.0):
- FirebaseCore (~> 10.0)
- FirebaseAnalytics (10.2.0):
- FirebaseAnalytics/AdIdSupport (= 10.2.0)
- FirebaseCore (~> 10.0)
- FirebaseInstallations (~> 10.0)
- GoogleUtilities/AppDelegateSwizzler (~> 7.8)
- GoogleUtilities/MethodSwizzler (~> 7.8)
- GoogleUtilities/Network (~> 7.8)
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- nanopb (< 2.30910.0, >= 2.30908.0)
- FirebaseAnalytics/AdIdSupport (10.2.0):
- FirebaseCore (~> 10.0)
- FirebaseInstallations (~> 10.0)
- GoogleAppMeasurement (= 10.2.0)
- GoogleUtilities/AppDelegateSwizzler (~> 7.8)
- GoogleUtilities/MethodSwizzler (~> 7.8)
- GoogleUtilities/Network (~> 7.8)
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- nanopb (< 2.30910.0, >= 2.30908.0)
- FirebaseCore (10.2.0):
- FirebaseCoreInternal (~> 10.0)
- GoogleUtilities/Environment (~> 7.8)
- GoogleUtilities/Logger (~> 7.8)
- FirebaseCoreInternal (10.2.0):
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- FirebaseCrashlytics (10.2.0):
- FirebaseCore (~> 10.0)
- FirebaseInstallations (~> 10.0)
- GoogleDataTransport (~> 9.2)
- GoogleUtilities/Environment (~> 7.8)
- nanopb (< 2.30910.0, >= 2.30908.0)
- PromisesObjC (~> 2.1)
- FirebaseInstallations (10.2.0):
- FirebaseCore (~> 10.0)
- GoogleUtilities/Environment (~> 7.8)
- GoogleUtilities/UserDefaults (~> 7.8)
- PromisesObjC (~> 2.1)
- FirebaseRemoteConfig (10.2.0):
- FirebaseABTesting (~> 10.0)
- FirebaseCore (~> 10.0)
- FirebaseInstallations (~> 10.0)
- GoogleUtilities/Environment (~> 7.8)
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- GoogleAppMeasurement (10.2.0):
- GoogleAppMeasurement/AdIdSupport (= 10.2.0)
- GoogleUtilities/AppDelegateSwizzler (~> 7.8)
- GoogleUtilities/MethodSwizzler (~> 7.8)
- GoogleUtilities/Network (~> 7.8)
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- nanopb (< 2.30910.0, >= 2.30908.0)
- GoogleAppMeasurement/AdIdSupport (10.2.0):
- GoogleAppMeasurement/WithoutAdIdSupport (= 10.2.0)
- GoogleUtilities/AppDelegateSwizzler (~> 7.8)
- GoogleUtilities/MethodSwizzler (~> 7.8)
- GoogleUtilities/Network (~> 7.8)
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- nanopb (< 2.30910.0, >= 2.30908.0)
- GoogleAppMeasurement/WithoutAdIdSupport (10.2.0):
- GoogleUtilities/AppDelegateSwizzler (~> 7.8)
- GoogleUtilities/MethodSwizzler (~> 7.8)
- GoogleUtilities/Network (~> 7.8)
- "GoogleUtilities/NSData+zlib (~> 7.8)"
- nanopb (< 2.30910.0, >= 2.30908.0)
- GoogleDataTransport (9.2.0):
- GoogleUtilities/Environment (~> 7.7)
- nanopb (< 2.30910.0, >= 2.30908.0)
- PromisesObjC (< 3.0, >= 1.2)
- GooglePlaces (7.2.0)
- GoogleUtilities/AppDelegateSwizzler (7.10.0):
- GoogleUtilities/Environment
- GoogleUtilities/Logger
- GoogleUtilities/Network
- GoogleUtilities/Environment (7.10.0):
- PromisesObjC (< 3.0, >= 1.2)
- GoogleUtilities/Logger (7.10.0):
- GoogleUtilities/Environment
- GoogleUtilities/MethodSwizzler (7.10.0):
- GoogleUtilities/Logger
- GoogleUtilities/Network (7.10.0):
- GoogleUtilities/Logger
- "GoogleUtilities/NSData+zlib"
- GoogleUtilities/Reachability
- "GoogleUtilities/NSData+zlib (7.10.0)"
- GoogleUtilities/Reachability (7.10.0):
- GoogleUtilities/Logger
- GoogleUtilities/UserDefaults (7.10.0):
- GoogleUtilities/Logger
- KeychainAccess (4.2.2)
- nanopb (2.30909.0):
- nanopb/decode (= 2.30909.0)
- nanopb/encode (= 2.30909.0)
- nanopb/decode (2.30909.0)
- nanopb/encode (2.30909.0)
- PromisesObjC (2.1.1)
- SwiftLint (0.50.1)
DEPENDENCIES:
- AEXML
- atlantis-proxyman
- CocoaDebug
- Firebase/Analytics
- Firebase/Crashlytics
- Firebase/RemoteConfig
- GooglePlaces
- KeychainAccess
- SwiftLint
SPEC REPOS:
https://github.com/CocoaPods/Specs.git:
- AEXML
- atlantis-proxyman
- CocoaDebug
- Firebase
- FirebaseABTesting
- FirebaseAnalytics
- FirebaseCore
- FirebaseCoreInternal
- FirebaseCrashlytics
- FirebaseInstallations
- FirebaseRemoteConfig
- GoogleAppMeasurement
- GoogleDataTransport
- GooglePlaces
- GoogleUtilities
- KeychainAccess
- nanopb
- PromisesObjC
- SwiftLint
SPEC CHECKSUMS:
AEXML: 1e255ecc6597212f97a7454a69ebd3ede64ac1cf
atlantis-proxyman: c3ca06216fbb5cf87a83de3911f955dcb1615048
CocoaDebug: 61cf93ada6ce8f3407507dc01f9b874d91ac1d5c
Firebase: a3ea7eba4382afd83808376edb99acdaff078dcf
FirebaseABTesting: 22840e1573ea2fbb519f5a2f1c93be7232508358
FirebaseAnalytics: 24a15e58e505abcedc3017b6f7c206fbfa964580
FirebaseCore: 813838072b797b64f529f3c2ee35e696e5641dd1
FirebaseCoreInternal: 091bde13e47bb1c5e9fe397634f3593dc390430f
FirebaseCrashlytics: df7406152189d48346deafb716806d7bd9ebb573
FirebaseInstallations: 004915af170935e3a583faefd5f8bc851afc220f
FirebaseRemoteConfig: 5bdeadd64a042dad0f6a38fee7e017818240c3d2
GoogleAppMeasurement: 3bc3a6484b7bb20dd8489242c4dd3c92a3e5107b
GoogleDataTransport: 1c8145da7117bd68bbbed00cf304edb6a24de00f
GooglePlaces: 590dea495d69431454ea92217033c3184995165d
GoogleUtilities: bad72cb363809015b1f7f19beb1f1cd23c589f95
KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51
nanopb: b552cce312b6c8484180ef47159bc0f65a1f0431
PromisesObjC: ab77feca74fa2823e7af4249b8326368e61014cb
SwiftLint: 6b0cf1f4d619808dbc16e4fab064ce6fc79f090b
PODFILE CHECKSUM: 330733d16ffa7f8b7749843d82f340e9c137b794
COCOAPODS: 1.11.3
</code></pre>
|
[
{
"answer_id": 74595142,
"author": "Abel",
"author_id": 111575,
"author_profile": "https://Stackoverflow.com/users/111575",
"pm_score": 0,
"selected": false,
"text": "page.EvaluateAsync(\"() => this.window._StatementLinesData\").Result\n|> fun x -> JObject.Parse(x.Value.GetRawText()).Last.Last\n|> fun item -> item.Children()\n|> Seq.map(fun item -> item.ToObject<StatementLine>())\n .Result task Task.map"
},
{
"answer_id": 74597673,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 2,
"selected": true,
"text": "|> item let! statementData = page.EvaluateAsync(\"() => this.window._StatementLinesData\")\nlet item = JObject.Parse(statementData.Value.GetRawText()).Last.Last\nreturn item.Children() |> Seq.map(fun item -> item.ToObject<StatementLine>())\n let! Result map module Task =\n let map f (t:Task<_>) = task { \n let! r = t\n return f r }\n |> map page.EvaluateAsync(\"() => this.window._StatementLinesData\")\n|> Task.map (fun statementData ->\n JObject.Parse(statementData.Value.GetRawText()).Last.Last\n |> (fun item -> item.Children() )\n |> Seq.map(fun item -> item.ToObject<StatementLine>())) \n |>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6488746/"
] |
74,595,103
|
<p>I'm new to Flutter and I have to make a list of rules where every item in the list is green and if you break a rule you can press it and change the color to red. I also have to have extensible.
I also have to have extensible. In my implementation from the YouTube tutorial, I saw that I used <code>.map()</code> to map the items in the list, but now when I have to press and change the color, all items change, not just one.</p>
<p>Any ideas how to fix this?</p>
<pre><code>class _MyHomePageState extends State<MyHomePage> {
bool isSelected = true;
static const lawText =
' example text of the laws that are going to be implemented inside here. This is only to fill out the space at the moment';
final List<Item> items = [
Item(header: 'Law 1 ' , body: lawText),
Item(header: 'Law 2 ' , body: lawText),
Item(header: 'Law 3 ' , body: lawText),
Item(header: 'Law 4 ' , body: lawText),
Item(header: 'Law 5 ' , body: lawText),
];
@override
Widget build(BuildContext context) => Scaffold(
drawer: NavBar(),
appBar: AppBar(
title: Text('§ Regel'),
centerTitle: true,
),
body: SingleChildScrollView(
//crossAxisAlignment : crossAxisAlignment,
child:ExpansionPanelList(
expansionCallback: (index, isExpanded) {
setState(() => items[index].isExpanded = !isExpanded);
},
children: items
.map((item) => ExpansionPanel(
isExpanded: item.isExpanded,
headerBuilder:(context, isExpanded) => ListTile(
tileColor: isSelected ? Colors.green : Colors.red,
onTap: () => setState(() => isSelected = !isSelected),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
title:Text(
item.header,
style: TextStyle(fontSize: 20),
),
),
body: ListTile(
title: Text(item.body, style: TextStyle(fontSize: 20) ),
//tileColor: Colors.lightGreen,
//onTap: () => setState(() => isSelected = !isSelected),
),
))
.toList(),
),
),
);
}
class Item {
final String header;
final String body;
bool isExpanded;
Item({
required this.header,
required this.body,
this.isExpanded = false,
});
}
</code></pre>
<p><img src="https://i.stack.imgur.com/eqUkL.png" alt="Image" /><img src="https://i.stack.imgur.com/JHbn2.png" alt="Image" /></p>
<p>I try to do everything with <code>ListTile</code> instead of normal list.
I also tried using <code>elementAt(index)</code> but it didn't work.</p>
|
[
{
"answer_id": 74595142,
"author": "Abel",
"author_id": 111575,
"author_profile": "https://Stackoverflow.com/users/111575",
"pm_score": 0,
"selected": false,
"text": "page.EvaluateAsync(\"() => this.window._StatementLinesData\").Result\n|> fun x -> JObject.Parse(x.Value.GetRawText()).Last.Last\n|> fun item -> item.Children()\n|> Seq.map(fun item -> item.ToObject<StatementLine>())\n .Result task Task.map"
},
{
"answer_id": 74597673,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 2,
"selected": true,
"text": "|> item let! statementData = page.EvaluateAsync(\"() => this.window._StatementLinesData\")\nlet item = JObject.Parse(statementData.Value.GetRawText()).Last.Last\nreturn item.Children() |> Seq.map(fun item -> item.ToObject<StatementLine>())\n let! Result map module Task =\n let map f (t:Task<_>) = task { \n let! r = t\n return f r }\n |> map page.EvaluateAsync(\"() => this.window._StatementLinesData\")\n|> Task.map (fun statementData ->\n JObject.Parse(statementData.Value.GetRawText()).Last.Last\n |> (fun item -> item.Children() )\n |> Seq.map(fun item -> item.ToObject<StatementLine>())) \n |>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618742/"
] |
74,595,105
|
<p>I need to find the first 16 multiples of 2 starting with 2. Then find the product in the next line like this. I need to use for loops only.</p>
<p>Sample output: 2 4 6 8 10 12 ...</p>
<p>The product is ______</p>
<p>I tried this. For loops only.</p>
<pre><code>import java.util.Scanner;
public class Program30
{
public static void main(String args[]) {
int a,b;
b=2*4*6*10*12*14*16*18*20*22*24*26*28*30*32;
for(int x=1;x<=16;x++) {
a=2*x;
System.out.print(a+" ");
}
System.out.println("\nThe product is "+b);
}
}
</code></pre>
<p>Is there a better way to do this? Thank you.</p>
|
[
{
"answer_id": 74595209,
"author": "Anon",
"author_id": 20460294,
"author_profile": "https://Stackoverflow.com/users/20460294",
"pm_score": 2,
"selected": false,
"text": " public static void main(String[] args) {\n long a;\n long b = 1L;\n for (int x = 1; x <= 16; x++) {\n a = 2L * x;\n b *= a;\n System.out.print(a + \" \");\n }\n System.out.println(\"\\nThe product is \" + b);\n }\n"
},
{
"answer_id": 74595270,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 1,
"selected": false,
"text": "a b ints a 1 b=2*4*6*10*12*14*16*18*20*22*24*26*28*30*32; 2L b=2L*4*6*8*10*12*14*16*18*20*22*24*26*28*30*32; 8 a = 2*x; a = a * 2*x public static void main(String args[]) {\n long a = 1,b;\n b=2L*4*6*8*10*12*14*16*18*20*22*24*26*28*30*32;\n for(int x=1;x<=16;x++) {\n a = a *2*x;\n System.out.println(a+\" \"); \n }\n System.out.println(\"\\nThe product for a is \"+a);\n System.out.println(\"\\nThe product for b is \"+b);\n}\n 2 \n8 \n48 \n384 \n3840 \n46080 \n645120 \n10321920 \n185794560 \n3715891200 \n81749606400 \n1961990553600 \n51011754393600 \n1428329123020800 \n42849873690624000 \n1371195958099968000 \n\nThe product for a is 1371195958099968000\n\nThe product for b is 1371195958099968000\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618720/"
] |
74,595,146
|
<p>Ok, so I want to return the elements that are present in both provided arrays having the same index location.</p>
<pre><code>exe1 = [A,B,C,D,N]
exe2 = [B,D,C,A,T]
</code></pre>
<p>it should return only C</p>
<p>I've tried looping them by nested loops but doesn't work, here is what I've tried:</p>
<pre><code> let testing = []
for (let i = 0; i < exe1.length; i++){
for(let j = 0; j < exe2.length; j++){
if(exe1[i] === exe2[j]){
testing.push(exe1[i])
}
}
};
return testing;
</code></pre>
<p>mind the names of the arrays, please</p>
|
[
{
"answer_id": 74595174,
"author": "Phil",
"author_id": 283366,
"author_profile": "https://Stackoverflow.com/users/283366",
"pm_score": 3,
"selected": true,
"text": "exe1 exe2 const exe1 = ['A','B','C','D','N'];\nconst exe2 = ['B','D','C','A','T'];\n\nconst testing = exe1.filter((val, i) => val === exe2[i]);\n\nconsole.log(testing)"
},
{
"answer_id": 74595207,
"author": "async await",
"author_id": 7978627,
"author_profile": "https://Stackoverflow.com/users/7978627",
"pm_score": 0,
"selected": false,
"text": "const exe1 = [\"A\",\"B\",\"C\",\"D\",\"N\"];\nconst exe2 = [\"B\",\"D\",\"C\",\"A\",\"T\"];\n\nfunction getElementsThatAreTheSame(arr1, arr2) {\n const minLength = Math.min(arr1.length, arr2.length);\n const sameArray = [];\n for (let i = 0; i < minLength; i++) {\n const item1 = arr1[i];\n const item2 = arr2[i];\n if (item1 == item2) sameArray.push(item1);\n }\n return sameArray;\n}\n\nconst sameItems = getElementsThatAreTheSame(exe1, exe2);\nconsole.log(sameItems) const exe1 = [\"A\",\"B\",\"C\",\"D\",\"N\"];\nconst exe2 = [\"B\",\"D\",\"C\",\"A\",\"T\"];\nconst sameArr = exe1.filter((e, i) => exe2[i] == e);\nconsole.log(sameArr); {foo: \"bar\"} !== {foo: \"bar\"}"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409564/"
] |
74,595,178
|
<p>I'm trying to learn Laravel, but ran into an issue I hope you can help resolve. Recently, while working to learn php programming I installed XAMPP, without problem and used it with both php and MYSql. It uses the localhost IP of <a href="http://127.0.0.1" rel="nofollow noreferrer">http://127.0.0.1</a>. In the new course I'm using to learn Laravel after the installation of Laravel the setup uses <a href="http://127.0.0.1:8000/" rel="nofollow noreferrer">http://127.0.0.1:8000/</a>, which I can access using Visual Code Terminal and entering "php artisan serve". Following the course instructions for setting up Visual Code I next installed an Extension titled "Connect to Server". After installation of the extension I get a dialog box to connect to the database and it defaults to the 127.0.0.1:8000/ address. If I click on the connect button I get an error. That said, if I start XAMPP and change the value in the dialog box and use the XAMPP 127.0.0.1 address I make a successful connection to MYSQL.The question I have is this, am I going to have a problem in the near future as the result of the two different 127.0.0... addresses and if so is there any way to resolve it?</p>
<p>If you look at the problem I have outlined the issue and hope I can get some resolution before I get to the point I run into trouble.</p>
|
[
{
"answer_id": 74595496,
"author": "Mr. Kenneth",
"author_id": 13933721,
"author_profile": "https://Stackoverflow.com/users/13933721",
"pm_score": 1,
"selected": false,
"text": "php artisan serve httpd-vhosts.conf C:\\wamp64\\bin\\apache\\apache2.4.51\\conf\\extra C:\\xampp\\apache\\conf\\extra <VirtualHost *:80>\n ServerAdmin webmaster@dummy-host.example.com\n DocumentRoot \"path-to-project\\public\"\n ServerName project.local\n <Directory \"path-to-project\">\n Options Indexes FollowSymLinks\n AllowOverride All\n Require all granted\n </Directory>\n\n ErrorLog \"logs/project-errors.log\"\n CustomLog \"logs/project-access.log\" common\n</VirtualHost>\n C:\\Windows\\System32\\drivers\\etc 127.0.0.1 project.local project.local"
},
{
"answer_id": 74596416,
"author": "Ravi",
"author_id": 8274885,
"author_profile": "https://Stackoverflow.com/users/8274885",
"pm_score": 0,
"selected": false,
"text": "php artisan serve"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2283892/"
] |
74,595,182
|
<p>Hi,</p>
<p>I have these 2 arrays of objects:</p>
<pre><code>const arr1 = [{"id":"pear","qty":2},{"id":"apple","qty":2}];
const arr2 = [{"id":"pear","qty":5},{"id":"lemon","qty":1}];
</code></pre>
<p>I want to combine them but at the same time summing their values in <code>qty</code> when they have the same <code>id</code> so this is the expected output:</p>
<pre><code>[{"id":"pear","qty":7},{"id":"apple","qty":2},{"id":"lemon","qty":1}];
</code></pre>
<p>I tried this but it only keeps the first object:</p>
<pre><code>const newArray = arr1.map((obj) => {
const secondArrayObj = arr2.find((obj2) => obj2.id === obj.id);
if (secondArrayObj) {
return {...secondArrayObj, ...obj}
}
return null;
}).filter((obj) => obj != null);
console.log(newArray);
</code></pre>
<p>What is the best approach here?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74595196,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "Array.map() arr1 arr2 Array.reduce() Array.filter() const arr1 = [{\"id\":\"pear\",\"qty\":2},{\"id\":\"apple\",\"qty\":2}];\nconst arr2 = [{\"id\":\"pear\",\"qty\":5},{\"id\":\"lemon\",\"qty\":1}];\n\nlet arr3 = [...arr1,...arr2]\narr3 = arr3.reduce((a,v) => {\n let obj = a.find(i => i.id === v.id)\n if(obj){\n obj.qty += v.qty \n }else{\n a.push(v) \n }\n return a\n},[])\nconsole.log(arr3)"
},
{
"answer_id": 74595218,
"author": "Phil",
"author_id": 283366,
"author_profile": "https://Stackoverflow.com/users/283366",
"pm_score": 0,
"selected": false,
"text": "id qty const arr1 = [{\"id\":\"pear\",\"qty\":2},{\"id\":\"apple\",\"qty\":2}];\nconst arr2 = [{\"id\":\"pear\",\"qty\":5},{\"id\":\"lemon\",\"qty\":1}];\n\nconst newArray = [\n ...arr1\n .concat(arr2)\n .reduce(\n (map, { id, qty }) => map.set(id, qty + (map.get(id) ?? 0)),\n new Map()\n ),\n].map(([id, qty]) => ({ id, qty }));\n\nconsole.log(newArray); .as-console-wrapper { max-height: 100% !important; }"
},
{
"answer_id": 74595222,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 1,
"selected": false,
"text": "sums const arr1 = [{\"id\":\"pear\",\"qty\":2},{\"id\":\"apple\",\"qty\":2}];\nconst arr2 = [{\"id\":\"pear\",\"qty\":5},{\"id\":\"lemon\",\"qty\":1}];\n\nlet sums = {};\narr1.concat(arr2).forEach(obj => {\n if(!sums[obj.id]) {\n sums[obj.id] = 0;\n }\n sums[obj.id] += obj.qty;\n});\nlet arr3 = Object.keys(sums).map(id => { return {id: id, qty: sums[id]}; });\nconsole.log(arr3); [\n {\n \"id\": \"pear\",\n \"qty\": 7\n },\n {\n \"id\": \"apple\",\n \"qty\": 2\n },\n {\n \"id\": \"lemon\",\n \"qty\": 1\n }\n]\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2230939/"
] |
74,595,185
|
<p>I have written code that should do as the title says but im getting "TypeError: can only join an iterable"
on line 12, in reverse_words d.append(''.join(c))</p>
<p>here is my following code-</p>
<pre><code>def reverse_words(text):
#makes 'apple TEST' into ['apple', 'TEST']
a = text.split(' ')
d = []
for i in a:
#takes 'apple' and turns it into ['a','p','p','l','e']
b = i.split()
#takes ['a','p','p','l','e'] and turns it into ['e','l','p','p','a']
c = b.reverse()
#takes ['e','l','p','p','a'] and turns it into 'elppa'
#appends 'elppa' onto d
d.append(''.join(c))
#whole thing repeats for 'TEST' as well
#joins d together by a space and should print out 'elppa TSET'
print(' '.join(d))
reverse_words('apple TEST')
</code></pre>
<p>I know it has to do something that I messed up with c but I cannot identify it.</p>
<p>trying to reverse words while maintaining order but i got a type error</p>
|
[
{
"answer_id": 74595206,
"author": "Atticus Reeves",
"author_id": 13696100,
"author_profile": "https://Stackoverflow.com/users/13696100",
"pm_score": -1,
"selected": false,
"text": "d.append('').join(d)\n"
},
{
"answer_id": 74595257,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 1,
"selected": true,
"text": "str.join def reverse_words(text: str) -> str:\n return ' '.join(word[::-1] for word in text.split(' '))\n"
},
{
"answer_id": 74602820,
"author": "parkdj1",
"author_id": 20618950,
"author_profile": "https://Stackoverflow.com/users/20618950",
"pm_score": 0,
"selected": false,
"text": "def reverse_words(text):\n #makes 'apple TEST' into ['apple', 'TEST']\n a = text.split(' ')\n d = []\n for i in a:\n #takes 'apple' and turns it into ['a','p','p','l','e']\n b = i.split()\n #takes ['a','p','p','l','e'] and turns it into ['e','l','p','p','a']\n b.reverse()\n #takes ['e','l','p','p','a'] and turns it into 'elppa'\n #appends 'elppa' onto d\n d.append(''.join(b))\n #whole thing repeats for 'TEST' as well\n #joins d together by a space and should print out 'elppa TSET'\n print(' '.join(d))\n\nreverse_words('apple TEST')\n def reverse_words(text):\n #makes 'apple TEST' into ['apple', 'TEST']\n a = text.split(' ')\n d = []\n for i in a:\n #takes 'apple' and turns it into ['a','p','p','l','e']\n b = i.split()\n #takes ['a','p','p','l','e'] and turns it into ['e','l','p','p','a']\n c = reversed(b)\n #takes ['e','l','p','p','a'] and turns it into 'elppa'\n #appends 'elppa' onto d\n d.append(''.join(c))\n #whole thing repeats for 'TEST' as well\n #joins d together by a space and should print out 'elppa TSET'\n print(' '.join(d))\n\nreverse_words('apple TEST')\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618879/"
] |
74,595,187
|
<p>I'm having trouble fully wiring on my Django applications submit button, it seems that the JS function does not understand which checked boxes to look for
all the console returns are "cannot read properties of null, reading "checked" I'm assuming its something with the function defining but I cannot seem to get it working</p>
<p>Heres the code:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
{% load static%}
{% block content%}
<link rel="shortcut icon" type="image/png" href="{% static 'IMG/favicon.ico' %}"/>
<link rel="stylesheet" href="{% static 'CSS/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'CSS/jquery-ui.css' %}">
<script type="text/javascript" src="{% static 'JS/bootstrap.min.js' %}"></script>
<title>Task List</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="{% static 'JS/jquery-ui.min.js' %}"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
let _csrf = '{{csrf_token}}';
function submit_delete() {
var listItems = $("#list li input");
var checkedListItems = [];
listItems.each(function() {
if (document.getElementById(this.id).checked) {
checkedListItems.push(getTaskId(this.id));
console.log(checkedListItems);
}
})
$.ajax({
headers: { "X-CSRFToken": _csrf },
type: "POST",
url: "/ptm/item_delete",
data: {
'deleteList[]': checkedListItems
}
}).done(location.reload());
}
function getTaskId(str) {
return str.split('-')[1];
}
</script>
</head>
<body>
<div id="logo" class="border-success border border-3 rounded-2" style="width: 61.rem;">
<div class="card-body">
<img class="card-img" src="{% static '/IMG/Logo.png' %}">
</div>
</div>
<div id="taskList" class="card">
{% if task_list %}
<ul class="list-group" id="list">
{% for item in task_list %}
<li class="list-group-item" id='tdList'>
<input id="check-{{ item.id }}" type="checkbox" class="form-check-input me-1" value="">
<label class='d-flex w-100 justify-content-between'>
<h2 class="form-check-label" for="check-{{ item.id }}">{{ item.title }}</h2>
<small class='text-muted'>{{ item.date }}</small>
<input size='3'>
</label>
<h5 class="form-check-label">{{ item.description }}</h5>
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no current tasks assigned to this department.</p>
{% endif %}
</div>
{% csrf_token %}
<div id="taskEnter" class="card-footer">
<div class="d-grid mx-auto">
{% if task_list %}
<button type="button" onclick="submit_delete()" value='delete' class="btn btn-success btn-lg d-grid" value='delete'><i class="">Submit</i></button>
{% endif %}
</div>
</div>
</body>
{% endblock %}
</html>
</code></pre>
|
[
{
"answer_id": 74595229,
"author": "Dennis Hackethal",
"author_id": 1371131,
"author_profile": "https://Stackoverflow.com/users/1371131",
"pm_score": 1,
"selected": false,
"text": "document.getElementById(this.id).checked\n document.getElementById(this.id) null null.checked this window this.id listItems.each(function(listItem) {\n if (listItem.checked) {\n checkedListItems.push(getTaskId(listItem.id));\n console.log(checkedListItems);\n }\n})\n each"
},
{
"answer_id": 74595725,
"author": "traktor",
"author_id": 5217142,
"author_profile": "https://Stackoverflow.com/users/5217142",
"pm_score": 0,
"selected": false,
"text": "submit_delete var listItems = $(\"#list li > input\");\n input .list li <input size='3'> id each null getElementById checked null each this this id this getElementById(this.id) this !this.id getElementById(this.id)===null"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618810/"
] |
74,595,213
|
<p>I have a simple Javascript function that calculates the weeks between two dates, every seven days equals one week:</p>
<pre><code>function getWeeksDiff(startDate, endDate) {
const msInWeek = 1000 * 60 * 60 * 24 * 7;
return Math.round(Math.abs(endDate - startDate) / msInWeek);
}
</code></pre>
<p>It works correctly, but now I want to change the logic. I want to take a week from every Monday to Saturday regardless of the day it is on and that is not strictly related to 7 days</p>
<p>For example: Today is November 23, so 24,25,26 and 27 must count 1 week, and from Monday 28 to Sunday 4 it must count two weeks, so my logic is as follows:</p>
<pre><code>const week = 1000 * 60 * 60 * 24 * 7;
const day = 24 * 60 * 60 * 1000;
function weeksBetween(startDate, endDate) {
return Math.ceil((weekStart(endDate) - weekStart(startDate)) / week) + 1;
}
function weekStart(dt) {
const weekday = dt.getDay();
return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}
</code></pre>
<p>But for some reason, every Sunday it calculates one more week, for example, Sunday the 27th already shows me two weeks instead of one:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const week = 7 * 24 * 60 * 60 * 1000;
const day = 24 * 60 * 60 * 1000;
function weekStart(dt) {
const weekday = dt.getDay();
return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}
function weeksBetween(d1, d2) {
return Math.ceil((weekStart(d2) - weekStart(d1)) / week)+1;
}
console.log(weeksBetween(new Date("11/23/2022"), new Date("11/27/2022")));</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74595839,
"author": "Jeff Vdovjak",
"author_id": 1937507,
"author_profile": "https://Stackoverflow.com/users/1937507",
"pm_score": 3,
"selected": true,
"text": "function countWeeks(startDate, endDate) {\n // Calculate the next Sunday from the startDate \n // Change the 0 if you need a different day to start the week\n const firstWeek = startDate.getDate() + (7 + 0 - startDate.getDay()) % 7;\n const newStartDate = new Date(startDate.setDate(firstWeek));\n\n // Remove that partial week and calculate how many partial weeks remaining\n return Math.ceil((endDate-newStartDate)/1000/60/60/24/7) + 1;\n\n}\n\nconst date1 = new Date('11/20/2022');\nconst date2 = new Date('11/27/2022');\nconsole.log(countWeeks(date1, date2)); // 2\n\nconst date3 = new Date('11/1/2022');\nconst date4 = new Date('11/29/2022');\nconsole.log(countWeeks(date3, date4)); // 5\n"
},
{
"answer_id": 74596119,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 0,
"selected": false,
"text": "function weeksBetween(startDate, endDate) {\n const dayTimestamp = 24 * 3600 * 1000\n //count how many days between 2 dates\n const days = 1 + Math.round((endDate - startDate) / dayTimestamp);\n\n //get the day difference from the current date with Monday\n const dayDiff = (startDate.getDay() + 6) % 7\n \n //the default count is always 1, and calculate how many full weeks go from the start date to the end date\n //a full week will be 7 days\n return 1 + Math.floor((days + dayDiff) / 7);\n}\nconsole.log(\"11/22/2022 - 11/24/2022:\",weeksBetween(new Date(\"11/22/2022\"), new Date(\"11/24/2022\")));\n\nconsole.log(\"11/21/2022 - 11/28/2022:\",weeksBetween(new Date(\"11/21/2022\"), new Date(\"11/28/2022\")));\n\nconsole.log(\"11/21/2022 - 11/29/2022:\",weeksBetween(new Date(\"11/21/2022\"), new Date(\"11/29/2022\")));\n\nconsole.log(\"11/23/2022 - 12/04/2022:\",weeksBetween(new Date(\"11/23/2022\"), new Date(\"12/04/2022\")));"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16090212/"
] |
74,595,246
|
<p>I'm using Bootstrap in my app where I've got a multiple filters above my table. How to add some space between <code>Date Min</code> line and <code>Payment Method</code> line? Here is screenshot which better describes my issue:</p>
<p><a href="https://i.stack.imgur.com/jsqv1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jsqv1.png" alt="enter image description here" /></a></p>
<p>Here is my code: <a href="https://jsfiddle.net/71tr3sqj/" rel="nofollow noreferrer">https://jsfiddle.net/71tr3sqj/</a></p>
<pre><code><div class="row">
<div class="col text-end">
<form data-controller="transactions-form" data-transactions-form-target="form" data-turbo-frame="transactions" action="/transactions" accept-charset="UTF-8" method="get">
<label for="platform_payment_id">Order Id</label>
<input data-action="input->transactions-form#search" type="text" name="platform_payment_id" id="platform_payment_id">
<label for="min_amount">Min Amount</label>
<input data-action="input->transactions-form#search" type="text" name="min_amount" id="min_amount">
<label for="max_amount">Max Amount</label>
<input data-action="input->transactions-form#search" type="text" name="max_amount" id="max_amount">
<label for="payer_name">Payer Name</label>
<input data-action="input->transactions-form#search" type="text" name="payer_name" id="payer_name">
<label for="date_min">
<span class="translation_missing" title="translation missing: en.transactions.table.date_min">Date Min</span>
</label>
<input data-action="input->transactions-form#search" type="date" name="date_min" id="date_min">
<label for="date_max">
<span class="translation_missing" title="translation missing: en.transactions.table.date_max">Date Max</span>
</label>
<input data-action="input->transactions-form#search" type="date" name="date_max" id="date_max">
<label for="payment_method">Payment Method</label>
<select data-action="change->transactions-form#search" name="payment_method" id="payment_method">
<option value="">All Methods</option>
<option value="directdebit">Direct Debit</option>
<option value="creditcard">Credit Card</option>
</select>
<label for="status">Status</label>
<select data-action="change->transactions-form#search" name="status" id="status">
<option value="">All Statuses</option>
<option value="awaiting_authentication">Awaiting Authentication</option>
<option value="awaiting_clearance">Awaiting Clearance</option>
<option value="awaiting_user_input">Awaiting User Input</option>
<option value="fully_paid">Fully Paid</option>
<option value="payment_declined">Payment Declined</option>
<option value="user_canceled">User Canceled</option>
</select>
</form>
</div>
</div>
</code></pre>
|
[
{
"answer_id": 74595474,
"author": "Dexter",
"author_id": 5413283,
"author_profile": "https://Stackoverflow.com/users/5413283",
"pm_score": 2,
"selected": true,
"text": "mb-2 <form method=\"get\">\n <div class=\"mb-2\">\n <label for=\"\">Order Id</label>\n <input type=\"text\" name=\"\">\n </div>\n</form>\n"
},
{
"answer_id": 74595633,
"author": "Okumaru",
"author_id": 20619314,
"author_profile": "https://Stackoverflow.com/users/20619314",
"pm_score": 0,
"selected": false,
"text": "<form data-controller=\"transactions-form\" data-transactions-form-target=\"form\" data-turbo-frame=\"transactions\" action=\"/transactions\" accept-charset=\"UTF-8\" method=\"get\" style=\"display: flex; flex-wrap: wrap;gap: 10px;\">\n <div>\n <label for=\"platform_payment_id\">Order Id</label>\n <input data-action=\"input->transactions-form#search\" type=\"text\" name=\"platform_payment_id\" id=\"platform_payment_id\">\n </div>\n <div>\n <label for=\"min_amount\">Min Amount</label>\n <input data-action=\"input->transactions-form#search\" type=\"text\" name=\"min_amount\" id=\"min_amount\">\n </div>\n</form>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19143199/"
] |
74,595,253
|
<p>I have a csv file called csv1.csv that looks like:</p>
<pre><code> name|surname|grade
Maier|Hans,|A
Huber|Anna|B
Weißbäck|Werner|C
</code></pre>
<p>(So my csv is a table with 4 rows and 3 columns. There are tabular lines and not "|" in my csv file - like a spreadsheet.)
My actual file is a .csv file in my desktop that I imported in my overleaf. I have no idea why I am unable to simply display the table, let alone format it, using the <a href="https://ctan.math.washington.edu/tex-archive/macros/latex/contrib/csvsimple/csvsimple-l3.pdf" rel="nofollow noreferrer">csvsimple</a> package. What I tried:</p>
<pre><code>\documentclass[10pt]{beamer}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{csvsimple}
\begin{document}
\begin{table}[h]
\centering
\csvautobooktabular{csv1.csv}
\end{table}
\caption{My File}
\end{document}
</code></pre>
<p>I just want to display my csv file in my beamer and format it a bit (capitalize headers, make them bold, etc) instead of pasting a screenshot of it. If there is any other package that can help me, please feel free to suggest! Thank you!</p>
|
[
{
"answer_id": 74595356,
"author": "rral",
"author_id": 2857542,
"author_profile": "https://Stackoverflow.com/users/2857542",
"pm_score": 2,
"selected": false,
"text": "\\documentclass{beamer}\n\n\\usepackage{csvsimple}\n \n% file content grade.csv\n\n% name,givenname,matriculation,gender,grade\n% Maier,Hans,12345,m,1.0\n% Huber,Anna,23456,f,2.3\n% Weisbaeck,Werner,34567,m,5.0\n\n\n\\begin{document}\n\n\\begin{frame}{Title frame}\n \\begin{table}\n \\caption{Caption of table}\n \\begin{tabular}{l|c}%\n \\hline\n \\bfseries Person & \\bfseries Matr.~No.% specify table head\n \\csvreader[head to column names]{grade.csv}{}% use head of csv as column names\n {\\\\\\hline\\givenname\\ \\name & \\matriculation}% specify your columns here\n \\end{tabular}\n \\end{table}\n\\end{frame}\n\\end{document}\n"
},
{
"answer_id": 74595436,
"author": "imnothere",
"author_id": 538699,
"author_profile": "https://Stackoverflow.com/users/538699",
"pm_score": 2,
"selected": false,
"text": "csvsimple csv1.csv separator=pipe \\caption \\end{table} \\documentclass[10pt]{beamer}\n\\usepackage[utf8]{inputenc} \n\\usepackage{booktabs} \n\\usepackage{csvsimple}\n\n\\begin{document}\n\n\n\\begin{frame}\n\\begin{table}\n\\csvautobooktabular[separator=pipe]{csv1.csv}\n\\caption{My File}\n\\end{table}\n\\end{frame}\n\\end{document}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383481/"
] |
74,595,259
|
<p>I have a warehouses dictionary (shown below) and I need to get the sum of 'tons'. The values can be at various depths in the dictionary.</p>
<pre><code>warehouses = {
"Warehouse Lisboa": [
{ "name": "apples", "tons": 4},
{ "name": "oranges", "tons": 10},
{ "name": "lemons", "tons": 50}
],
"Warehouse Cascais": {
"Branch 1": [
{ "name": "apples", "tons": 10},
{ "name": "oranges", "tons": 24}
],
"Branch 2": [
{ "name": "apples", "tons": 16},
{ "name": "oranges", "tons": 8}
]
},
"Warehouse Oeiras": {
"Branch 1": {
"Sub Branch 1":{
"Sub sub Branch 1": [
{ "name": "lemons", "tons": 10}
]
}
},
"Branch 2": [
{ "name": "apples", "tons": 3}
]
}
}
</code></pre>
<p>I tried the following but it returned - <em>TypeError: unsupported operand type(s) for +: 'int' and 'list'</em>:</p>
<pre><code>def stock_fruits(warehouses):
return sum(warehouses.values())
</code></pre>
<p>How do I get the sum of all the 'tons' values in the dictionary?</p>
|
[
{
"answer_id": 74595374,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 1,
"selected": false,
"text": "from typing import Union\n\ndef stock_fruits(curr: Union[dict, list]) -> int:\n if isinstance(curr, dict):\n return sum(stock_fruits(value) for value in curr.values())\n return sum(entry[\"tons\"] for entry in curr)\n\nwarehouses = {\n \"Warehouse Lisboa\": [\n {\"name\": \"apples\", \"tons\": 4},\n {\"name\": \"oranges\", \"tons\": 10},\n {\"name\": \"lemons\", \"tons\": 50}\n ],\n \"Warehouse Cascais\": {\n \"Branch 1\": [\n {\"name\": \"apples\", \"tons\": 10},\n {\"name\": \"oranges\", \"tons\": 24}\n ],\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 16},\n {\"name\": \"oranges\", \"tons\": 8}\n ]\n },\n \"Warehouse Oeiras\": {\n \"Branch 1\": {\n \"Sub Branch 1\": {\n \"Sub sub Branch 1\": [\n {\"name\": \"lemons\", \"tons\": 10}\n ]\n }\n },\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 3}\n ]\n }\n}\nprint(f\"{stock_fruits(warehouses) = }\")\n stock_fruits(warehouses) = 135\n"
},
{
"answer_id": 74595697,
"author": "Ezra Katz",
"author_id": 14872851,
"author_profile": "https://Stackoverflow.com/users/14872851",
"pm_score": 0,
"selected": false,
"text": " def stock_fruits(warehouses):\n fruit_sum = 0\n\n queue = deque(list(warehouses.values()))\n while queue:\n node = queue.popleft()\n if isinstance(node, List):\n fruit_sum += sum([item.get('tons', 0) for item in node])\n else:\n queue.extend(list(node.values()))\n\n return fruit_sum\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20275245/"
] |
74,595,261
|
<p>I have a button navigation and when you click on a button, the active class is added. My goal is for the active class to be added to the button clicked, but remove that class of active on all other buttons if present. The 'About' button will have a class of active on page load.</p>
<p>Not sure how to translate this to React, in JavaScript on click I would remove the class from all the elements in a loop and add a class to the target clicked if it did not already have the active class.</p>
<p>Code Sandbox - <a href="https://codesandbox.io/s/toggle-active-on-class-clicked-remove-from-the-rest-r467l1?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/toggle-active-on-class-clicked-remove-from-the-rest-r467l1?file=/src/App.js</a></p>
<pre><code>export default function Header() {
const [active, setActive] = useState(true);
const toggleColor = function (e) {
// on load, 'About' button has active class
// when clicking another menu item add active class, remove active from the rest of buttons
console.log(e.target);
};
return (
<header className="header-img-container">
<nav>
<ul>
<li>
<button onClick={toggleColor} className={active ? "active" : ""}>
About
</button>
</li>
<li>
<button onClick={toggleColor}>Skills</button>
</li>
<li>
<button onClick={toggleColor}>Projects</button>
</li>
<li>
<button onClick={toggleColor}>Words</button>
</li>
</ul>
</nav>
</header>
);
}
</code></pre>
|
[
{
"answer_id": 74595374,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 1,
"selected": false,
"text": "from typing import Union\n\ndef stock_fruits(curr: Union[dict, list]) -> int:\n if isinstance(curr, dict):\n return sum(stock_fruits(value) for value in curr.values())\n return sum(entry[\"tons\"] for entry in curr)\n\nwarehouses = {\n \"Warehouse Lisboa\": [\n {\"name\": \"apples\", \"tons\": 4},\n {\"name\": \"oranges\", \"tons\": 10},\n {\"name\": \"lemons\", \"tons\": 50}\n ],\n \"Warehouse Cascais\": {\n \"Branch 1\": [\n {\"name\": \"apples\", \"tons\": 10},\n {\"name\": \"oranges\", \"tons\": 24}\n ],\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 16},\n {\"name\": \"oranges\", \"tons\": 8}\n ]\n },\n \"Warehouse Oeiras\": {\n \"Branch 1\": {\n \"Sub Branch 1\": {\n \"Sub sub Branch 1\": [\n {\"name\": \"lemons\", \"tons\": 10}\n ]\n }\n },\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 3}\n ]\n }\n}\nprint(f\"{stock_fruits(warehouses) = }\")\n stock_fruits(warehouses) = 135\n"
},
{
"answer_id": 74595697,
"author": "Ezra Katz",
"author_id": 14872851,
"author_profile": "https://Stackoverflow.com/users/14872851",
"pm_score": 0,
"selected": false,
"text": " def stock_fruits(warehouses):\n fruit_sum = 0\n\n queue = deque(list(warehouses.values()))\n while queue:\n node = queue.popleft()\n if isinstance(node, List):\n fruit_sum += sum([item.get('tons', 0) for item in node])\n else:\n queue.extend(list(node.values()))\n\n return fruit_sum\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11091321/"
] |
74,595,275
|
<p>I have a API post method in my react app. I need to add or remove a parameter inside the body conditionally</p>
<p>If the variable 'locale' value is 'all'.I don't need locale inside body of post method. If the 'locale' is not 'all' then I need to attach locale inside the post method.</p>
<p>I used if else..just wanted to know if there is a better way to handle this.
This is just a overview (pseudo code) of my code.</p>
<pre><code>If(locale?.includes('all')) {
return API.post(),{
body: {
id,
status
}}}
else{
return API.post(),{
body: {
id,
status,
locale
}}}
</code></pre>
|
[
{
"answer_id": 74595374,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 1,
"selected": false,
"text": "from typing import Union\n\ndef stock_fruits(curr: Union[dict, list]) -> int:\n if isinstance(curr, dict):\n return sum(stock_fruits(value) for value in curr.values())\n return sum(entry[\"tons\"] for entry in curr)\n\nwarehouses = {\n \"Warehouse Lisboa\": [\n {\"name\": \"apples\", \"tons\": 4},\n {\"name\": \"oranges\", \"tons\": 10},\n {\"name\": \"lemons\", \"tons\": 50}\n ],\n \"Warehouse Cascais\": {\n \"Branch 1\": [\n {\"name\": \"apples\", \"tons\": 10},\n {\"name\": \"oranges\", \"tons\": 24}\n ],\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 16},\n {\"name\": \"oranges\", \"tons\": 8}\n ]\n },\n \"Warehouse Oeiras\": {\n \"Branch 1\": {\n \"Sub Branch 1\": {\n \"Sub sub Branch 1\": [\n {\"name\": \"lemons\", \"tons\": 10}\n ]\n }\n },\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 3}\n ]\n }\n}\nprint(f\"{stock_fruits(warehouses) = }\")\n stock_fruits(warehouses) = 135\n"
},
{
"answer_id": 74595697,
"author": "Ezra Katz",
"author_id": 14872851,
"author_profile": "https://Stackoverflow.com/users/14872851",
"pm_score": 0,
"selected": false,
"text": " def stock_fruits(warehouses):\n fruit_sum = 0\n\n queue = deque(list(warehouses.values()))\n while queue:\n node = queue.popleft()\n if isinstance(node, List):\n fruit_sum += sum([item.get('tons', 0) for item in node])\n else:\n queue.extend(list(node.values()))\n\n return fruit_sum\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15464620/"
] |
74,595,302
|
<p>I have a CSS style for a button. I don’t know how to do it. I think it’s a bit too complicated and it’s not easy to make responsive adjustments. I would like to ask everyone how to write a button like this in CSS? thanks</p>
<p><a href="https://i.stack.imgur.com/hFiKo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hFiKo.jpg" alt="enter image description here" /></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.save_coin {
display: inline-block;
position: relative;
z-index: 3;
}
.save_coin::after {
content: "";
display: inline-block;
position: absolute;
background: #222;
border-radius: 32px;
padding: 26px 101px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
@media (max-width: 768px) {
.save_coin::after {
border-radius: 38px;
padding: 38px 102px;
}
}
.save_coin span {
display: inline-block;
font-weight: 500;
text-align: center;
background: #222;
color: #fff;
padding: 12px;
border-radius: 32px;
position: relative;
z-index: 2;
border: 1px solid #fff;
width: 192px;
}
@media (max-width: 768px) {
.save_coin span {
width: auto;
font-size: 24px;
font-weight: 700;
padding: 15px 46px;
}
}
.save_coin:hover span {
color: #222;
background-color: #fff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="#" class="save_coin"><span>save</span></a></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74595374,
"author": "Sash Sinha",
"author_id": 6328256,
"author_profile": "https://Stackoverflow.com/users/6328256",
"pm_score": 1,
"selected": false,
"text": "from typing import Union\n\ndef stock_fruits(curr: Union[dict, list]) -> int:\n if isinstance(curr, dict):\n return sum(stock_fruits(value) for value in curr.values())\n return sum(entry[\"tons\"] for entry in curr)\n\nwarehouses = {\n \"Warehouse Lisboa\": [\n {\"name\": \"apples\", \"tons\": 4},\n {\"name\": \"oranges\", \"tons\": 10},\n {\"name\": \"lemons\", \"tons\": 50}\n ],\n \"Warehouse Cascais\": {\n \"Branch 1\": [\n {\"name\": \"apples\", \"tons\": 10},\n {\"name\": \"oranges\", \"tons\": 24}\n ],\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 16},\n {\"name\": \"oranges\", \"tons\": 8}\n ]\n },\n \"Warehouse Oeiras\": {\n \"Branch 1\": {\n \"Sub Branch 1\": {\n \"Sub sub Branch 1\": [\n {\"name\": \"lemons\", \"tons\": 10}\n ]\n }\n },\n \"Branch 2\": [\n {\"name\": \"apples\", \"tons\": 3}\n ]\n }\n}\nprint(f\"{stock_fruits(warehouses) = }\")\n stock_fruits(warehouses) = 135\n"
},
{
"answer_id": 74595697,
"author": "Ezra Katz",
"author_id": 14872851,
"author_profile": "https://Stackoverflow.com/users/14872851",
"pm_score": 0,
"selected": false,
"text": " def stock_fruits(warehouses):\n fruit_sum = 0\n\n queue = deque(list(warehouses.values()))\n while queue:\n node = queue.popleft()\n if isinstance(node, List):\n fruit_sum += sum([item.get('tons', 0) for item in node])\n else:\n queue.extend(list(node.values()))\n\n return fruit_sum\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11241725/"
] |
74,595,340
|
<p>I am trying to call this <code>GetProductStatus()</code> method on a page button click event, but it's loading before the button click. Means when the ViewModel is loading, this is also load automatically.</p>
<p>I would like to declared this VM method "<code>GetProductStatus()</code>" to be called only when a button click event occurs.</p>
<p><strong>ViewModel method:</strong></p>
<pre><code>private async void GetProductStatus()
{
try
{
IsBusy = true;
var status = await ProductStatusService.GetProductStatus(new ProductStatus()
{
StoreCode = s_code,
StartTime = StartDateValue.AddMinutes(time1),
EndTime = StartDateValue.AddMinutes(time2)
});
IsBusy = false;
if (status != null)
{
//Process happens
}
else
{
//Array is Null
}
ProductStatus = status;
}
catch (Exception)
{
ProductStatus = null;
}
}
</code></pre>
<p>Here, the method is declared.</p>
<pre><code>public ProductViewModel(INavigation nav, Store store)
{
_Nav = nav;
GetProductStatus();
}
</code></pre>
<p>Here, the clicked event.</p>
<pre><code>private async void ProductTypeButton_Clicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new ProductPage(_ViewModel));
}
</code></pre>
|
[
{
"answer_id": 74595424,
"author": "ToolmakerSteve",
"author_id": 199364,
"author_profile": "https://Stackoverflow.com/users/199364",
"pm_score": 0,
"selected": false,
"text": "class class A public ProductViewModel(..., bool doGetProductStatus)... new ProductViewModel(..., true); A.DoSomething(); _ViewModel.DoSomething();"
},
{
"answer_id": 74596406,
"author": "Jessie Zhang -MSFT",
"author_id": 10308336,
"author_profile": "https://Stackoverflow.com/users/10308336",
"pm_score": 2,
"selected": true,
"text": " private async void ProductTypeButton_Clicked(object sender, EventArgs e)\n { \n await Navigation.PushAsync(new ProductPage(_ViewModel));\n }\n new ProductPage(_ViewModel) GetProductStatus(); ProductViewModel public ProductViewModel(INavigation nav, Store store)\n{\n _Nav = nav;\n \n // remove code here\n //GetProductStatus(); \n}\n public class ProductViewModel \n{\n public Command LoadDataCommand { get; set; }\n\n public ProductViewModel() {\n\n LoadDataCommand = new Command(loadData);\n\n // remove code here\n //GetProductStatus();\n }\n\n private void loadData()\n {\n GetProductStatus(); // add your code here\n }\n\n private async void GetProductStatus()\n {\n // other code\n }\n\n }\n ProductViewModel "
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12399310/"
] |
74,595,348
|
<p>So I have a program for this class where I'm supposed to allow the user to select a data type like byte, int, short, long, and etc. And then I am supposed to validate and make sure that the numbers they enter for the math problem aren't outside of the bounds of the data type they selected. Right now I'm using a bunch of if statements for each individual data type, and checking if it's above MaxValue or below MinValue. However, there has to be a better way to do this, right?</p>
<p>My current code is like this (numType is a byte set to the value of a constant when the button is pressed):</p>
<pre><code>if(numType = BYTE){
if(leftNum > byte.MaxValue){
errorsEncountered = true;
returnString = returnString + "Left number must not be more than " +
byte.MaxValue.ToString() + " for a byte.\n";
}
if(leftNum < byte.MinValue){
errorsEncountered = true;
returnString = returnString + "Left number must not be less than " +
byte.MinValue.ToString() + " for a byte.\n";
... (so on and so forth)
}
</code></pre>
<p>However I'd like to think that you could instead use something like a variable to record the data type and use that instead. So lets say that you have an array of each potential value of numType (1-7 in this case). Would there be a way to do something like this?</p>
<pre><code>byte numType = 8; // Will never be returned as this, an error is output for this value immediately.
const byte BYTE = 0;
const byte SHORT = 1;
const byte INT = 2;
const byte LONG = 3;
const byte FLOAT = 4;
const byte DOUBLE = 5;
const byte DECIMAL = 6;
string[] dataTypes = {"byte", "short", "int", "long", "float", "double", "decimal"};
if(leftNum > dataTypes[numType].MaxValue) {
errorsEncountered = true;
returnString = "Left number must not be more than " +
dataTypes[numType].MaxValue.ToString() + " for a " + dataTypes[numType] + ".";
}
if(leftNum < dataTypes[numType].MinValue) {
errorsEncountered = true;
returnString = "Left number must not be more than " +
dataTypes[numType].MinValue.ToString() + " for a " + dataTypes[numType] + ".";
}
</code></pre>
<p>I know my demonstration is incredibly simplistic but I genuinely don't know how better to describe what I'm trying to do. Thank you for any help you can provide.</p>
<p>Edit: Honestly it seems I'm a bit out of my depth here. I have no clue what most of these solutions are actually doing, and I've come out of this with the impression that I should probably just work on learning the language as a whole.</p>
|
[
{
"answer_id": 74595696,
"author": "Gabriel Luci",
"author_id": 1202807,
"author_profile": "https://Stackoverflow.com/users/1202807",
"pm_score": 1,
"selected": false,
"text": "TryParse MinValue MaxValue public static readonly Dictionary<string, Type> aliases = new() {\n { \"byte\", typeof(byte) },\n { \"short\" , typeof(short) },\n { \"int\" , typeof(int) },\n { \"long\" , typeof(long) },\n { \"float\" , typeof(float) },\n { \"double\" , typeof(double) },\n { \"decimal\" , typeof(decimal) }\n};\n\nstatic void Main() {\n Type type;\n while (true) {\n Console.WriteLine(\"Enter the type:\");\n var selectedType = Console.ReadLine().Trim();\n if (!aliases.TryGetValue(selectedType, out type)) {\n Console.WriteLine(\"You did it wrong\");\n continue;\n }\n break;\n }\n\n while (true) {\n Console.WriteLine(\"Type a value:\");\n var value = Console.ReadLine().Trim();\n\n // Create an instance of whatever type we're using\n object result = Activator.CreateInstance(type);\n\n // Get a reference to the TryParse method for this type\n var tryParseMethod = type.GetMethod(\"TryParse\", new[] { typeof(string), type.MakeByRefType() });\n\n // Call TryParse\n if (tryParseMethod.Invoke(null, new[] { value, result }) is bool success && success) {\n Console.WriteLine(\"You did it right!\");\n break;\n } else {\n // TryParse failed, so show the user the min/max values\n var minValueProp = type.GetField(\"MinValue\");\n var maxValueProp = type.GetField(\"MaxValue\");\n Console.WriteLine($\"You did it wrong. Enter a value between {minValueProp.GetValue(result)} and {maxValueProp.GetValue(result)}\");\n continue;\n }\n }\n}\n Enter the type:\nbyte\nType a value:\n-1\nYou did it wrong. Enter a value between 0 and 255\nType a value:\n1\nYou did it right!\n"
},
{
"answer_id": 74600780,
"author": "Matheus Lemos",
"author_id": 6619603,
"author_profile": "https://Stackoverflow.com/users/6619603",
"pm_score": 0,
"selected": false,
"text": "leftNum numType ITypeValidator IntegerValidator : ITypeValidator Dictionary<byte, ITypeValidator> internal class Program\n{\n static void Main(string[] args)\n {\n var myTypes = GetTypesImplementingInterface();\n\n byte numType = 2;\n object leftNum = 3;\n\n var validator = myTypes[numType];\n var result = validator.Validate(leftNum);\n }\n\n public static Dictionary<byte, ITypeValidator> GetTypesImplementingInterface()\n {\n // Fancy approach would be to use reflection to scan the Assembly \n // for implementations of our interface and automatically \n // instantiate and fill in the Dictionary\n\n return new Dictionary<byte, ITypeValidator>()\n {\n { 2, new IntValidator() }\n };\n }\n\n public interface ITypeValidator\n {\n byte TypeNumber { get; } // Tip: this helps with the Reflection approach\n ValidationResult Validate(object number);\n }\n\n public class ValidationResult\n {\n public bool HasError { get; set; }\n public List<string> ErrorMessages { get; set; }\n }\n\n public class IntValidator : ITypeValidator\n {\n public byte TypeNumber => 2;\n\n public ValidationResult Validate(object number)\n {\n // do your things\n\n return new ValidationResult();\n }\n }\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618980/"
] |
74,595,359
|
<pre><code>Range("TableIR000[Deductions in Month]").Copy
Range("TableIR000[Previous Deductions]").PasteSpecial xlPasteValues, Operation:=xlAdd
Range("TableIR001[Deductions in Month]").Copy
Range("TableIR001[Previous Deductions]").PasteSpecial xlPasteValues, Operation:=xlAdd
Range("TableIR002[Deductions in Month]").Copy
Range("TableIR002[Previous Deductions]").PasteSpecial xlPasteValues, Operation:=xlAdd
Range("TableIR002a[Deductions in Month]").Copy
Range("TableIR002a[Previous Deductions]").PasteSpecial xlPasteValues, Operation:=xlAdd
</code></pre>
<p>As you can see, all the tables I want to loop through start with "TableIR" in the name. I want the loop to ignore all tables without that prefix.</p>
<p>I currently have about 70 tables like this so a lot of repetitive lines. Every time I add another table, I will have to manually add another 2 lines of code.</p>
|
[
{
"answer_id": 74595838,
"author": "Domenic",
"author_id": 6585761,
"author_profile": "https://Stackoverflow.com/users/6585761",
"pm_score": 1,
"selected": false,
"text": "Dim listObj As ListObject\nFor Each listObj In Worksheets(\"Sheet1\").ListObjects 'change the sheet name accordingly\n If Left(listObj.Name, 7) = \"TableIR\" Then\n Range(listObj.Name & \"[Deductions in Month]\").Copy\n Range(listObj.Name & \"[Previous Deductions]\").PasteSpecial xlPasteValues, Operation:=xlAdd\n End If\nNext listObj\n Dim ws As Worksheet\nDim listObj As ListObject\nFor Each ws In ThisWorkbook.Worksheets\n For Each listObj In ws.ListObjects\n If Left(listObj.Name, 7) = \"TableIR\" Then\n Range(listObj.Name & \"[Deductions in Month]\").Copy\n Range(listObj.Name & \"[Previous Deductions]\").PasteSpecial xlPasteValues, Operation:=xlAdd\n End If\n Next listObj\nNext ws\n"
},
{
"answer_id": 74599057,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Worksheet.Evaluate Range.PasteSpecial Sub UpdateDeductions()\n\n Const COPY_COLUMN As String = \"Deductions in Month\"\n Const PASTE_COLUMN As String = \"Previous Deductions\"\n Const BEGINS_WITH As String = \"TableIR\"\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n Dim ws As Worksheet, lo As ListObject, crg As Range, prg As Range\n Dim cAd As String, pAd As String, EvalFormula As String\n \n For Each ws In wb.Worksheets\n For Each lo In ws.ListObjects\n If InStr(1, lo.Name, BEGINS_WITH, vbTextCompare) = 1 Then\n Set crg = lo.ListColumns(COPY_COLUMN).DataBodyRange\n Set prg = lo.ListColumns(PASTE_COLUMN).DataBodyRange\n' ' This is nice but messes up the selections:\n' crg.Copy\n' prg.PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd\n ' I would prefer this:\n cAd = crg.Address\n pAd = prg.Address\n EvalFormula = \"IFERROR(\" & pAd & \"+\" & cAd & \",\" & pAd & \")\"\n 'Debug.Print cAd, pAd, EvalFormula\n prg.Value = ws.Evaluate(EvalFormula)\n End If\n Next lo\n Next ws\n\n ' If for some reason you stick with 'PasteSpecial', you will also use this:\n 'Application.CutCopyMode = False\n\n 'wb.Save\n\n ' It should be pretty fast so to assure yourself that it has run, use:\n MsgBox \"Deductions updated.\", vbInformation\n\nEnd Sub\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619036/"
] |
74,595,375
|
<p><a href="https://i.stack.imgur.com/SxlPJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SxlPJ.png" alt="Dataframe" /></a></p>
<p>I have a dataframe as shown. I need 4 new columns [['PriceSpread_ATL', 'PriceSpread_CHI', 'PriceSpread_LA', 'PriceSpread_NY']] that are the price spreads for each market. For 'PriceSpreadATL', each cell in the column 'FarmPrice' must be subtracted from the corresponding cell in the column 'AtlantaRetail' and divided by the cell in 'FarmPrice' (ex.: (4.12 - 2.05)/2.05; (4.12 - 1.49)/1.49; (3.37 - 1.35)/1.35; (3.12 - 1.20)/ 1.20; and so on). Similarly, for 'PriceSpreadCHI', each cell in the column 'FarmPrice' must be subtracted from the corresponding cell in the column 'ChicagoRetail' and divided by the cell in 'FarmPrice', and so on for 'PriceSpread_LA' and 'PriceSpread_NY'. All the new price spread columns [['PriceSpread_ATL', 'PriceSpread_CHI', 'PriceSpread_LA', 'PriceSpread_NY']] should be appended column-wise to the dataframe. How do I carry out such an operation?</p>
|
[
{
"answer_id": 74595838,
"author": "Domenic",
"author_id": 6585761,
"author_profile": "https://Stackoverflow.com/users/6585761",
"pm_score": 1,
"selected": false,
"text": "Dim listObj As ListObject\nFor Each listObj In Worksheets(\"Sheet1\").ListObjects 'change the sheet name accordingly\n If Left(listObj.Name, 7) = \"TableIR\" Then\n Range(listObj.Name & \"[Deductions in Month]\").Copy\n Range(listObj.Name & \"[Previous Deductions]\").PasteSpecial xlPasteValues, Operation:=xlAdd\n End If\nNext listObj\n Dim ws As Worksheet\nDim listObj As ListObject\nFor Each ws In ThisWorkbook.Worksheets\n For Each listObj In ws.ListObjects\n If Left(listObj.Name, 7) = \"TableIR\" Then\n Range(listObj.Name & \"[Deductions in Month]\").Copy\n Range(listObj.Name & \"[Previous Deductions]\").PasteSpecial xlPasteValues, Operation:=xlAdd\n End If\n Next listObj\nNext ws\n"
},
{
"answer_id": 74599057,
"author": "VBasic2008",
"author_id": 9814069,
"author_profile": "https://Stackoverflow.com/users/9814069",
"pm_score": 0,
"selected": false,
"text": "Worksheet.Evaluate Range.PasteSpecial Sub UpdateDeductions()\n\n Const COPY_COLUMN As String = \"Deductions in Month\"\n Const PASTE_COLUMN As String = \"Previous Deductions\"\n Const BEGINS_WITH As String = \"TableIR\"\n \n Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code\n \n Dim ws As Worksheet, lo As ListObject, crg As Range, prg As Range\n Dim cAd As String, pAd As String, EvalFormula As String\n \n For Each ws In wb.Worksheets\n For Each lo In ws.ListObjects\n If InStr(1, lo.Name, BEGINS_WITH, vbTextCompare) = 1 Then\n Set crg = lo.ListColumns(COPY_COLUMN).DataBodyRange\n Set prg = lo.ListColumns(PASTE_COLUMN).DataBodyRange\n' ' This is nice but messes up the selections:\n' crg.Copy\n' prg.PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd\n ' I would prefer this:\n cAd = crg.Address\n pAd = prg.Address\n EvalFormula = \"IFERROR(\" & pAd & \"+\" & cAd & \",\" & pAd & \")\"\n 'Debug.Print cAd, pAd, EvalFormula\n prg.Value = ws.Evaluate(EvalFormula)\n End If\n Next lo\n Next ws\n\n ' If for some reason you stick with 'PasteSpecial', you will also use this:\n 'Application.CutCopyMode = False\n\n 'wb.Save\n\n ' It should be pretty fast so to assure yourself that it has run, use:\n MsgBox \"Deductions updated.\", vbInformation\n\nEnd Sub\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13127909/"
] |
74,595,376
|
<p>I have a given dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>list<em>ofnumbers</em></th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>[1, 2, 5, 6, 7]</td>
</tr>
<tr>
<td>5</td>
<td>[1, 2, 13, 51, 12]</td>
</tr>
</tbody>
</table>
</div>
<p>Where one column is just id, and the other one is list of number made like that which i got previously from JSON file, is there any way to get this into this format using only MySQL?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>list<em>of</em>numbers</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>13</td>
</tr>
<tr>
<td>5</td>
<td>51</td>
</tr>
<tr>
<td>5</td>
<td>12</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>I know it could be easily done using Python and pandas, but I only need to use MySQL in that case, and I do not really know how to transpose lists in MySQL like that</p>
|
[
{
"answer_id": 74595638,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 0,
"selected": false,
"text": "select \nid,regexp_split_to_table(listofnumbers,',')\nfrom test\n"
},
{
"answer_id": 74596011,
"author": "Kazi Mohammad Ali Nur",
"author_id": 8651601,
"author_profile": "https://Stackoverflow.com/users/8651601",
"pm_score": 1,
"selected": false,
"text": "create table myTable(id int, listofnumbers varchar(200));\ninsert into myTable values(2, '[1, 2, 5, 6, 7]');\ninsert into myTable values(5, '[1, 2, 13, 51, 12]');\n select t.id, j.listofnumbers\nfrom myTable t\njoin json_table(\n t.listofnumbers,\n '$[*]' columns (listofnumbers varchar(50) path '$')\n) j;\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20566782/"
] |
74,595,378
|
<p>I have an issue with keeping a division active after submitting a form using AJAX. My scenario is that I have a search bar, which can take multiple types of input (Name, ID, category, etc.). Then, I have a filter bar which is basically an advanced search, it practically does the same thing but has more options like separate fields for Name, ID, Category, price range, etc. these are some important terms,</p>
<ol>
<li>ID: product ID</li>
<li>Name: Product name</li>
<li>SPL_CD: Special code assigned to every product</li>
<li>ALT_NM2: Alternate name/Description</li>
<li>costStart/costEnd: range search for all products whose cost price is between the range</li>
<li>sellStart/sellEnd: range search for all products whose selling price is between the range</li>
<li>cname: category of the product</li>
<li>gname: group the product is classified under the category</li>
</ol>
<p>I don't care much for the CSS, <strong>but the point is that, anyone using this page at client end needs to see the values inserted in the filter dropdown i.e. keeping the filter drop down visible even on page reload.</strong> After submitting the form, my entire page reloads. This makes the dropdown go hidden again. I am bad at AJAX so I do not know how to do it, any help would be appreciated.</p>
<p>This is the working fiddle (ignore the lack of CSS, as it is all majorly defined under a different file based on MVC approach)- <a href="https://jsfiddle.net/retrop5/45jgv6qs/33/" rel="nofollow noreferrer">Fiddle</a>
This fiddle as well, does not support keeping the division active after the form is submitted, so I am trying to switch to AJAX.</p>
<p>This is what my AJAX approach is, but it keeps displaying a blank instead of the table and its data.</p>
<pre><code>$("#searchButton").click(function() {
var params = {
searchKeyword: $("#searchKeyword").val()
};
var form = $("#searchArea");
var url = form.attr("action")+"?"+$.param(params);
$.ajax({
url: url,
type: "POST",
dataType: "json",
colModel:[
{label:'ProductID', name:'ITM_CD',classes:'ITM_CD', width:40, align:"center", sorttype:"int"},
{label:'Name', name:'ITM_NM',classes:'ITM_NM',width:100, align:"center", sorttype:"int"},
{label:'Alt.name', name:'ITM_ALT_NM2',classes:'ITM_ALT_NM2', width:100, align:"center", sorttype:"string"},
{label:'Special code', name:'SPL_CD',classes:'SPL_CD', width:50, align:"center", sorttype:"int"},
{label:'Sort Order', name:'SORDER',classes:'SORDER', width:40, align:"center", sorttype:"int"},
{label:'Talent Points', name:'TPOINTS',classes:'TPOINTS', width:40, align:"center", sorttype:"int"},
{label:'Selling price', name:'SPRICE',classes:'SPRICE', width:30, align:"right", sorttype:"string"},
{label:'Cost price', name:'CPRICE',classes:'CPRICE', width:30, align:"right", sorttype:"string"},
{label: 'Category Name', name:'CNAME', classes: 'CNAME', width: 30, align: "right", sorttype:"string"},
{label: 'Group name', name:'GNAME', classes: 'GNAME', width: 30, align: "right", sorttype:"string"}
],
});
});
$("#searchButton").click(function() {
var params = {
searchKeyword: $("#searchKeyword").val(),
IDKeyword: $("#IDKeyword").val(),
NMKeyword: $("#NMKeyword").val(),
NM2Keyword: $("#NM2Keyword").val(),
SCKeyword: $("#SCKeyword").val(),
costStartKeyword: $("#costStartKeyword").val(),
costEndKeyword: $("#costEndKeyword").val(),
sellStartKeyword: $("#sellStartKeyword").val(),
sellEndKeyword: $("#sellEndKeyword").val(),
cnameKeyword: $("#cnameKeyword").val(),
gnameKeyword: $("#gnameKeyword").val()
};
var form = $("#dropDownFilter");
var url = form.attr("action")+"?"+$.param(params);
$.ajax({
url: url,
type: "POST",
dataType: "json",
colModel:[
{label:'ProductID', name:'ITM_CD',classes:'ITM_CD', width:40, align:"center", sorttype:"int"},
{label:'Name', name:'ITM_NM',classes:'ITM_NM',width:100, align:"center", sorttype:"int"},
{label:'Alt.name', name:'ITM_ALT_NM2',classes:'ITM_ALT_NM2', width:100, align:"center", sorttype:"string"},
{label:'Special code', name:'SPL_CD',classes:'SPL_CD', width:50, align:"center", sorttype:"int"},
{label:'Sort Order', name:'SORDER',classes:'SORDER', width:40, align:"center", sorttype:"int"},
{label:'Talent Points', name:'TPOINTS',classes:'TPOINTS', width:40, align:"center", sorttype:"int"},
{label:'Selling price', name:'SPRICE',classes:'SPRICE', width:30, align:"right", sorttype:"string"},
{label:'Cost price', name:'CPRICE',classes:'CPRICE', width:30, align:"right", sorttype:"string"},
{label: 'Category Name', name:'CNAME', classes: 'CNAME', width: 30, align: "right", sorttype:"string"},
{label: 'Group name', name:'GNAME', classes: 'GNAME', width: 30, align: "right", sorttype:"string"}
],
});
});
});
</code></pre>
<p>The HTML and the CSS is the same as the Fiddle.</p>
<h2>Edit 1: Tried the Local Storage</h2>
<pre><code>$("#filterSearchButton").on("click", function(){
localStorage.setItem("style", $("#dropDownFilter").css("display", "none"));
});
if (localStorage.getItem("style") === null) {
localStorage.setItem("style", $("#dropDownFilter").css("display", "flex"));
} else {
$("#dropDownFilter").css("display", "flex");
}
});
</code></pre>
<p><strong>Problem: The dropdown displays on first reload too, need to avoid that.</strong></p>
|
[
{
"answer_id": 74597054,
"author": "Bhavik",
"author_id": 20529186,
"author_profile": "https://Stackoverflow.com/users/20529186",
"pm_score": 3,
"selected": true,
"text": "window.localStorage.setItem(\"variable\", variable);\n\nvar getItem = window.localStorage.getItem(\"variable\");\n window.localStorage.removeItem('variable');\n"
},
{
"answer_id": 74597947,
"author": "retrop5",
"author_id": 15890212,
"author_profile": "https://Stackoverflow.com/users/15890212",
"pm_score": 1,
"selected": false,
"text": "$(document).on(\"click\", \"#report tr\", function(){\n parent.onSearched($(\"#report\").getRowData($(this).attr(\"value\")));\n});\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15890212/"
] |
74,595,390
|
<p><strong>Edited to add solution at bottom</strong></p>
<p>I have a project created with React and Typescript.</p>
<p>There is a parent component (Home) that displays a child component depending on the value of the state variable 'currentDemo'. The goal is to have a navigation component that will display whatever item was clicked. Each nav item has an id associated that relates to the component to be displayed. Ie, nav item 'a' should display component 'a', nav item 'b' should show component 'b', etc. Here is a snippet of the code.</p>
<p>Home.tsx (Parent):</p>
<pre><code>import React, { useState } from 'react';
import { Intro } from 'app/components/intro/Intro';
import { SidebarNav } from 'app/components/sidebarNav/SidebarNav';
import { ComponentA } from 'app/components/ComponentA/ComponentA';
import { ComponentB } from 'app/components/ComponentB/ComponentB';
export function Home() {
//use state to track which demo is currently displayed ('intro' is default)
const [currentDemo, setCurrentDemo] = useState('intro');
return (
<>
<Header />
<div className="home">
<SidebarNav setCurrentDemo={setCurrentDemo} />
{currentDemo === 'intro' && <Intro />}
{currentDemo === 'ComponentA' && <ComponentA/>}
{currentDemo === 'ComponentB' && <ComponentB/>}
</div>
</>
);
}
</code></pre>
<p>SidebarNav.tsx(child):</p>
<pre><code>import React, { useState } from 'react';
const navData = [
{
title: 'Introduction',
id: 'intro'
},
{
title: 'Component A',
id: 'ComponentA'
},
{
title: 'Component B',
id: 'ComponentB'
}
];
export function SidebarNav(setCurrentDemo: any) {
//GOAL: PASS ID OF SELECTED NAV ITEM TO PARENT COMPONENT AND SET VALUE OF 'CURRENTDEMO' TO THAT ID
const handleCurrentClick = (id: any) => {
if (id === 'intro') {
setCurrentDemo('ComponentA');
} else if (id === 'ComponentA') {
setCurrentDemo('ComponentB');
} else if (id === 'ComponentB') {
setCurrentDemo('intro');
}
};
return (
<div className="sidebarNav">
<div className="sidebarNav__container">
{navData?.map((item, index) => (
<div key={index}>
<button
onClick={() => {
handleCurrentClick(item.id);
}}
id={item.id}
>
{item.title}
</button>
</div>
))}
</div>
</div>
);
}
</code></pre>
<p>The specific implementation of Component A and B don't matter for this scenario. I've tested by manually setting the value of 'currentDemo' and the correct demo will display. I also confirmed that the id's for each nav item are correctly displaying via console.log(item.id).</p>
<p>How can I pass the pass the value of the id from SidebarNav to Home, setting the value of currentDemo to the ID of the nav item that was clicked? I feel like I'm close, but it's not quite right.</p>
<p>When clicking any of the nav elements there is a console error stating that setCurrentDemo is not a function. Which makes sense because it's the setter for the state, but how can I specify that we want to actually set currentDemo to the value of the item's ID?</p>
<p>Here is the solution that worked for this application. Changes made are in the navigation component. Added an interface in the nav and adjusted as such:</p>
<pre><code>interface SidebarNavProps {
setCurrentDemo: React.Dispatch<SetStateAction<string>>;
}
export function SidebarNav(props: SidebarNavProps) {
const { setCurrentDemo } = props;
...rest of function remains the same
};
</code></pre>
|
[
{
"answer_id": 74595649,
"author": "Muhammad Nouman Rafique",
"author_id": 19932999,
"author_profile": "https://Stackoverflow.com/users/19932999",
"pm_score": 2,
"selected": true,
"text": "{ setCurrentDemo } :any setCurrentDemo:any SidebarNav import { SetStateAction } from \"react\";\n\ninterface SidebarNavProps {\n setCurrentDemo: SetStateAction<string>\n}\n SidebarNav export function SidebarNav(props: SidebarNavProps) {\n const { setCurrentDemo } = props;\n\n //GOAL: PASS ID OF SELECTED NAV ITEM TO PARENT COMPONENT AND SET VALUE OF 'CURRENTDEMO' TO THAT ID\n const handleCurrentClick = (id: any) => {\n if (id === 'intro') {\n setCurrentDemo('ComponentA');\n } else if (id === 'ComponentA') {\n setCurrentDemo('ComponentB');\n } else if (id === 'ComponentB') {\n setCurrentDemo('intro');\n }\n };\n\n return (\n <div className=\"sidebarNav\">\n <div className=\"sidebarNav__container\">\n {navData?.map((item, index) => (\n <div key={index}>\n <button\n onClick={() => {\n handleCurrentClick(item.id);\n }}\n id={item.id}\n >\n {item.title}\n </button>\n </div>\n ))}\n </div>\n </div>\n );\n}\n setCurrentDemo"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16613979/"
] |
74,595,418
|
<p>I hope my title makes sense. Basically, I want to stack an H1 on top of an H3 that I have within the same flex box. This is for an assessment for App Academy. I'm not asking for a solution. Just a bit of guidance on how to do this concept.</p>
<p>Here is the image of reference:</p>
<p><img src="https://assets.aaonline.io/Module-Solo-Prep-Work/assets/html-css-assessment-card-picture.png" alt="" /></p>
<p>The "Title goes here" and "Secondary text" is what I am referring to.
I know my code is obviously not the cleanest, but I plan on cleaning up/optimizing a bit once I figure this darn thing out.</p>
<p>Here is my HTML:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
display: flex;
width: 344px;
flex-wrap: wrap;
}
.card:hover {
box-shadow: 0px 2px 4px rgba(0, 0, 0, .3);
}
.desert {
height: 194px;
width: 100%;
}
.avatar {
border-radius: 50%;
height: 40px;
width: 40px;
align-items: center;
padding: 10px;
}
p {
padding: 16px;
font-size: 11px;
}
h1 {
color: #000;
font-size: 22px;
}
h3,
p {
color: #232f32;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
<img class="desert" src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="a desert">
<img class="avatar" src="https://material.angular.io/assets/img/examples/shiba1.jpg" alt="an avatar">
<h1>Title goes here</h1>
<h3>Secondary text</h3>
<p>Greyhound divisively hello coldly wonderfully marginally far
upon excluding.</p>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74595649,
"author": "Muhammad Nouman Rafique",
"author_id": 19932999,
"author_profile": "https://Stackoverflow.com/users/19932999",
"pm_score": 2,
"selected": true,
"text": "{ setCurrentDemo } :any setCurrentDemo:any SidebarNav import { SetStateAction } from \"react\";\n\ninterface SidebarNavProps {\n setCurrentDemo: SetStateAction<string>\n}\n SidebarNav export function SidebarNav(props: SidebarNavProps) {\n const { setCurrentDemo } = props;\n\n //GOAL: PASS ID OF SELECTED NAV ITEM TO PARENT COMPONENT AND SET VALUE OF 'CURRENTDEMO' TO THAT ID\n const handleCurrentClick = (id: any) => {\n if (id === 'intro') {\n setCurrentDemo('ComponentA');\n } else if (id === 'ComponentA') {\n setCurrentDemo('ComponentB');\n } else if (id === 'ComponentB') {\n setCurrentDemo('intro');\n }\n };\n\n return (\n <div className=\"sidebarNav\">\n <div className=\"sidebarNav__container\">\n {navData?.map((item, index) => (\n <div key={index}>\n <button\n onClick={() => {\n handleCurrentClick(item.id);\n }}\n id={item.id}\n >\n {item.title}\n </button>\n </div>\n ))}\n </div>\n </div>\n );\n}\n setCurrentDemo"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7531876/"
] |
74,595,440
|
<p>I have this form:</p>
<p><code><input type="file" name="CAR_Logo"></code><br />
<code><button data-action="save" data-name="Africa">Save</></code></p>
<p>How I can update my code to be able to upload the file ?</p>
<p>This is what I have tried:</p>
<p><code>$('[data-action="save"]').click(function(e) {</code><br>
<code> e.preventDefault();</code><br>
<code> CAR_Name = $(this).data('name');</code><br>
<code> CAR_Logo = $(this).val('CAR_Logo');</code><br>
<code>});</code></p>
|
[
{
"answer_id": 74596012,
"author": "Ahmadreza Sadafi",
"author_id": 9336947,
"author_profile": "https://Stackoverflow.com/users/9336947",
"pm_score": 0,
"selected": false,
"text": "<input id=\"file\" type=\"file\" name=\"CAR_Logo\">\n $('#form').submit(function(e) {\n e.preventDefault();\n let fd = new FormData(this);\n fd.append('myfile', $('#file').files[0]);\n \n$.ajax({\n url : 'upload.php',\n type : 'POST',\n data : fd,\n processData: false,\n contentType: false,\n success : function(data) {\n console.log(data);\n alert(data);\n }\n});\n});\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531591/"
] |
74,595,458
|
<p>I am trying to implement a B-tree and from what I understand this is how you split a node:</p>
<ol>
<li>Attempt to insert a new value V at a leaf node N</li>
<li>If the leaf node has no space, create a new node and pick a middle value of N and anything right of it move to the new node and anything to the left of the middle value leave in the old node, but move it left to free up the right indices and insert V in the appropriate of the now two nodes</li>
<li>Insert the middle value we picked into the parent node of N and also add the newly created node to the list of children of the parent of N (thus making N and the new node siblings)</li>
<li>If the parent of N has no free space, perform the same operation and along with the values also split the children between the two split nodes (so this last part applies only to non-leaf nodes)</li>
<li>Continue trying to insert the previous split's middle point into the parent until you reach the root and potentially split the root itself, making a new root</li>
</ol>
<p>This brings me to the question - how do I traverse upwards, am I supposed to keep a pointer of the parent?<br />
Because I can only know if I have to split the leaf node when I have reached it for insertion. So once I have to split it, I have to somehow go back to its parent and if I have to split the parent as well, I have to keep going back up.<br />
Otherwise I would have to re-traverse the tree again and again each time to find the next parent.</p>
<p>Here is an example of my node class:</p>
<pre><code>template<typename KEY, typename VALUE, int DEGREE>
struct BNode
{
KEY Keys[DEGREE];
VALUE Values[DEGREE];
BNode<KEY, VALUE, DEGREE>* Children[DEGREE + 1];
BNode<KEY, VALUE, DEGREE>* Parent;
bool IsLeaf;
};
</code></pre>
<p>(Maybe I should not have an IsLeaf field and instead just check if it has any children, to save space)</p>
|
[
{
"answer_id": 74596012,
"author": "Ahmadreza Sadafi",
"author_id": 9336947,
"author_profile": "https://Stackoverflow.com/users/9336947",
"pm_score": 0,
"selected": false,
"text": "<input id=\"file\" type=\"file\" name=\"CAR_Logo\">\n $('#form').submit(function(e) {\n e.preventDefault();\n let fd = new FormData(this);\n fd.append('myfile', $('#file').files[0]);\n \n$.ajax({\n url : 'upload.php',\n type : 'POST',\n data : fd,\n processData: false,\n contentType: false,\n success : function(data) {\n console.log(data);\n alert(data);\n }\n});\n});\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1906587/"
] |
74,595,498
|
<p>I have a many2many field that represents a list of student. I want to only add student to that list but not remove any students from that list (in form view). Is it possible to implement that?</p>
|
[
{
"answer_id": 74596012,
"author": "Ahmadreza Sadafi",
"author_id": 9336947,
"author_profile": "https://Stackoverflow.com/users/9336947",
"pm_score": 0,
"selected": false,
"text": "<input id=\"file\" type=\"file\" name=\"CAR_Logo\">\n $('#form').submit(function(e) {\n e.preventDefault();\n let fd = new FormData(this);\n fd.append('myfile', $('#file').files[0]);\n \n$.ajax({\n url : 'upload.php',\n type : 'POST',\n data : fd,\n processData: false,\n contentType: false,\n success : function(data) {\n console.log(data);\n alert(data);\n }\n});\n});\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9301149/"
] |
74,595,507
|
<p>I am trying to add some text to an input element using a button. I have so far tried modifying .textContent - which does actually appear to modify the textContent, but this does not show up in the image box. Adjusting the .value does not seem to work.</p>
<p>My code:</p>
<pre><code>const buttons = document.querySelectorAll(".row button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
document.querySelector("input").value += buttons[i].value;
})
}
</code></pre>
<p>Every solution I have read online just suggests modifying the .value of the input element, which is not working for me, so I am at a loss.</p>
<p>EDIT: Thanks everyone, such a silly thing to overlook.</p>
|
[
{
"answer_id": 74596012,
"author": "Ahmadreza Sadafi",
"author_id": 9336947,
"author_profile": "https://Stackoverflow.com/users/9336947",
"pm_score": 0,
"selected": false,
"text": "<input id=\"file\" type=\"file\" name=\"CAR_Logo\">\n $('#form').submit(function(e) {\n e.preventDefault();\n let fd = new FormData(this);\n fd.append('myfile', $('#file').files[0]);\n \n$.ajax({\n url : 'upload.php',\n type : 'POST',\n data : fd,\n processData: false,\n contentType: false,\n success : function(data) {\n console.log(data);\n alert(data);\n }\n});\n});\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619204/"
] |
74,595,532
|
<p>I'm having trouble with what seems like a very simple problem. Yet, I don't know how to fix it.</p>
<p>I am trying to clear cell A2 if and only if A1 is empty. I'm sure there is an easy solution but I don't seem to notice it. I'll share a sample spreadsheet for all of you to visualize my objective.</p>
<p><a href="https://docs.google.com/spreadsheets/d/1qiq0w4xcUDO8pkFyeMO2ma_KR48evSsVAP6o50O0RtI/edit#gid=0" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1qiq0w4xcUDO8pkFyeMO2ma_KR48evSsVAP6o50O0RtI/edit#gid=0</a></p>
<p>This is what I tried.</p>
<pre><code>function onEdit(e) {
var sheet = SpreadsheetApp.getActive().getSheetByName("TEST");
var range = e.source.getActiveRange();
if(e.range.getRow() == 1 && e.range.getColumn() == 1) {
if(sheet.getRange("A1").getValue() == "") {
sheet.getRange('A2').clearContent();
}
}
}
</code></pre>
<p>Is there any problem with what I'm doing?</p>
<p>Help would be awesome.</p>
|
[
{
"answer_id": 74596012,
"author": "Ahmadreza Sadafi",
"author_id": 9336947,
"author_profile": "https://Stackoverflow.com/users/9336947",
"pm_score": 0,
"selected": false,
"text": "<input id=\"file\" type=\"file\" name=\"CAR_Logo\">\n $('#form').submit(function(e) {\n e.preventDefault();\n let fd = new FormData(this);\n fd.append('myfile', $('#file').files[0]);\n \n$.ajax({\n url : 'upload.php',\n type : 'POST',\n data : fd,\n processData: false,\n contentType: false,\n success : function(data) {\n console.log(data);\n alert(data);\n }\n});\n});\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403203/"
] |
74,595,543
|
<p>So every cell that has a value of 0, that row will be hidden. And any value that is outside the minimum and maximum values will be red.</p>
<p>How to identify red color but active (not hidden) with macro? because I used "range. displayformat. interior. color = vbred", the cells are red but hidden are also counted. Thanks.</p>
|
[
{
"answer_id": 74596107,
"author": "Thavisack VRCHDV",
"author_id": 19422735,
"author_profile": "https://Stackoverflow.com/users/19422735",
"pm_score": 1,
"selected": false,
"text": "Set rng = Range(\"Your range\").SpecialCells(xlCellTypeVisible)\n rng = ActiveCell.DisplayFormat.Interior.Color = vbRed\n"
},
{
"answer_id": 74598664,
"author": "Thavisack VRCHDV",
"author_id": 19422735,
"author_profile": "https://Stackoverflow.com/users/19422735",
"pm_score": 0,
"selected": false,
"text": "Sub Highlight_Greater_Than()\n\nDim ws As Worksheet\nDim Rng As Range\nDim ColorCell As Range\n\nSet ws = Worksheets(\"Name\")\nSet rng = Range(\"Your range\").SpecialCells(xlCellTypeVisible)\n 'rng = ActiveCell.DisplayFormat.Interior.Color = vbRed\nSet ColorCell = rng\n\nFor Each ColorCell In Rng\nIf ColorCell.Value > 1 Then \" You can define here\" \"greater, smaller, equal etc..\"\nColorCell.Interior.Color = vbred\n\nElse\nColorCell.Interior.ColorIndex = \"vb(colour)or\" xlNone\nEnd If\nNext\n\nEnd Sub\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619259/"
] |
74,595,552
|
<p>I have been struggling for hours and couldn't figuring out how to increment <code>i</code> using <code>useState([])</code>. I know <code>useState([])</code> is an asynchronous function, and I don't know how to increment <code>i</code> properly to give unique keys to each <code>Text</code></p>
<p>Here is my code -</p>
<pre><code>import React, { Component, useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
TextInput
} from 'react-native';
let weatherPanel = []
function WeatherApp(){
const [data, setData] = useState([]);
let i = 0;
const dates = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const temperatures = [20, 21, 26, 19, 30, 32, 23, 22, 24];
const cities = ['LA', 'SAN', 'SFO', 'LGA', 'HND', 'KIX', 'DEN', 'MUC', 'BOM'];
const buttonPressed = () => {
weatherPanel.push(
<View style = {styles.weatherBoard}>
<Text key = {dates[i]} style = {styles.date}>{dates[i]}</Text>
<Text key = {temperatures[i]} style = {styles.temperature}>{temperatures[i]}</Text>
<Text key = {cities[i]} style = {styles.cityName}>{cities[i]}</Text>
</View>
)
setData(weatherPanel);
i = i + 1;
}
// learn this to increment i properly
useEffect(()=>{
console.log(i)
}, [])
return(
<View style={styles.appBackground}>
<View style = {styles.searchBar}>
<TextInput>Text</TextInput>
</View>
<View style = {styles.weatherPanel}>
{data}
</View>
<View style = {styles.addButton}>
<Text onPress={() => buttonPressed(i)} style = {styles.temperature}>Text</Text> // CALLED buttonPressed() HERE.
</View>
</View>
)
}
</code></pre>
<p>I am calling button <code>buttonPressed</code> at the comment, <code>//CALLED buttonPressed() HERE.</code>. I am trying to add <code>i</code>, that is mentioned above, to access elements of all equal length lists. Could someone help me?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74596107,
"author": "Thavisack VRCHDV",
"author_id": 19422735,
"author_profile": "https://Stackoverflow.com/users/19422735",
"pm_score": 1,
"selected": false,
"text": "Set rng = Range(\"Your range\").SpecialCells(xlCellTypeVisible)\n rng = ActiveCell.DisplayFormat.Interior.Color = vbRed\n"
},
{
"answer_id": 74598664,
"author": "Thavisack VRCHDV",
"author_id": 19422735,
"author_profile": "https://Stackoverflow.com/users/19422735",
"pm_score": 0,
"selected": false,
"text": "Sub Highlight_Greater_Than()\n\nDim ws As Worksheet\nDim Rng As Range\nDim ColorCell As Range\n\nSet ws = Worksheets(\"Name\")\nSet rng = Range(\"Your range\").SpecialCells(xlCellTypeVisible)\n 'rng = ActiveCell.DisplayFormat.Interior.Color = vbRed\nSet ColorCell = rng\n\nFor Each ColorCell In Rng\nIf ColorCell.Value > 1 Then \" You can define here\" \"greater, smaller, equal etc..\"\nColorCell.Interior.Color = vbred\n\nElse\nColorCell.Interior.ColorIndex = \"vb(colour)or\" xlNone\nEnd If\nNext\n\nEnd Sub\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18284412/"
] |
74,595,554
|
<p>When writing a nested function in Go, how does the compiler treat it? Is it turned into another function and put outside the code, or does it get re-created anytime the parent function is called?</p>
<p>For example:</p>
<pre><code>func FuncA() int {
a := 0
funcB := func(_a int) int {
return _a
}
return funcB(a)
}
</code></pre>
<p>Is this function compiled as follows?</p>
<pre><code>func FuncA() int {
a := 0
return _funcB(a)
}
func _funcB(_a int) int {
return _a
}
</code></pre>
<p>Or is it compiled exactly as written which means that new memory is allocated for the definition of <code>funcB</code> anytime <code>FuncA</code> is called?</p>
|
[
{
"answer_id": 74596030,
"author": "Burak Serdar",
"author_id": 11923999,
"author_profile": "https://Stackoverflow.com/users/11923999",
"pm_score": 2,
"selected": false,
"text": " func FuncA() int {\n a := 0\n funcB := func() int {\n return a\n }\n return funcB()\n}\n type closureB struct {\n a int\n}\n\nfunc FuncA() int {\n c:=new(closureB)\n c.a=0\n return funcB(c)\n}\n\nfunc funcB(c *closureB) int {\n return c.a\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701022/"
] |
74,595,570
|
<p>Given a <code>sorted list</code>, and a variable <code>n</code>, I want to break up the <code>list</code> into <code>n</code> parts. With <code>n = 3,</code> I expect three <code>lists</code>, with the last one taking on the <code>overflow</code>.</p>
<p>I expect: <code>0,1,2,3,4,5</code>, <code>6,7,8,9,10,11</code>, <code>12,13,14,15,16,17</code></p>
<p>If the number of <code>items</code> in the <code>list</code> is not <code>divisible</code> by <code>n</code>, then just put the overflow <code>(mod n)</code> in the last <code>list</code>.</p>
<p>This doesn't work:</p>
<pre><code>static class Program
{
static void Main(string[] args)
{
var input = new List<double>();
for (int k = 0; k < 18; ++k)
{
input.Add(k);
}
var result = input.Split(3);
foreach (var resul in result)
{
foreach (var res in resul)
{
Console.WriteLine(res);
}
}
}
}
static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
int i = 0;
var splits = from item in list
group item by i++ % parts into part
select part.AsEnumerable();
return splits;
}
}
</code></pre>
|
[
{
"answer_id": 74597198,
"author": "Rufus L",
"author_id": 2052655,
"author_profile": "https://Stackoverflow.com/users/2052655",
"pm_score": 1,
"selected": false,
"text": "Console.Write Console.WriteLine() PadRight static void Main(string[] args)\n{\n var numItems = 18;\n var splitBy = 3;\n\n var input = Enumerable.Range(0, numItems).ToList();\n var results = input.Split(splitBy);\n\n // Get the length of the largest value to use for padding smaller values, \n // so all the columns will line up when we display the results\n var padValue = input.Max().ToString().Length + 1;\n\n foreach (var group in results)\n {\n foreach (var item in group)\n {\n Console.Write($\"{item}\".PadRight(padValue));\n }\n\n Console.WriteLine();\n }\n\n Console.Write(\"\\n\\nDone. Press any key to exit...\");\n Console.ReadKey();\n} \n 0 3 6 9 12 15\n1 4 7 10 13 16\n2 5 8 11 14 17\n 3 0 1 18 3 6 0 5 0 6 6 11 1 6 12 17 2 6 rows * columns public static IEnumerable<IEnumerable<T>> Split<T>(\n this IEnumerable<T> list, int parts)\n{\n int numItems = list.Count();\n int columns = numItems / parts;\n int overflow = numItems % parts;\n\n int index = 0;\n\n return from item in list\n group item by\n index++ >= (parts * columns) ? parts - 1 : (index - 1) / columns\n into part\n select part.AsEnumerable();\n}\n // For 18 items split into 3\n0 1 2 3 4 5\n6 7 8 9 10 11\n12 13 14 15 16 17\n\n// For 25 items split into 7\n0 1 2\n3 4 5\n6 7 8\n9 10 11\n12 13 14\n15 16 17\n18 19 20 21 22 23 24\n"
},
{
"answer_id": 74597756,
"author": "Astrid E.",
"author_id": 17213526,
"author_profile": "https://Stackoverflow.com/users/17213526",
"pm_score": 3,
"selected": true,
"text": "list yield return yield return list list n list ICollection<T> list ICollection<T> list.ToList() public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)\n{\n var collection = list is ICollection<T> c\n ? c\n : list.ToList();\n \n var itemCount = collection.Count;\n \n // return all items if source list is too short to split up\n if (itemCount < parts)\n {\n yield return collection;\n yield break;\n }\n \n var itemsInEachChunk = itemCount / parts;\n \n var chunks = itemCount % parts == 0\n ? parts\n : parts - 1;\n \n var itemsToChunk = chunks * itemsInEachChunk;\n \n foreach (var chunk in collection.Take(itemsToChunk).Chunk(itemsInEachChunk))\n {\n yield return chunk;\n }\n \n if (itemsToChunk < itemCount)\n {\n yield return collection.Skip(itemsToChunk);\n }\n}\n"
},
{
"answer_id": 74600374,
"author": "New Guy",
"author_id": 19433977,
"author_profile": "https://Stackoverflow.com/users/19433977",
"pm_score": -1,
"selected": false,
"text": "static class Program\n {\n static void Main(string[] args)\n {\n var input = new List<String>();\n for (int k = 0; k < 18; ++k)\n {\n input.Add(k.ToString());\n }\n var result = SplitList(input, 5);//I've used 5 but it can be any number\n \n foreach (var resul in result)\n {\n foreach (var res in result)\n {\n Console.WriteLine(res);\n }\n }\n }\n\n public static List<List<string>> SplitList (List<string> origList, int n)\n {//\"n\" is the number of parts you want to split your list into\n int splitLength = origList.Count / n; //splitLength is no. of items in each list bar the last one. (In case of overflow)\n List<List<string>> listCollection = new List<List<string>>();\n\n for ( int i = 0; i < n; i++ )\n {\n List<string> tempStrList = new List<string>();\n\n if ( i < n - 1 )\n {\n for ( int j = i * splitLength; j < (i + 1) * splitLength; j++ )\n {\n tempStrList.Add(origList[j]);\n }\n }\n else\n {\n for ( int j = i * splitLength; j < origList.Count; j++ )\n {\n tempStrList.Add(origList[j]);\n }\n }\n\n listCollection.Add(tempStrList);\n }\n\n return listCollection;\n }\n }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/817659/"
] |
74,595,617
|
<p>I am using the MauiCommunityToolkit and builder.ConfigureLifeCycleEvents in MauiProgram.cs like this:</p>
<pre><code> // Initialise the toolkit
builder.UseMauiApp<App>().UseMauiCommunityToolkit();
// the rest of the logic...
builder.ConfigureLifecycleEvents(events =>
{
#if ANDROID
events.AddAndroid(android => android
.OnStart((activity) => MyOnStart(activity))
.OnCreate((activity, bundle) => MyOnCreate(activity, bundle))
.OnResume((activity) => MyOnResume(activity))
.OnBackPressed((activity) => MyOnBackPressed(activity))
.OnPause((activity) => MyOnPause(activity))
.OnStop((activity) => MyOnStop(activity))
.OnDestroy((activity) => MyOnDestroy(activity)));
#endif
});
</code></pre>
<p>This is all good, but is there some way to subscribe to these events directly from a ViewModel?
I could use the messenger service to let the ViewModel know if these events are fired if not.
Is there a better way?
I am new to MAUI (and this may be a C# question anyway).</p>
|
[
{
"answer_id": 74595734,
"author": "Jason",
"author_id": 1338,
"author_profile": "https://Stackoverflow.com/users/1338",
"pm_score": 0,
"selected": false,
"text": "App.Current.OnStart += MyEventHandler;\n"
},
{
"answer_id": 74610088,
"author": "Liyun Zhang - MSFT",
"author_id": 17455524,
"author_profile": "https://Stackoverflow.com/users/17455524",
"pm_score": 2,
"selected": true,
"text": "OnStart public partial class App : Application\n{\n public App()\n {\n InitializeComponent();\n\n MainPage = new AppShell();\n }\n public static Window Window { get; private set; }\n protected override Window CreateWindow(IActivationState activationState)\n {\n Window window = base.CreateWindow(activationState);\n Window = window;\n return window;\n }\n}\n var window = App.Window;\n window.Stopped += (s, e) =>\n {\n Debug.WriteLine(\"=========stopped\");\n };\n window.Resumed += (s, e) =>\n {\n Debug.WriteLine(\"=========resumed\");\n };\n window.Destroying += (s, e) =>\n {\n Debug.WriteLine(\"=========destorying\");\n };\n CreateWindow"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1374091/"
] |
74,595,618
|
<p>I want to make tokens available for only 30 minutes to users. This is doable if we configure token lifetime policy but it's not working as I still get tokens valid for 1 hour.</p>
<p>Followed this suggested documentation <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/configure-token-lifetimes#create-a-policy-for-web-sign-in" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/active-directory/develop/configure-token-lifetimes#create-a-policy-for-web-sign-in</a></p>
<pre><code>$policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"00:30:00"}}') -DisplayName "Valid 30min" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"
# Get ID of the service principal
$sp = Get-AzureADServicePrincipal -Filter "DisplayName eq '<service principal display name>'"
# Assign policy to a service principal
Add-AzureADServicePrincipalPolicy -Id $sp.ObjectId -RefObjectId $policy.Id
</code></pre>
<p>How to make tokens valid for only 30 minutes?</p>
|
[
{
"answer_id": 74595734,
"author": "Jason",
"author_id": 1338,
"author_profile": "https://Stackoverflow.com/users/1338",
"pm_score": 0,
"selected": false,
"text": "App.Current.OnStart += MyEventHandler;\n"
},
{
"answer_id": 74610088,
"author": "Liyun Zhang - MSFT",
"author_id": 17455524,
"author_profile": "https://Stackoverflow.com/users/17455524",
"pm_score": 2,
"selected": true,
"text": "OnStart public partial class App : Application\n{\n public App()\n {\n InitializeComponent();\n\n MainPage = new AppShell();\n }\n public static Window Window { get; private set; }\n protected override Window CreateWindow(IActivationState activationState)\n {\n Window window = base.CreateWindow(activationState);\n Window = window;\n return window;\n }\n}\n var window = App.Window;\n window.Stopped += (s, e) =>\n {\n Debug.WriteLine(\"=========stopped\");\n };\n window.Resumed += (s, e) =>\n {\n Debug.WriteLine(\"=========resumed\");\n };\n window.Destroying += (s, e) =>\n {\n Debug.WriteLine(\"=========destorying\");\n };\n CreateWindow"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20045451/"
] |
74,595,636
|
<p>Suppose I have a Player Struct inside list</p>
<pre class="lang-elixir prettyprint-override"><code>[
%Player{name: "John", role: "nil"},
%Player{name: "Sansa", role: "nil"},
%Player{name: "Barry", role: "nil"},
%Player{name: "Edward", role: "nil"}
]
</code></pre>
<p>and I have a list of roles:</p>
<pre class="lang-elixir prettyprint-override"><code> Enum.shuffle([:werewolf, :farmer, :farmer, :farmer])
</code></pre>
<p>What function to use || How do I map it one by one into my expected result:</p>
<pre class="lang-elixir prettyprint-override"><code>[
%Player{name: "John", role: ":farmer"},
%Player{name: "Sansa", role: ":farmer"},
%Player{name: "Barry", role: ":werewolf"},
%Player{name: "Edward", role: ":farmer"}
]
</code></pre>
<p>I tried mapping, but with OO background, all I think is matching the index, which is not efficient in Elixir.</p>
|
[
{
"answer_id": 74595666,
"author": "sabiwara",
"author_id": 13979518,
"author_profile": "https://Stackoverflow.com/users/13979518",
"pm_score": 3,
"selected": true,
"text": "Enum.zip/2 Enum.zip_with/3 Enum.zip_with(players, roles, fn player, role -> Map.put(player, :role, role) end)\n"
},
{
"answer_id": 74595936,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "defmodule Player do\n defstruct name: nil, role: :farmer\n\n def setup do\n [werewolf | farmers] =\n [\"John\", \"Sansa\", \"Barry\", \"Edward\"]\n |> Enum.map(fn name -> %Player{name: name} end)\n |> Enum.shuffle()\n\n [%Player{werewolf | role: :werewolf} | farmers]\n end\nend\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11817809/"
] |
74,595,637
|
<p>I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems.</p>
<p>In my models.py:</p>
<pre><code>FuncionarioPathFoto = models.FileField(
"Foto",
upload_to = "images/",
db_column= "FuncionarioPathFoto",
null= False,
blank = False
)
</code></pre>
<p>In my views (I'm using inline forms, so the code is big):</p>
<pre><code>def create_funcionario(request):
if request.method == "GET":
form = FuncionariosForm
form_funcionarioadicional_factory = inlineformset_factory(Funcionarios, FuncionarioAdicional, form=FuncionarioAdicionalForm, extra=1)
form_funcionarioaux_factory = inlineformset_factory(Funcionarios, FuncionarioAux, form=FuncionarioAuxForm, extra=1)
form_funcionarioarquivo_factory = inlineformset_factory(Funcionarios, FuncionarioArquivo, form=FuncionarioArquivoForm, extra=1)
form_funcionarioadicional = form_funcionarioadicional_factory()
form_funcionarioaux = form_funcionarioaux_factory()
form_funcionarioarquivo = form_funcionarioarquivo_factory()
context = {
'form': form,
'form_funcionarioadicional': form_funcionarioadicional,
'form_funcionarioaux': form_funcionarioaux,
'form_funcionarioarquivo': form_funcionarioarquivo,
}
return render(request, '../templates/funcionarios/form_funcionarios.html', context)
elif request.method == "POST":
form = FuncionariosForm(request.POST)
form_funcionarioadicional_factory = inlineformset_factory(Funcionarios, FuncionarioAdicional, form=FuncionarioAdicionalForm)
form_funcionarioaux_factory = inlineformset_factory(Funcionarios, FuncionarioAux, form=FuncionarioAuxForm)
form_funcionarioarquivo_factory = inlineformset_factory(Funcionarios, FuncionarioArquivo, form=FuncionarioArquivoForm)
form_funcionarioadicional = form_funcionarioadicional_factory(request.POST)
form_funcionarioaux = form_funcionarioaux_factory(request.POST)
form_funcionarioarquivo = form_funcionarioarquivo_factory(request.POST)
if form.is_valid() and form_funcionarioadicional.is_valid() and form_funcionarioaux.is_valid() and form_funcionarioarquivo.is_valid():
funcionario = form.save()
form_funcionarioadicional.instance = funcionario
form_funcionarioaux.instance = funcionario
form_funcionarioarquivo.instance = funcionario
form_funcionarioadicional.save()
form_funcionarioaux.save()
form_funcionarioarquivo.save()
messages.success(request, "Funcionário adicionado com sucesso!")
return redirect(reverse('lista_funcionarios'))
else:
context = {
'form': form,
'form_funcionarioadicional': form_funcionarioadicional,
'form_funcionarioaux': form_funcionarioaux,
'form_funcionarioarquivo': form_funcionarioarquivo,
}
return render(request, '../templates/funcionarios/form_funcionarios.html', context)
</code></pre>
<p>I put this in my urls, and settings:
urls:</p>
<pre><code>if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT,
)
</code></pre>
<p>settings:</p>
<pre><code>MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code></pre>
<p>And I already tried to add <code><form method="POST" enctype="multipart/form-data"></code></p>
<p>but I was unsuccessful, when submitting my form, that field keeps giving error.</p>
<p>I tried uploading the file via /admin, and it went to the directory correctly with no errors.</p>
<p>what can i try to do to solve it?</p>
|
[
{
"answer_id": 74595666,
"author": "sabiwara",
"author_id": 13979518,
"author_profile": "https://Stackoverflow.com/users/13979518",
"pm_score": 3,
"selected": true,
"text": "Enum.zip/2 Enum.zip_with/3 Enum.zip_with(players, roles, fn player, role -> Map.put(player, :role, role) end)\n"
},
{
"answer_id": 74595936,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "defmodule Player do\n defstruct name: nil, role: :farmer\n\n def setup do\n [werewolf | farmers] =\n [\"John\", \"Sansa\", \"Barry\", \"Edward\"]\n |> Enum.map(fn name -> %Player{name: name} end)\n |> Enum.shuffle()\n\n [%Player{werewolf | role: :werewolf} | farmers]\n end\nend\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557228/"
] |
74,595,648
|
<p>Why can't I use boolean?</p>
<p>I want to check whether I am an admin or not.
and hide the button or disable the button</p>
<pre><code> const Authenticate = useSelector(userSelector)
let check :boolean = true;
<Link href="/stock" passHref className={Authenticate.level != 'admin' ? check=false:check=true}> // className redline
<ListItem
button
className={router.pathname === "/stock" ? "Mui-selected" : ""}
disabled={check}
>
<ListItemIcon>
<Layers />
</ListItemIcon>
<ListItemText primary="Stock" />
</ListItem>
</Link>
</code></pre>
<p><a href="https://i.stack.imgur.com/fsTjF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fsTjF.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74595666,
"author": "sabiwara",
"author_id": 13979518,
"author_profile": "https://Stackoverflow.com/users/13979518",
"pm_score": 3,
"selected": true,
"text": "Enum.zip/2 Enum.zip_with/3 Enum.zip_with(players, roles, fn player, role -> Map.put(player, :role, role) end)\n"
},
{
"answer_id": 74595936,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "defmodule Player do\n defstruct name: nil, role: :farmer\n\n def setup do\n [werewolf | farmers] =\n [\"John\", \"Sansa\", \"Barry\", \"Edward\"]\n |> Enum.map(fn name -> %Player{name: name} end)\n |> Enum.shuffle()\n\n [%Player{werewolf | role: :werewolf} | farmers]\n end\nend\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19032198/"
] |
74,595,653
|
<p>I want my <code>App</code> component to display keys every time <code>keys</code> changes. I'm doing this by passed keys as a <code>prop</code> of <code>App</code>:</p>
<pre><code>import * as React from "react";
import { render } from "react-dom";
import { useState, useEffect } from "react"
let keys: string[] = [];
// This is what is supposed to happen in the real app
// document.addEventListener("keypress", (event) => {
// keys.push(event.key)
// });
setTimeout(() => {
keys.push('a');
}, 1000)
function App({ keys }: { keys: string[] }) {
let [keysState, setKeysState] = useState(keys)
useEffect(() => {
setKeysState(keys)
}, [keys])
return (
<div>
{keysState.map((key: string) => (
<li>{key}</li>
))}
</div>
);
}
const rootElement = document.getElementById("root");
render(<App keys={keys} />, rootElement);
</code></pre>
<p>However, App isn't re-rendering and displaying keys new value:</p>
<p><a href="https://codesandbox.io/s/changing-props-on-react-root-component-forked-3mv0xf?file=/src/index.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/changing-props-on-react-root-component-forked-3mv0xf?file=/src/index.tsx</a></p>
<p>Why is this, and how to fix it?</p>
<p>Note: I tried: <code>setKeysState([...keys, 'a'])</code>. That doesn't re-render <code>App</code> either.</p>
<p>Live code: <a href="https://codesandbox.io/s/changing-props-on-react-root-component-forked-3mv0xf?file=/src/index.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/changing-props-on-react-root-component-forked-3mv0xf?file=/src/index.tsx</a></p>
|
[
{
"answer_id": 74595666,
"author": "sabiwara",
"author_id": 13979518,
"author_profile": "https://Stackoverflow.com/users/13979518",
"pm_score": 3,
"selected": true,
"text": "Enum.zip/2 Enum.zip_with/3 Enum.zip_with(players, roles, fn player, role -> Map.put(player, :role, role) end)\n"
},
{
"answer_id": 74595936,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "defmodule Player do\n defstruct name: nil, role: :farmer\n\n def setup do\n [werewolf | farmers] =\n [\"John\", \"Sansa\", \"Barry\", \"Edward\"]\n |> Enum.map(fn name -> %Player{name: name} end)\n |> Enum.shuffle()\n\n [%Player{werewolf | role: :werewolf} | farmers]\n end\nend\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122536/"
] |
74,595,656
|
<p>I'm really struggling with alignment here; I've spent hours looking online but to no avail. The circle, "Welcome to" text and rectangle are too far apart from each other like in the image below
<a href="https://i.stack.imgur.com/BuZTA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BuZTA.png" alt="enter image description here" /></a></p>
<p>But I would like for them to be like this, so that the user would not need to scroll down
<a href="https://i.stack.imgur.com/nSkAX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nSkAX.jpg" alt="enter image description here" /></a></p>
<p>Any help is appreciated.</p>
<p>I have tried the</p>
<pre><code>justifyContent: 'center',
alignItems: 'center',
</code></pre>
<p>properties, along with many more, but it still does not work.</p>
|
[
{
"answer_id": 74595666,
"author": "sabiwara",
"author_id": 13979518,
"author_profile": "https://Stackoverflow.com/users/13979518",
"pm_score": 3,
"selected": true,
"text": "Enum.zip/2 Enum.zip_with/3 Enum.zip_with(players, roles, fn player, role -> Map.put(player, :role, role) end)\n"
},
{
"answer_id": 74595936,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "defmodule Player do\n defstruct name: nil, role: :farmer\n\n def setup do\n [werewolf | farmers] =\n [\"John\", \"Sansa\", \"Barry\", \"Edward\"]\n |> Enum.map(fn name -> %Player{name: name} end)\n |> Enum.shuffle()\n\n [%Player{werewolf | role: :werewolf} | farmers]\n end\nend\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14597497/"
] |
74,595,679
|
<p>I'm trying to capture words in a string such that the first word starts with an s, and the regex stops matching if the next word also starts with an s.</p>
<p>For example. I have the string " Stack, Code and StackOverflow". I want to capture only " Stack, Code and " and not include "StackOverflow" in the match.</p>
<p>This is what I am thinking:</p>
<ol>
<li>Start with a space followed by an s.</li>
<li>Match everything except if the group is a space and an s (I'm using negative lookahead).</li>
</ol>
<p>The regex I have tried:</p>
<pre><code>(?<=\s)S[a-z -,]*(?!(\sS))
</code></pre>
<p>I don't know how to make it work.</p>
|
[
{
"answer_id": 74595666,
"author": "sabiwara",
"author_id": 13979518,
"author_profile": "https://Stackoverflow.com/users/13979518",
"pm_score": 3,
"selected": true,
"text": "Enum.zip/2 Enum.zip_with/3 Enum.zip_with(players, roles, fn player, role -> Map.put(player, :role, role) end)\n"
},
{
"answer_id": 74595936,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "defmodule Player do\n defstruct name: nil, role: :farmer\n\n def setup do\n [werewolf | farmers] =\n [\"John\", \"Sansa\", \"Barry\", \"Edward\"]\n |> Enum.map(fn name -> %Player{name: name} end)\n |> Enum.shuffle()\n\n [%Player{werewolf | role: :werewolf} | farmers]\n end\nend\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619368/"
] |
74,595,685
|
<p>I am working on a piece of code that is supposed to randomly display a view count on my site. It all works fine, except that it only runs once on page load. Its supposed to change the view count every 10 seconds after the initial first run. E.g. run this code snippet every 10 seconds after page load. I have tried multiple ways with <code>setInterval</code> but found that it is supposedly bad practice to use anyways after so many failed attempts?</p>
<p>Could you guys point me in the right direction. I have been reading posts on Stack overflow for hours and none had an answer to my issue. I have a feeling, that I am overlooking something obvious here.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.addEventListener('page:loaded', function() { //// Page has loaded and theme assets are ready
(function() {
var f = function() {
document.addEventListener('DOMContentLoaded', function() {
// Minimum view count
var minViews = 2;
// Maximum view count
var maxViews = 20;
// Text to show after the view count number
var text = 'people are viewing this product right now.';
// Create the new element to display on the page
$(".view-count").get().forEach(function(entry, index, array) {
var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;
$(entry).html($viewCountElement);
});
});
};
window.setInterval(f, 10000); //10 sec interval
f();
})();
});</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74595718,
"author": "brk",
"author_id": 2181397,
"author_profile": "https://Stackoverflow.com/users/2181397",
"pm_score": 1,
"selected": false,
"text": "setInterval DOMContentLoaded function elementDisplay() {\n // Minimum view count\n var minViews = 2;\n // Maximum view count\n var maxViews = 20;\n // Text to show after the view count number\n var text = 'people are viewing this product right now.';\n\n\n // Create the new element to display on the page\n $(\".view-count\").get().forEach(function(entry, index, array) {\n var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;\n $(entry).html($viewCountElement);\n });\n\n}\n\n\ndocument.addEventListener('DOMContentLoaded', function() {\n window.setInterval(elementDisplay, 10000); //10 sec interval\n});\n"
},
{
"answer_id": 74595887,
"author": "Shashank Malviya",
"author_id": 8406046,
"author_profile": "https://Stackoverflow.com/users/8406046",
"pm_score": 0,
"selected": false,
"text": "setInterval setInterval jQuery.ready DOMContentLoaded var interval;\n$(document).ready(function(){\n console.log(\"I am initialized\")\n var f = function() {\n console.log(\"I am called\")\n // Minimum view count\n var minViews = 2;\n // Maximum view count\n var maxViews = 20;\n // Text to show after the view count number\n var text = 'people are viewing this product right now.';\n // Create the new element to display on the page\n $(\".view-count\").get().forEach(function(entry, index, array) {\n var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;\n $(entry).html($viewCountElement);\n });\n };\n interval = setInterval(f, 10000);\n\n});\n\n$(window).on(\"beforeunload\", function() {\n // clear the interval when window closes\n return clearInterval(interval);\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9075184/"
] |
74,595,687
|
<p>I want to save my process definition. But so far, I only know that my process files will be saved when deploying.</p>
<p>But I just want to save without deploying.</p>
<p>How can I do this ?</p>
|
[
{
"answer_id": 74595718,
"author": "brk",
"author_id": 2181397,
"author_profile": "https://Stackoverflow.com/users/2181397",
"pm_score": 1,
"selected": false,
"text": "setInterval DOMContentLoaded function elementDisplay() {\n // Minimum view count\n var minViews = 2;\n // Maximum view count\n var maxViews = 20;\n // Text to show after the view count number\n var text = 'people are viewing this product right now.';\n\n\n // Create the new element to display on the page\n $(\".view-count\").get().forEach(function(entry, index, array) {\n var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;\n $(entry).html($viewCountElement);\n });\n\n}\n\n\ndocument.addEventListener('DOMContentLoaded', function() {\n window.setInterval(elementDisplay, 10000); //10 sec interval\n});\n"
},
{
"answer_id": 74595887,
"author": "Shashank Malviya",
"author_id": 8406046,
"author_profile": "https://Stackoverflow.com/users/8406046",
"pm_score": 0,
"selected": false,
"text": "setInterval setInterval jQuery.ready DOMContentLoaded var interval;\n$(document).ready(function(){\n console.log(\"I am initialized\")\n var f = function() {\n console.log(\"I am called\")\n // Minimum view count\n var minViews = 2;\n // Maximum view count\n var maxViews = 20;\n // Text to show after the view count number\n var text = 'people are viewing this product right now.';\n // Create the new element to display on the page\n $(\".view-count\").get().forEach(function(entry, index, array) {\n var $viewCountElement = Math.floor(Math.random() * (maxViews - minViews) + minViews) + ' ' + text;\n $(entry).html($viewCountElement);\n });\n };\n interval = setInterval(f, 10000);\n\n});\n\n$(window).on(\"beforeunload\", function() {\n // clear the interval when window closes\n return clearInterval(interval);\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376176/"
] |
74,595,703
|
<p>After submission for review, I got this from Apple review:</p>
<blockquote>
<p>We noticed that your app requests the user’s consent to access the camera and photos, but doesn’t sufficiently explain the use of the camera and photos in the purpose string.</p>
</blockquote>
<p>In my app, camera and gallery access is needed in various places like for uploading product images, sending images to chat, posting images in the news feed, and uploading profile photo.</p>
<p>Apple requires an explanation to why the camera and gallery are being accessed.
If I explain the use for uploading profile image, this is irrelevant if they upload a product and also needs another explanation if the user will send photos to chat.</p>
<p>So the question is how can I generalize the camera's purpose string in a way that it can cover all my camera usage given that the purpose string is only one.</p>
<p>Or is there a way to write a camera purpose string for each and every camera usage?</p>
|
[
{
"answer_id": 74595778,
"author": "Kamlendra Pandey",
"author_id": 5340621,
"author_profile": "https://Stackoverflow.com/users/5340621",
"pm_score": 1,
"selected": false,
"text": "<key>NSCameraUsageDescription</key>\n <string>Access to your camera is required to capture photos required for loan processing or your profile.</string>\n <key>NSLocationUsageDescription</key>\n <string>To show your location on the map.</string>\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16146701/"
] |
74,595,711
|
<p>I am using <code>.cshtml</code> to send a <code>POST</code> request to my controller. The following is my <code>.cshtml</code> form.</p>
<pre class="lang-cs prettyprint-override"><code>@using (Html.BeginForm("PostTest, "Test", FormMethod.Post))
{
<input type="number" name="test" min="0" max="99999" />
<button type="submit">Submit</button>
}
</code></pre>
<p>The number entered by the user will be sent to the controller as shown below:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpPost]
public ActionResult PostTest(int test)
{
// process the data here
}
</code></pre>
<p>I am only expecting about 5 digits for the number that is passed in. However, if I enter a very large value with like 100 digits, the program crashes because I am using <code>int</code> data type. Even if I change to <code>long</code> data type, this problem still occurs if I enter a large number. I think the program crashes when the argument was passed in way beyond its limit.</p>
<p>I did set a range to limit the data passed in from 0 to 99999. However, I want to prevent such a scenario in my controller action too. Is that possible?</p>
<p>How do I solve this issue?</p>
|
[
{
"answer_id": 74596238,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 1,
"selected": false,
"text": "check if it convert into a int is in the desired range [HttpPost]\n public ActionResult PostTest(string test)\n {\n int number = -1;\n var result = int.TryParse(test, out number);\n if (result && number >= 0 && number <= 99999)\n return Ok(number);\n else\n return BadRequest(\"the number is in the wrong format ... \");\n }\n"
},
{
"answer_id": 74596341,
"author": "Leandro Bardelli",
"author_id": 888472,
"author_profile": "https://Stackoverflow.com/users/888472",
"pm_score": 0,
"selected": false,
"text": "public class MyTest {\n [Range(0, 2147483646)]\n public int myproperty {get;set;}\n}\n\n\n\n [HttpPost]\n public ActionResult PostTest(MyTest test) \n {\n // process the data here\n }\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19561210/"
] |
74,595,712
|
<p>I have tried to run a pretty simple code</p>
<pre><code>x = input("What's x? ")
y = input("What's y? ")
z= int(x) + int(y)
print (z)
</code></pre>
<p>But, when I try to run that code from the terminal writing "name_of_the_file.py", I find this error:</p>
<p>"The term "name_of_the_file.py" is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."</p>
<p>If a right click on where you write the code, and then click on "run python file in terminal", it runs!</p>
<p>I am taking the CS50P, and I see that this should be possible because the teacher is able to do that. What am I doing wrong guys?</p>
|
[
{
"answer_id": 74596732,
"author": "JialeDu",
"author_id": 19133920,
"author_profile": "https://Stackoverflow.com/users/19133920",
"pm_score": 1,
"selected": false,
"text": "& c:/WorkSpace/pytest11/.venv/Scripts/python.exe c:/WorkSpace/pytest11/main.py python main.py\n main.py"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619489/"
] |
74,595,714
|
<p>I have an infinite loop thread that sets an event when a sensor is high/true</p>
<pre><code>event = threading.Event()
def eventSetter():
while True:
if sensor:
event.set()
else:
event.clear()
th1 = threading.thread(target=eventSetter)
th1.start
</code></pre>
<p>and I have a function capture that takes 5 sec to execute</p>
<pre><code>def capture():
time.sleep(2) #sleep represents a task that takes 2 sec to finish
time.sleep(1)
time.sleep(2)
return
</code></pre>
<p>now I want to exit the function capture in the middle of its task whenever the event is set</p>
<p>for example if task 1 takes 5sec to finish and the event occurs at time 2sec, the task should not continue at time 2sec and the function should exit</p>
<hr />
<p>I tried checking for the event every line but i don't know how to exit in the middle of its task thus it waits for the task to finish before return applies also I didn't like the look of multiple if/return</p>
<pre><code>def capture():
time.sleep(2) #sleep represents a task that takes sec to finish
if event.is_set():
return
time.sleep(1)
if event.is_set():
return
time.sleep(2)
if event.is_set():
return
</code></pre>
|
[
{
"answer_id": 74596732,
"author": "JialeDu",
"author_id": 19133920,
"author_profile": "https://Stackoverflow.com/users/19133920",
"pm_score": 1,
"selected": false,
"text": "& c:/WorkSpace/pytest11/.venv/Scripts/python.exe c:/WorkSpace/pytest11/main.py python main.py\n main.py"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12171816/"
] |
74,595,716
|
<p>I want Odoo to show an Xpath or not, depending on a condition</p>
<p>I have this 3 fields</p>
<pre><code>lots_id = fields.Many2one('stock.production.lot', 'Lot/Serial Number')
q_auth = fields.Boolean(related='lot_id.q_auth', string="Quality Auth.")
needs_auth= fields.Boolean("Needs Auth")
</code></pre>
<p>If <code>needs_auth == False</code>, i need to show this xpath</p>
<pre><code> <xpath expr="//field[@name='lot_id']" position="replace">
<field name="q_auth" invisible="1"/>
<field name="lots_id" groups="stock.group_production_lot"
domain="[('product_id','=?', product_id)]"
context="{'product_id': product_id}"/>
</xpath>
</code></pre>
<p>but if <code>needs_auth == True</code> I need the Xpath to be like this</p>
<pre><code> <xpath expr="//field[@name='lot_id']" position="replace">
<field name="q_auth" invisible="1"/>
<field name="lots_id" groups="stock.group_production_lot"
domain="[('product_id','=?', product_id),('q_auth','!=',False)]"
context="{'product_id': product_id}"/>
</xpath>
</code></pre>
<p>You can see that the only difference is in the domain.
I don't know if this is possible to do it in XML, but in case is not possible, how can I do it with Python?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74596732,
"author": "JialeDu",
"author_id": 19133920,
"author_profile": "https://Stackoverflow.com/users/19133920",
"pm_score": 1,
"selected": false,
"text": "& c:/WorkSpace/pytest11/.venv/Scripts/python.exe c:/WorkSpace/pytest11/main.py python main.py\n main.py"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19883757/"
] |
74,595,730
|
<p>Hi How would I be able to convert millisecond to HH:MM:SS format in mongodb? Below is my sample data.</p>
<pre><code>{
"Item":"Test1",
"millisecond" : 188760000
},
{
"Item":"Test2",
"millisecond" : 23280000
},
{
"Item":"Test3",
"millisecond" : 128820000
},
</code></pre>
<p>Expected output will be</p>
<pre><code>{
"Item":"Test1",
"hrFormat" : 62:22:00
},
{
"Item":"Test2",
"millisecond" : 06:28:00
},
{
"Item":"Test3",
"millisecond" : 35:47:00
},
</code></pre>
|
[
{
"answer_id": 74595782,
"author": "Victor Lagunas",
"author_id": 10038617,
"author_profile": "https://Stackoverflow.com/users/10038617",
"pm_score": 0,
"selected": false,
"text": "{$toDate: 120000000000.5}. \n//result ISODate(\"1973-10-20T21:20:00Z\")\n"
},
{
"answer_id": 74597383,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 2,
"selected": true,
"text": "aggregate db.collection.aggregate([\n {\n $project: {\n \"Item\": 1,\n \"hours\": {\n $floor: {\n $divide: [\n \"$millisecond\",\n 3600000 // millis in 1h\n ]\n }\n },\n \"minutes\": {\n $floor: {\n $divide: [\n {\n $mod: [\n \"$millisecond\",\n 3600000\n ]\n },\n 60000 // millis in 1m\n ]\n }\n }\n }\n },\n {\n $project: {\n \"Item\": 1,\n \"millisecond\": {\n $concat: [\n {\n $toString: \"$hours\"\n },\n \":\",\n {\n $toString: \"$minutes\"\n },\n \":00\"\n ]\n }\n }\n }\n])\n"
},
{
"answer_id": 74599081,
"author": "Wernfried Domscheit",
"author_id": 3027266,
"author_profile": "https://Stackoverflow.com/users/3027266",
"pm_score": 1,
"selected": false,
"text": "db.collection.aggregate([\n {\n $set: {\n hours: {\n $concat: [\n {\n $toString: {\n $sum: [\n -24,\n { $multiply: [{ $dayOfYear: { $toDate: { $toLong: \"$millisecond\" } } }, 24] },\n { $hour: { $toDate: { $toLong: \"$millisecond\" } } },\n ]\n }\n },\n {\n $dateToString: {\n date: { $toDate: { $toLong: \"$millisecond\" } },\n format: \":%M:%S\"\n }\n }\n ]\n }\n }\n }\n])\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16478523/"
] |
74,595,732
|
<p>When I customize the theme to set a font...</p>
<ol>
<li>some text gets properly styled (e.g. <code><mat-card-title> <mat-card-action></code> etc)</li>
<li>but some other does not (e.g. <code><p> <span> <mat-card-content></code>) and default to Roboto... <strong>Shouldn't those take the body-1 style?</strong> Note that I am using mat-card as an example, but the same happens with other components.
<a href="https://material.angular.io/guide/typography" rel="nofollow noreferrer">https://material.angular.io/guide/typography</a></li>
</ol>
<p><a href="https://i.stack.imgur.com/fP6cA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fP6cA.png" alt="enter image description here" /></a></p>
<p>Minimal steps to repro:</p>
<ul>
<li>Add a Google font to index.html</li>
<li>Configure styles in styles.scss so that the new font is the default for all levels (should be used everywhere)</li>
</ul>
<pre><code>$theme-primary: mat.define-palette(mat.$indigo-palette);
$theme-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);
$my-typography: mat.define-typography-config(
$font-family: "'Nerko One', cursive",
);
$theme: mat.define-light-theme(
(
color: (
primary: $theme-primary,
accent: $theme-accent,
),
typography: $my-typography,
)
);
@include mat.all-component-themes($theme);
</code></pre>
<p>Here is an example, you can see that the title etc are styled, but not the content of the card:
<a href="https://stackblitz.com/edit/angular-wan6f9?file=src/app/card-actions-example.html" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-wan6f9?file=src/app/card-actions-example.html</a></p>
<p>I tried a few approaches, including configuring each level which did not work. The only thing that works is to hardcode the default to the root of the document, which I would rather not do.</p>
|
[
{
"answer_id": 74614277,
"author": "rexsuecia",
"author_id": 1007013,
"author_profile": "https://Stackoverflow.com/users/1007013",
"pm_score": 2,
"selected": false,
"text": "@include mat.all-component-typographies($typography); @include mat.all-component-themes($my-theme); $typography"
},
{
"answer_id": 74654170,
"author": "Poveu",
"author_id": 8613553,
"author_profile": "https://Stackoverflow.com/users/8613553",
"pm_score": 0,
"selected": false,
"text": "@include mat.all-component-themes($theme); body { ... } body {\n @include mat.all-component-themes($theme);\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850438/"
] |
74,595,772
|
<p>I have a dataframe <code>df</code> where one column <code>'Images'</code> contains a bunch of HTML strings in each row from which I would like to extract URLs, that have a specific <code>Start</code> and <code>End</code> characters. Ideally they would then be turned into columns for each URL extracted.</p>
<p><code>df</code> example:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
'Description': ['USB Emergency Light Torch', 'USB RC LED DESKLAMP DL013', 'Green torch light with strap', 'Sensor Night Light W Switch A78'],
'SKU': ['9023578-001001', '9023464-001001', '9023463-001001', '9023290-001001'],
'Images': ['[{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023578-temp.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023578-3.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023578.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023578-temp.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023578.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023578-1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023578-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023578-3.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/4c186adb30ce12db4dc6d068ea20241d/9/0/9023578-temp.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/wysiwyg/mageplus/_images/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://image.useinsider.com/default/action-builder/instant-purchase.png"}]',
'[{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023464-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023464-1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023464.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023464-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023464.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023464-1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/4c186adb30ce12db4dc6d068ea20241d/9/0/9023464-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/wysiwyg/mageplus/_images/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://image.useinsider.com/default/action-builder/instant-purchase.png"}]',
'[{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023463-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023463-1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023463.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023463-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023463.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023463-1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/4c186adb30ce12db4dc6d068ea20241d/9/0/9023463-2.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/wysiwyg/mageplus/_images/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://image.useinsider.com/default/action-builder/instant-purchase.png"}]',
'[{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/logo/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023290-2_1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023290.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/9/0/9023290-1_1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023290-2_1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023290-1_1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/f0229e02574c793c147c08297c074a46/9/0/9023290.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/catalog/product/cache/4c186adb30ce12db4dc6d068ea20241d/9/0/9023290-2_1.jpg"},{"Images":"","Images-src":"https://www.website.com.my/media/wysiwyg/mageplus/_images/stores/3/logo-b2b_1_-min.png"},{"Images":"","Images-src":"https://image.useinsider.com/default/action-builder/instant-purchase.png"}]']
})
</code></pre>
<p>Which looks like this:
<a href="https://i.stack.imgur.com/DyKdN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DyKdN.jpg" alt="enter image description here" /></a></p>
<p>Start: <code>https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d</code></p>
<p>End: <code>.jpg</code></p>
<p>The other URLs and text can be ignored.</p>
<p>Desired Output (one URL per column, added to the end of the <code>df</code>; there might be more than 3 results, so the number of columns added is variable):</p>
<pre class="lang-none prettyprint-override"><code>https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/8/9/8993791-temp.jpg
https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/8/9/8993791-3.jpg
https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d/8/9/8993791.jpg
</code></pre>
<p>Here's an image example of the desired output in case:
<a href="https://i.stack.imgur.com/qEXfb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEXfb.jpg" alt="enter image description here" /></a></p>
<p>So far I tried this code below (it only extracts to a single cell with "," as a joiner, haven't figured the column splitting yet) but the output is a seemingly empty cell with just <code>''</code> contained within:</p>
<pre class="lang-py prettyprint-override"><code>df['img_lines'] = df['Images'].str.findall('^https://www.website.com.my/media/catalog/product/cache/3f354f4955006fba9bb013076742094d.*\.jpg$').str.join(",")
</code></pre>
|
[
{
"answer_id": 74614277,
"author": "rexsuecia",
"author_id": 1007013,
"author_profile": "https://Stackoverflow.com/users/1007013",
"pm_score": 2,
"selected": false,
"text": "@include mat.all-component-typographies($typography); @include mat.all-component-themes($my-theme); $typography"
},
{
"answer_id": 74654170,
"author": "Poveu",
"author_id": 8613553,
"author_profile": "https://Stackoverflow.com/users/8613553",
"pm_score": 0,
"selected": false,
"text": "@include mat.all-component-themes($theme); body { ... } body {\n @include mat.all-component-themes($theme);\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11332149/"
] |
74,595,784
|
<p>In addition to pointers, C++ also provides references that behave similarly. In addition to these built-in types, it also gives the option to construct custom types that mimic this behavior.</p>
<p>Take these two custom types:</p>
<pre class="lang-cpp prettyprint-override"><code>class Ptr
{
private:
int inner_;
public:
int& operator*() { return inner_; }
const int& operator*() const { return inner_; }
};
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>class Ref
{
private:
int inner_;
public:
operator int&() { return inner_; }
operator const int&() const { return inner_; }
};
</code></pre>
<p>These two types are used in different ways:</p>
<pre><code>void f(const int& x);
auto r = Ref{};
auto p = Ptr{};
f(r);
f(*p);
</code></pre>
<p>These two are not equivalent but serve largely the same purpose. In the C++ standard library, example types are:</p>
<ul>
<li>pointer behavior: <code>std::optional</code>, <code>std::unique_ptr</code></li>
<li>reference behavior: <code>std::reference_wrapper</code>, <code>std::atomic</code></li>
</ul>
<p>In case we are designing a custom data type for which both pointer behavior and reference behavior are reasonable, which one should be chosen?</p>
|
[
{
"answer_id": 74596984,
"author": "Ayxan Haqverdili",
"author_id": 10147399,
"author_profile": "https://Stackoverflow.com/users/10147399",
"pm_score": 2,
"selected": false,
"text": "operator. ref.foo() std::reference_wrapper ref.get().foo()"
},
{
"answer_id": 74621453,
"author": "Post Self",
"author_id": 3560202,
"author_profile": "https://Stackoverflow.com/users/3560202",
"pm_score": 0,
"selected": false,
"text": "Ptr{} + Ptr{} *Ptr{} + *Ptr{} Ref{} + Ref{} operator+ Ref Ptr{} Ref{}"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560202/"
] |
74,595,788
|
<p>I would like to add new inputs using jQuery, however, after clicking the add input which uses jQuery to add another of such element below, it removes the inputs before.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var num = 2;
document.getElementById('add').addEventListener("click", addInput);
function addInput() {
var newInput = `
<div>
<input type="date" id="start" name="avail[startdate${num}] value="" min="" max="" />
<input type="range" name = "avail[startdate${num}] value="" min="0" max="23" oninput="this.nextElementSibling.value = this.value" >
<output>12</output><span>:00 (GMT+8) </span>
</div>
`
// '<input type="text" name="input'+num+'"/><br> <br>';
document.getElementById('demo').innerHTML += newInput;
num++;
}
document.querySelectorAll('input[type="range"]').forEach((input) => {
input.addEventListener('mousedown', () => window.getSelection().removeAllRanges());
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Availability</p>
<div id="demo">
<div class="">
<input type="date" id="start" name="avail[startdate1]" value="" min="" max="">
<input type="range" value="" name="avail[startdate1]" min="0" max="23" oninput="this.nextElementSibling.value = this.value">
<output>12</output><span>:00 (GMT+8) </span>
<br>
</div>
</div>
<input type="button" id="add" value="Add input" /></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74595840,
"author": "Ali Sheikhpour",
"author_id": 4700922,
"author_profile": "https://Stackoverflow.com/users/4700922",
"pm_score": -1,
"selected": false,
"text": "document.getElementById('demo').innerHTML innerHTML append"
},
{
"answer_id": 74596104,
"author": "4b0",
"author_id": 965146,
"author_profile": "https://Stackoverflow.com/users/965146",
"pm_score": 1,
"selected": false,
"text": "parent insertAdjacentHTML var num = 2;\ndocument.getElementById('add').addEventListener(\"click\", addInput);\n\nfunction addInput() {\n var parent = document.getElementById('demo');\n var newInput = `\n<div>\n<input type=\"date\" id=\"start\" name=\"avail[startdate${num}] value=\"\" min=\"\" max=\"\" />\n<input type=\"range\" name = \"avail[startdate${num}] value=\"\" min=\"0\" max=\"23\" oninput=\"this.nextElementSibling.value = this.value\" >\n<output>12</output><span>:00 (GMT+8) </span>\n</div>\n`\n // '<input type=\"text\" name=\"input'+num+'\"/><br> <br>';\n parent.insertAdjacentHTML('beforeend', newInput);\n num++;\n}\ndocument.querySelectorAll('input[type=\"range\"]').forEach((input) => {\n input.addEventListener('mousedown', () => window.getSelection().removeAllRanges());\n}); <p>Availability</p>\n<div id=\"demo\">\n <div class=\"\">\n <input type=\"date\" id=\"start\" name=\"avail[startdate1]\" value=\"\" min=\"\" max=\"\">\n <input type=\"range\" value=\"\" name=\"avail[startdate1]\" min=\"0\" max=\"23\" oninput=\"this.nextElementSibling.value = this.value\">\n <output>12</output><span>:00 (GMT+8) </span>\n <br>\n </div>\n</div>\n<input type=\"button\" id=\"add\" value=\"Add input\" />"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16806358/"
] |
74,595,789
|
<p>In my backend, which is nodejs for information only, the data is returned fine</p>
<p>But I had to populate the data returned in the response</p>
<p>To show the name of the user, not his ID</p>
<p>The response returns in the following form</p>
<p><a href="https://i.stack.imgur.com/4m2AL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4m2AL.png" alt="enter image description here" /></a></p>
<p>When I try to access the username, which is in this case (realName ) in my react application, a problem occurs as in the title of this question</p>
<p>I am attaching all the information and if anyone needs more information, do not hesitate to request it</p>
<p><strong>this hook</strong></p>
<pre><code>import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { getOneTicket } from "../../store/actions";
const TicketsDetailsHook = (id) => {
const dispatch = useDispatch();
//to get state from redux
const { ticketsDetiles, isTicketCreated, error } = useSelector((state) => ({
ticketsDetiles: state.Tickets.ticketsDetiles,
isTicketCreated: state.Tickets.isTicketCreated,
error: state.Tickets.error,
}));
let item = [];
if(isTicketCreated===true){
if (ticketsDetiles){
item = ticketsDetiles;
console.log(ticketsDetiles);
}
}
//else{item = [];}
//when first load
useEffect(() => {
dispatch(getOneTicket(id))
}, [])
return [item];
};
export default TicketsDetailsHook;
</code></pre>
<p><strong>this components</strong></p>
<pre><code>import React from "react";
import { useParams } from "react-router-dom";
import { Col, Row } from "reactstrap";
import TicketsDetailsHook from "../../../Hooks/TicketsHooks/TicketsDetailsHook";
const Section = () => {
const { id } = useParams();
const [item] = TicketsDetailsHook(id);
return (
<React.Fragment>
<Col lg={12}>
<div className="bg-soft-warning">
<Row>
<div className="col-md">
<h4 className="fw-semibold" id="ticket-title">
erere
</h4>
<div className="hstack gap-3 flex-wrap">
<div className="text-muted">
<i className="ri-building-line align-bottom me-1"></i>{" "}
<span id="ticket-client">{item.addedBy.realName}</span>
</div>
</div>
</div>
</Row>
</div>
</Col>
</React.Fragment>
);
};
export default Section;
</code></pre>
<p>This line is not accepted and herein lies the problem</p>
<p><strong>{item.addedBy.realName}</strong></p>
<p>note :</p>
<p>If I cancel the populate process, everything works fine, of course, except that I will get the ID for the laser, and not its name</p>
<p><strong>this console.log(item)</strong>
<a href="https://i.stack.imgur.com/knbUV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/knbUV.png" alt="enter image description here" /></a></p>
<p><strong>this conslo.log component file</strong>
<a href="https://i.stack.imgur.com/KOtd6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KOtd6.png" alt="enter image description here" /></a></p>
<p>The error only appears when I try to log in</p>
<p><strong>item.addedBy.realName</strong></p>
<p>This is the error log in the console</p>
<p><strong>Error: Objects are not valid as a React child (found: object with keys {_id, realName, id}). If you meant to render a collection of children, use an array instead.</strong></p>
<p>As you can see, the rest of the data is fetched correctly, except for</p>
<p><strong>{item.data?.addedBy.realName}</strong>
<a href="https://i.stack.imgur.com/N3vPu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N3vPu.png" alt="enter image description here" /></a>
return empty
<a href="https://i.stack.imgur.com/hkBfJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hkBfJ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74596392,
"author": "Tehila",
"author_id": 16142839,
"author_profile": "https://Stackoverflow.com/users/16142839",
"pm_score": 1,
"selected": false,
"text": "Section item.data?.addedBy.realName ? isTicketCreated item Section const [item] = TicketsDetailsHook(id); data const item = TicketsDetailsHook(id);\n item[0].data?.addedBy.realName"
},
{
"answer_id": 74596888,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "return item console.log(item)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10598318/"
] |
74,595,796
|
<p>check_df has two column one with code and other is blank
in_df has 2 column one is merged column and other is V_ORG_UNIT_NAME_LEVEL14.</p>
<p>I want to check each code of "V_ORG_UNIT_CODE" from check_df inside "merged column from in_df.
If it matches(it may contain that value may not be exact match) i want corresponding "OutputDisplay" in check_df empty column "V_ORG_UNIT_CODE"</p>
<p>check_df</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>V_ORG_UNIT_CODE</th>
<th>V_ORG_UNIT_NAME_LEVEL14</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td></td>
</tr>
<tr>
<td>def</td>
<td></td>
</tr>
<tr>
<td>gth</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>in_df</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>OutputDisplay</th>
<th>MergedColumn</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>das<strong>abc</strong>raf</td>
</tr>
<tr>
<td>456</td>
<td>asfgfdg</td>
</tr>
<tr>
<td>567</td>
<td>as<em>0def</em>!gfhg</td>
</tr>
</tbody>
</table>
</div>
<p>Expected Output</p>
<p>check_df</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>V_ORG_UNIT_CODE</th>
<th>V_ORG_UNIT_NAME_LEVEL14</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td>123</td>
</tr>
<tr>
<td>def</td>
<td>567</td>
</tr>
<tr>
<td>gth</td>
<td>NA</td>
</tr>
</tbody>
</table>
</div>
<pre><code>for x in check_df["V_ORG_UNIT_CODE"]:
for y,z in zip(in_df["MergedColumn"],in_df["OutputDisplay"]):
if (y.__contains__(x)):
print(z)
check_df['V_ORG_UNIT_NAME_LEVEL14']=check_df['V_ORG_UNIT_NAME_LEVEL14'].append(z)
</code></pre>
<p>My print(z) is correct output but I am getting error when i am appending it in a dataframe column</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-6-e4f45d7306ae> in <module>
3 for x in check_df["V_ORG_UNIT_CODE"]:
4 for y,z in zip(in_df["MergedColumn"],in_df["OutputDisplay"]):
----> 5 if (y.__contains__(x)):
6 # print(z)
7 # check_df['V_ORG_UNIT_NAME_LEVEL14']=check_df['V_ORG_UNIT_NAME_LEVEL14'].append(z)
TypeError: 'in <string>' requires string as left operand, not int
</code></pre>
|
[
{
"answer_id": 74596392,
"author": "Tehila",
"author_id": 16142839,
"author_profile": "https://Stackoverflow.com/users/16142839",
"pm_score": 1,
"selected": false,
"text": "Section item.data?.addedBy.realName ? isTicketCreated item Section const [item] = TicketsDetailsHook(id); data const item = TicketsDetailsHook(id);\n item[0].data?.addedBy.realName"
},
{
"answer_id": 74596888,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "return item console.log(item)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11344916/"
] |
74,595,808
|
<p>I have an array like this</p>
<pre><code>[
123456 => 'John Doe'
654321 => 'Doe John'
]
</code></pre>
<p>I want to change the array key (123456 and 654321) into an index (0,1,2,3,....,n) and save it into value, the expected result looks like this</p>
<pre><code>array(
0 => array(
'name' => 'John Doe',
'code' => 123456.
),
1 => array(
'name' => 'Doe John',
'code' => 654321.
),
)
</code></pre>
<p>this is the code i have tried, i have only gotten so far</p>
<pre><code>$thearray= array_map(function ($value, $key) {
return $key;
}, $thearray, array_keys($thearray));
</code></pre>
|
[
{
"answer_id": 74596392,
"author": "Tehila",
"author_id": 16142839,
"author_profile": "https://Stackoverflow.com/users/16142839",
"pm_score": 1,
"selected": false,
"text": "Section item.data?.addedBy.realName ? isTicketCreated item Section const [item] = TicketsDetailsHook(id); data const item = TicketsDetailsHook(id);\n item[0].data?.addedBy.realName"
},
{
"answer_id": 74596888,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "return item console.log(item)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19591044/"
] |
74,595,810
|
<p>I'm trying to create 3 arrays of type int using malloc, then initialize all 3 arrays to the same value (10) in a for look, like this:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main() {
int* arr1;
int* arr2;
int* arr3;
arr1 =(int*) malloc(5* sizeof(int));
arr2 = (int*) malloc(5* sizeof(int));
arr3 =(int*) malloc(5* sizeof(int));
for(int j = 0; j< 5 ; j++){
*arr1 = 10;
*arr2 = 10;
*arr3 = 10;
arr1 += sizeof(int);
arr2 += sizeof(int);
arr3 += sizeof(int);
}
</code></pre>
<p>After this I reset all 3 pointers to their original position like this:</p>
<pre><code> arr1 -= (sizeof(int) * 5);
arr2 -= (sizeof(int) * 5);
arr3 -= (sizeof(int) * 5);
</code></pre>
<p>Then I want to print all the values stored, I try to do it like this:</p>
<pre><code> for(int k = 0; k < 5; k++){
arr1 += sizeof(int);
arr2 += sizeof(int);
arr3 += sizeof(int);
printf("arr1 %d\n",*arr1);
printf("arr2 %d\n",*arr2);
printf("arr3 %d\n",*arr3);
}
}
</code></pre>
<p>I expect all the values printed to be 10 but I'm getting some random values in unexpected places like this:</p>
<pre><code>arr1 10
arr2 10
arr3 10
arr1 10
arr2 10
arr3 846361185
arr1 10
arr2 10
arr3 10
arr1 10
arr2 829583969
arr3 10
arr1 10
arr2 10
arr3 0
</code></pre>
<p>I have absolutely no clue what is wrong, I've been stuck trying to solve this for hours without any result.</p>
<p>Can someone explain what's happening?.</p>
|
[
{
"answer_id": 74596392,
"author": "Tehila",
"author_id": 16142839,
"author_profile": "https://Stackoverflow.com/users/16142839",
"pm_score": 1,
"selected": false,
"text": "Section item.data?.addedBy.realName ? isTicketCreated item Section const [item] = TicketsDetailsHook(id); data const item = TicketsDetailsHook(id);\n item[0].data?.addedBy.realName"
},
{
"answer_id": 74596888,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "return item console.log(item)"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619544/"
] |
74,595,824
|
<p>This is my Object:</p>
<pre><code>{
"title": "Student Details",
"education": "under graduate",
"courses": [
{
"courseCode": "101",
"course": "Physics"
},
{
"courseCode": "102",
"course": "Chemistry"
},
{
"course": "Math",
"courseCode": "103"
}
],
"studentId": "xyz202267"
}
</code></pre>
<p>I want to get the courseCode when the course name is the input. If I send 'Math', then 103 needs to be returned.</p>
<p>I was able to get all the courseCodes:</p>
<pre><code>let ans = temp.courses.map(obj => obj.courseCode)
</code></pre>
<p>How do I get just the code when course is input?</p>
|
[
{
"answer_id": 74595830,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": false,
"text": "find map let ans = temp.courses.find(obj => obj.course === 'Math' )\n\nconsole.log(ans?.courseCode)\n"
},
{
"answer_id": 74598275,
"author": "Daryll Castelino",
"author_id": 18140151,
"author_profile": "https://Stackoverflow.com/users/18140151",
"pm_score": 1,
"selected": false,
"text": "find map ? const temp = {\n \"title\": \"Student Details\",\n \"education\": \"under graduate\",\n \"courses\": [\n {\n \"courseCode\": \"101\",\n \"course\": \"Physics\"\n },\n {\n \"courseCode\": \"102\",\n \"course\": \"Chemistry\"\n },\n {\n \"course\": \"Math\",\n \"courseCode\": \"103\"\n }\n ],\n \"studentId\": \"xyz202267\"\n};\n\nlet ans = temp.courses.find(obj => obj.course === 'Math' );\nans = ans && ans.courseCode ? ans.courseCode : \"Course not found\";\nconsole.log(ans);\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10419901/"
] |
74,595,848
|
<p>The following code:</p>
<pre><code>{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
class C (f :: Type -> Type) where
g :: String -> f a
class D a where
h :: C f => a -> f a
instance C Maybe where
g _ = Nothing
instance C (Either String) where
g = Left
instance D Int where
h = g . show
newtype NewInt = NewInt Int deriving newtype D
</code></pre>
<p>fails to compile with the following error:</p>
<pre><code> Couldn't match representation of type: f Int
with that of: f NewInt
arising from the coercion of the method ‘h’
</code></pre>
<p>Which I guess makes sense, if <code>f</code> does some weird type family stuff. But my <code>f</code>s do not, there just <code>Maybe</code> and <code>Either</code>, so replacing <code>Int</code> with it's newtype <code>NewInt</code> should probably work I believe.</p>
<p>How can I convince GHC of this (assuming I'm not wrong). I presume it's some <code>RoleAnnotations</code> thing required but nothing I have tried has worked.</p>
|
[
{
"answer_id": 74602016,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 1,
"selected": false,
"text": "f data E (f :: Type -> Type) a = MkE (f a)\n\nfoo :: E Maybe Int\nfoo = MkE Nothing\n\nbar :: E Maybe NewInt\nbar = coerce foo -- <<< error\n"
},
{
"answer_id": 74604421,
"author": "chi",
"author_id": 3234959,
"author_profile": "https://Stackoverflow.com/users/3234959",
"pm_score": 3,
"selected": true,
"text": "{-# LANGUAGE DerivingStrategies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE QuantifiedConstraints #-}\n\nimport Data.Kind\nimport Data.Coerce\n\nclass (forall a b . Coercible a b => Coercible (f a) (f b))\n => C (f :: Type -> Type) where\n g :: String -> f a\n class D a where\n h :: C f => a -> f a\n\ninstance C Maybe where\n g _ = Nothing\n\ninstance C (Either String) where\n g = Left \n\ninstance D Int where\n h = g . show\n newtype .. deriving coerce newtype NewInt = NewInt Int\n -- No \"deriving newtype D\" here\n\n-- explicit instance using \"coerce\"\ninstance D NewInt where \n h :: forall f. C f => NewInt -> f NewInt\n h = coerce (h @Int @f)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525980/"
] |
74,595,866
|
<p>I'm developing a TicTacToe game and faced with a some problem.<br />
After put the "X" I need to change <code>changeMove</code> to <code>true</code> in <code>ChangeMove()</code> function to put next move as "O" in another place.
I need to check <code>place.sprite == null</code> too, because I don't want to change put move again.<br />
In the <code>If</code> block I'm changing changeMove to apposite value but it isn't changing(I mean when I'm calling OnMouseDown method second time, I can't get into the <code>else if</code> block).
Here is my inspector of <code>MainCamera</code>:</p>
<p><img src="https://i.stack.imgur.com/vXOPZ.jpg" alt="enter image description here" /></p>
<p>I created a script(PutMove.cs) that inherits all the methods and fields from <strong>LogicOfGame.cs</strong> besides <code>private bool changeMove</code> only for clickable squares to put move there:<br />
Here is my LogicOfGame.cs, PutMove.cs scripts and inspector of first square:<br />
The square's inspector:</p>
<p><img src="https://i.stack.imgur.com/203CD.jpg" alt="enter image description here" /></p>
<p>LogicOfGame.cs:</p>
<pre><code>public class LogicOfGame : MonoBehaviour
{
public SpriteRenderer place;
private bool changeMove;
public Image X;
public Image O;
public void ChangeMove()
{
if (!changeMove && place.sprite == null)
{
place.sprite = X.sprite;
changeMove = !changeMove;
}
else if (changeMove && place.sprite == null)
{
place.sprite = O.sprite;
changeMove = !changeMove;
}
}
{
</code></pre>
<p>PutMove.cs:</p>
<pre><code>public class PutMove : LogicOfGame
{
private void OnMouseDown()
{
ChangeMove();
}
}
</code></pre>
<p>I also tried to change <code>changeMove</code> value in another method and call it in <code>OnMouseDown()</code> method, but isn't helped</p>
<pre><code>public bool ChangeMove(bool changeMove)
{
return !changeMove;
}
public class PutMove : LogicOfGame
{
private void OnMouseDown()
{
//renamed the ChangeMove()
//And left only place.sprite = X.sprite;
PutMove();
changeMove = ChangeMove(changeMove);
}
}
</code></pre>
<p>How can I change value of <code>changeMove</code> at last?</p>
|
[
{
"answer_id": 74602016,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 1,
"selected": false,
"text": "f data E (f :: Type -> Type) a = MkE (f a)\n\nfoo :: E Maybe Int\nfoo = MkE Nothing\n\nbar :: E Maybe NewInt\nbar = coerce foo -- <<< error\n"
},
{
"answer_id": 74604421,
"author": "chi",
"author_id": 3234959,
"author_profile": "https://Stackoverflow.com/users/3234959",
"pm_score": 3,
"selected": true,
"text": "{-# LANGUAGE DerivingStrategies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE QuantifiedConstraints #-}\n\nimport Data.Kind\nimport Data.Coerce\n\nclass (forall a b . Coercible a b => Coercible (f a) (f b))\n => C (f :: Type -> Type) where\n g :: String -> f a\n class D a where\n h :: C f => a -> f a\n\ninstance C Maybe where\n g _ = Nothing\n\ninstance C (Either String) where\n g = Left \n\ninstance D Int where\n h = g . show\n newtype .. deriving coerce newtype NewInt = NewInt Int\n -- No \"deriving newtype D\" here\n\n-- explicit instance using \"coerce\"\ninstance D NewInt where \n h :: forall f. C f => NewInt -> f NewInt\n h = coerce (h @Int @f)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18006503/"
] |
74,595,889
|
<p>I have a select field populated from the database table 'Grade'. It displays Grade objects instead of 'Grade 1', 'Grade 2', 'Grade 3' etc. How can I populate the select to display the texts.
<a href="https://i.stack.imgur.com/e8pgv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e8pgv.png" alt="Current Output" /></a></p>
<p>My codes:</p>
<p><strong>models.py</strong></p>
<pre><code>class Grade(models.Model):
grade_id = models.AutoField(primary_key=True)
grade_name = models.CharField(max_length=10, default="")
class Meta:
db_table = 'grade'
class Student(models.Model):
student_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=50, default="")
last_name = models.CharField(max_length=50, default="")
grade = models.ForeignKey(Grade, on_delete=models.CASCADE)
class Meta:
db_table = 'Student'
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>class CreateStudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['grade', 'first_name', 'last_name' ]
widgets = {
'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}),
'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}),
'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}),
}
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>def student_action(request):
form = CreateStudentForm()
return render(request, 'student.html', {'form': form})
</code></pre>
|
[
{
"answer_id": 74595949,
"author": "Mahammadhusain kadiwala",
"author_id": 19205926,
"author_profile": "https://Stackoverflow.com/users/19205926",
"pm_score": 2,
"selected": false,
"text": "class Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n class Meta:\n db_table = 'grade'\n \n def __str__(self):\n return self.grade_name\n"
},
{
"answer_id": 74595950,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 3,
"selected": true,
"text": "__str__() class Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n\n def __str__(self):\n return f\"{self.grade_name}\"\n\n class Meta:\n db_table = 'grade'\n __init__() class CreateStudentForm(forms.ModelForm):\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['grade'].empty_label = 'Select Grade'\n \n class Meta:\n model = Student\n fields = ['grade', 'first_name', 'last_name' ]\n widgets = {\n 'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}),\n 'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}),\n 'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}),\n } \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19313505/"
] |
74,595,908
|
<p>I am starting my first VB project and need to connect to SQL Server. The type <code>SqlConnection</code> is unknown even though the namespace <code>System.Data.SqlClient</code> is present.</p>
<p>I'm unable to move beyond this.</p>
<p>I have stripped the code back to essential lines that demonstrate.</p>
<p>I have downloaded/updated the <code>System.Data.SqlClient</code> from Nuget in tools.</p>
<p>Out of ideas and just chewing up good time</p>
<p>Hope you can help</p>
<p>Code:</p>
<pre class="lang-vb prettyprint-override"><code>Imports System.Data.SqlClient
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Private myConn As SqlConnection 'SqlConnection shows up as a red squiggly underline
Private myCmd As SqlCommand 'SqlCommand ditto
Private myReader As SqlDataReader 'SqlDataReader ditto
Private results As String
End Sub
</code></pre>
|
[
{
"answer_id": 74595949,
"author": "Mahammadhusain kadiwala",
"author_id": 19205926,
"author_profile": "https://Stackoverflow.com/users/19205926",
"pm_score": 2,
"selected": false,
"text": "class Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n class Meta:\n db_table = 'grade'\n \n def __str__(self):\n return self.grade_name\n"
},
{
"answer_id": 74595950,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 3,
"selected": true,
"text": "__str__() class Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n\n def __str__(self):\n return f\"{self.grade_name}\"\n\n class Meta:\n db_table = 'grade'\n __init__() class CreateStudentForm(forms.ModelForm):\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['grade'].empty_label = 'Select Grade'\n \n class Meta:\n model = Student\n fields = ['grade', 'first_name', 'last_name' ]\n widgets = {\n 'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}),\n 'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}),\n 'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}),\n } \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619494/"
] |
74,595,928
|
<p>i want to call data api based on the selected parameters, but i'm having a bit of trouble and this has been going on for a few days and it's still not done.</p>
<blockquote>
<p>this is the api you want to fetch data from. and also I marked the
parameters.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/yuMKm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yuMKm.png" alt="enter image description here" /></a></p>
<blockquote>
<p>and this is when i try to call data api</p>
</blockquote>
<pre><code> static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
await Future.delayed(const Duration(milliseconds: 1000));
// String responseJson = await rootBundle.loadString('assets/1.json');
Map<String, DataKuliahModel> finalResult = {};
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
result.forEach((key, value) {
DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
finalResult.addAll({
key: dataKuliah,
});
});
return finalResult;
}
</code></pre>
|
[
{
"answer_id": 74595949,
"author": "Mahammadhusain kadiwala",
"author_id": 19205926,
"author_profile": "https://Stackoverflow.com/users/19205926",
"pm_score": 2,
"selected": false,
"text": "class Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n class Meta:\n db_table = 'grade'\n \n def __str__(self):\n return self.grade_name\n"
},
{
"answer_id": 74595950,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 3,
"selected": true,
"text": "__str__() class Grade(models.Model):\n grade_id = models.AutoField(primary_key=True)\n grade_name = models.CharField(max_length=10, default=\"\")\n\n def __str__(self):\n return f\"{self.grade_name}\"\n\n class Meta:\n db_table = 'grade'\n __init__() class CreateStudentForm(forms.ModelForm):\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['grade'].empty_label = 'Select Grade'\n \n class Meta:\n model = Student\n fields = ['grade', 'first_name', 'last_name' ]\n widgets = {\n 'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}),\n 'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}),\n 'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}),\n } \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19132574/"
] |
74,595,932
|
<p>I'm building a word-game in React that, previously, would send user-made words to an online dictionary API as a fetch request, in order to validate the words. However, the servers for the API have been down recently and I no longer want to rely on a third-party in order for my game to work. I had the idea previously to implement a local dictionary in hopes that it would make my game run more smoothly, thanks to cutting out the fetch wait time (however small). After implementing the local dictionary, though, I've noticed that lookup times are a bit longer.</p>
<p>The dictionary file is a massive JSON object (370,000+ lines) that I am importing into my main component like so: <code>import * as data from '../../dictionary/words_dictionary.json';</code>
The JSON is structured like this:</p>
<pre><code>"afterwash": 1,
"afterwhile": 1,
"afterwisdom": 1,
"afterwise": 1,
"afterwit": 1,
"afterwitted": 1,
"afterword": 1,
"afterwork": 1,
</code></pre>
<p>In order to validate a word that a user has submitted, I am merely checking if the word exists in the keys of my JSON file, as such:</p>
<pre><code>if (Object.keys(data).includes(orderedInput.toLowerCase())) {
dispatch(actions)
else {
dispatch(other actions)
}
</code></pre>
<p>I realize of course that my implementation is a horribly slow and inefficient one, however, I have little experience in search optimization. If there is an easy, better way to accomplish this, I would appreciate any pointers in the right direction.</p>
|
[
{
"answer_id": 74596003,
"author": "Chris Hamilton",
"author_id": 12914833,
"author_profile": "https://Stackoverflow.com/users/12914833",
"pm_score": 2,
"selected": false,
"text": "includes if (data[orderedInput.toLowerCase()]) {\n dispatch(actions)\nelse {\n dispatch(other actions)\n}\n Set export const data = new Set([\n \"afterwash\",\n \"afterwhile\",\n \"afterwisdom\",\n \"afterwise\",\n ...\n]);\n if (data.has(orderedInput.toLowerCase())) {\n dispatch(actions)\nelse {\n dispatch(other actions)\n}\n"
},
{
"answer_id": 74596369,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 0,
"selected": false,
"text": "in in if (orderedInput.toLowerCase() in data) {\n dispatch(actions)\nelse {\n dispatch(other actions)\n}\n in Object.keys const fs = require(\"fs\");\nconst file = fs.readFileSync(\"path/to/words_dictionary.json\");\nfs.writeFileSync(\"path/to/words_dictionary.json\", Object.keys(file));\n Object.keys trie // create a custom trie implementation\nclass Trie {\n constructor(data) {\n this.root = {}; // use an object to represent the tree\n this.end = Symbol(\"trieEnd\"); // use a symbol to represent the end of a word\n\n // convert each letter into a key\n for(const i of data) {\n i.split(\"\").reduce((ref, letter, index) => {\n ref[letter] = {...(ref[letter] || {})};\n if(index === i.length - 1) {\n ref[letter][this.end] = 1; // mark this is as the end of a word\n }\n return ref[letter];\n }, this.root);\n }\n }\n search(word) {\n let pos = this.root;\n \n for(let i in word) {\n pos = pos[word[i]];\n \n if(typeof pos === \"undefined\")\n return false;\n \n if(i == word.length - 1) {\n // test if this end is an actual end\n if(!Object.hasOwn(pos, this.end))\n return false;\n }\n }\n \n return true;\n }\n}\n\nconst t = new Trie([\"hello\", \"hell\", \"hi\", \"boy\"]);\nconsole.log(\n t.search(\"hello\"),\n t.search(\"boy\"),\n t.search(\"ho\"),\n t.search(\"not in here\"),\n t.search(\"h\")\n); // set up\nArray.prototype.random = function() {\n return this[(Math.random() * this.length) | 0];\n}\n\nconst alphabet = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\nconst fakeDataList = Array.from({ length: 500000 }, (_, i) => {\n const wordLength = ((Math.random() * 20) | 0) + 1;\n let word = \"\";\n for(let i = 0; i < wordLength; i++)\n word += alphabet.random();\n return word;\n});\n\nclass Trie {\n constructor(data) {\n this.root = {};\n this.end = Symbol(\"trieEnd\");\n for(const i of data) {\n i.split(\"\").reduce((ref, letter, index) => {\n ref[letter] = {...(ref[letter] || {})};\n if(index === i.length - 1) {\n ref[letter][this.end] = 1;\n }\n return ref[letter];\n }, this.root);\n }\n }\n search(word) {\n let pos = this.root;\n \n for(let i in word) {\n pos = pos[word[i]];\n \n if(typeof pos === \"undefined\")\n return false;\n \n if(i == word.length - 1) {\n if(!Object.hasOwn(pos, this.end))\n return false;\n }\n }\n \n return true;\n }\n}\n\nfunction trieSearch(word, trie) {\n return trie.search(word);\n}\nfunction naiveSearch(word, list) {\n return list.includes(word);\n}\n\nconst findList = [];\nfor(let i = 0; i < 100000; i++)\n findList.push(fakeDataList.random());\nfunction runManyTimes(fn, data) {\n for(const w of findList) {\n fn(w, data);\n }\n}\n\nconsole.time(\"naive search\");\nrunManyTimes(naiveSearch, fakeDataList);\nconsole.timeEnd(\"naive search\");\n\nconsole.time(\"trie initialization\");\nconst t = new Trie(fakeDataList);\nconsole.timeEnd(\"trie initialization\");\n\nconsole.time(\"trie search\");\nrunManyTimes(trieSearch, t);\nconsole.timeEnd(\"trie search\");"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17844571/"
] |
74,595,933
|
<p>How do I change the text of p element to "Congratulations" when the "Start chaining" button is clicked. I want to add another chaining method to do that.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery Method Chaining</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
button {
padding: 10px;
}
p {
width: 200px;
padding: 30px 0;
font: bold 24px;
text-align: center;
background: #00ced1;
border: 1px;
box-sizing: border-box;
}
</style>
<script>
$(document).ready(function () {
$('.start').click(function () {
$('p')
.animate({ width: '100%' })
.animate({ fontSize: '35px' })
.animate({ borderWidth: 30 })
;
});
$('.reset').click(function () {
$('p').removeAttr('style');
});
});
</script>
</head>
<body>
<p>Hello !</p>
<button type="button" class="start">Start Chaining</button>
<button type="button" class="reset">Reset</button>
</body>
</html>
</code></pre>
<p>I tried using <code>.replaceWith()</code> function but it seemed to break other chaining methods</p>
<hr />
|
[
{
"answer_id": 74595953,
"author": "Thulitha Gurusinghe",
"author_id": 18212224,
"author_profile": "https://Stackoverflow.com/users/18212224",
"pm_score": 0,
"selected": false,
"text": ".text('Congratulations');"
},
{
"answer_id": 74595973,
"author": "Shashank Malviya",
"author_id": 8406046,
"author_profile": "https://Stackoverflow.com/users/8406046",
"pm_score": 2,
"selected": true,
"text": "id p $(document).ready(function () {\n$( \"p\" )\n $('.start').click(function () {\n let str = \"Congratulations\"\n $('p')\n .animate({ width: '100%' })\n .animate({ fontSize: '35px' })\n .animate({ borderWidth: 30 })\n .html( str );\n });\n\n $('.reset').click(function () {\n $('p').removeAttr('style');\n });\n }); <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>jQuery Method Chaining</title>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <style>\n button {\n padding: 10px;\n }\n p {\n width: 200px;\n padding: 30px 0;\n font: bold 24px;\n text-align: center;\n background: #00ced1;\n border: 1px;\n box-sizing: border-box;\n }\n </style>\n </head>\n <body>\n <p>Hello !</p>\n <button type=\"button\" class=\"start\">Start Chaining</button>\n <button type=\"button\" class=\"reset\">Reset</button>\n </body>\n</html>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18212224/"
] |
74,595,943
|
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="com.xam.mobileapp" xmlns:tools="http://schemas.android.com/tools" android:versionName="1.7" android:versionCode="30">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application android:requestLegacyExternalStorage="true" android:usesCleartextTraffic="true" android:label="Pragyan" android:icon="@mipmap/ic_launcher" android:name="android.support.multidex.MultiDexApplication" android:allowBackup="false">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="true"/>
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="true" android:enabled="true" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
</provider>
<!--<meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyAU3On6yQ8TZWJSce62TjXcXTWCm7MoXIU" />-->
<uses-library android:name="org.apache.http.legacy" android:required="false" />
<activity android:name="microsoft.identity.client.BrowserTabActivity" tools:node="merge" android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="msal{appid}" android:host="auth" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>Even after adding the property <strong>android:exported="true"</strong> at required places receving the same error msg.
Any one facing same issue in xamarin forms (Android application).
Thanks in advance.</p>
|
[
{
"answer_id": 74595953,
"author": "Thulitha Gurusinghe",
"author_id": 18212224,
"author_profile": "https://Stackoverflow.com/users/18212224",
"pm_score": 0,
"selected": false,
"text": ".text('Congratulations');"
},
{
"answer_id": 74595973,
"author": "Shashank Malviya",
"author_id": 8406046,
"author_profile": "https://Stackoverflow.com/users/8406046",
"pm_score": 2,
"selected": true,
"text": "id p $(document).ready(function () {\n$( \"p\" )\n $('.start').click(function () {\n let str = \"Congratulations\"\n $('p')\n .animate({ width: '100%' })\n .animate({ fontSize: '35px' })\n .animate({ borderWidth: 30 })\n .html( str );\n });\n\n $('.reset').click(function () {\n $('p').removeAttr('style');\n });\n }); <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>jQuery Method Chaining</title>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <style>\n button {\n padding: 10px;\n }\n p {\n width: 200px;\n padding: 30px 0;\n font: bold 24px;\n text-align: center;\n background: #00ced1;\n border: 1px;\n box-sizing: border-box;\n }\n </style>\n </head>\n <body>\n <p>Hello !</p>\n <button type=\"button\" class=\"start\">Start Chaining</button>\n <button type=\"button\" class=\"reset\">Reset</button>\n </body>\n</html>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601909/"
] |
74,595,947
|
<p>I produced 119 logistic regression models with lapply. I then used lapply again to get the coefficients and p-values in a summary format</p>
<pre><code>#Model 1
#looping through the different metabolites to produce over 100 logistic
regression models. For hpresponse1. Minimally adjusted
response1minadj<-lapply(metabolite.names, function(X)
glm(as.formula(paste0("hpresponse1~",X, "+ age + BMIfactor")),
data=df, family="binomial"))
response1minadj
#getting the effects sizes and p-values- hpresponse1, minimally adjusted
results1<-lapply(response1minadj, function(p) coef(summary(p)))
results1
</code></pre>
<p>Now I want adjusted p-values with p.adjust. I thought I could change the summary of results into their own separate dataframes, name the columns and then use p.adjust on the column I named "pvalue"</p>
<pre><code>#changing the results into separate dataframes
results1 = lapply(results1, function (d) as.data.frame(d))
#renaming the columns
results =lapply(results1, function(b) colnames(b) = c("beta","SE", "zvalue"
,"pvalue"))
</code></pre>
<p>However, the column names change doesn't seem to work as the following syntax produces "null"</p>
<pre><code>colnames(results1)
</code></pre>
<p>Is there another way to accomplish my goal of getting adjusted p-values for all 119 models? Or is there a way to get my syntax to work?</p>
|
[
{
"answer_id": 74595953,
"author": "Thulitha Gurusinghe",
"author_id": 18212224,
"author_profile": "https://Stackoverflow.com/users/18212224",
"pm_score": 0,
"selected": false,
"text": ".text('Congratulations');"
},
{
"answer_id": 74595973,
"author": "Shashank Malviya",
"author_id": 8406046,
"author_profile": "https://Stackoverflow.com/users/8406046",
"pm_score": 2,
"selected": true,
"text": "id p $(document).ready(function () {\n$( \"p\" )\n $('.start').click(function () {\n let str = \"Congratulations\"\n $('p')\n .animate({ width: '100%' })\n .animate({ fontSize: '35px' })\n .animate({ borderWidth: 30 })\n .html( str );\n });\n\n $('.reset').click(function () {\n $('p').removeAttr('style');\n });\n }); <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>jQuery Method Chaining</title>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <style>\n button {\n padding: 10px;\n }\n p {\n width: 200px;\n padding: 30px 0;\n font: bold 24px;\n text-align: center;\n background: #00ced1;\n border: 1px;\n box-sizing: border-box;\n }\n </style>\n </head>\n <body>\n <p>Hello !</p>\n <button type=\"button\" class=\"start\">Start Chaining</button>\n <button type=\"button\" class=\"reset\">Reset</button>\n </body>\n</html>"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20302818/"
] |
74,595,996
|
<p>I'm brand new to python and am using the "Job Ready for Python" as a first text and ran across this chapter 4 problem that I can't get my head around:</p>
<p><em>Create a program that prompts the user to a number and then displays the type of number entered(e.g., complex, integer, or a float).</em></p>
<p>I'm having a hard time understanding how to classify inputs as anything other than strings -- additionally in the book I have covered basics, variables, booleans, and operators: and (per the book) should have all the tools to do this</p>
<p>Any help would be appreciated</p>
<p>I tried something like</p>
<pre class="lang-python prettyprint-override"><code>num = input("Type any number: ")
print(num, ":", type(num))
</code></pre>
<p>but that kept returning string....</p>
<p>and then I thought maybe I have to classify values using operators such as</p>
<pre class="lang-python prettyprint-override"><code>num = input(....)
if num % 2 == x
</code></pre>
<p>IDK from hear</p>
|
[
{
"answer_id": 74596032,
"author": "Shrirang Mahajan",
"author_id": 17353907,
"author_profile": "https://Stackoverflow.com/users/17353907",
"pm_score": 1,
"selected": false,
"text": "age = input(\"Enter your age :\")\nprint(type(age))\n str age = int(input(\"Enter your age :\"))\nprint(type(age))\n int"
},
{
"answer_id": 74599238,
"author": "Andrew",
"author_id": 11844224,
"author_profile": "https://Stackoverflow.com/users/11844224",
"pm_score": 0,
"selected": false,
"text": "Mac_3.2.57$cat getType.py\nage = input(\"Enter your age :\")\nprint(type(age))\nMac_3.2.57$python getType.py\nEnter your age :22\n<type 'int'>\nMac_3.2.57$python getType.py\nEnter your age :22.0\n<type 'float'>\nMac_3.2.57$python getType.py\nEnter your age :22 + 23j\n<type 'complex'>\nMac_3.2.57$\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74595996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619807/"
] |
74,596,023
|
<p>Models:</p>
<pre><code>class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default=1,related_name='Employee')
eid = models.IntegerField(primary_key=True)
salary = models.IntegerField(null=True, blank=True)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1)
contactno = models.CharField(max_length=10, blank=False)
email = models.CharField(max_length=50 ,null=True, blank=True)
country = models.CharField(max_length=30)
address = models.CharField(max_length=60)
def __str__(self):
return self.user.first_name + '_' + self.user.last_name
class Attendance(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1,related_name='Attendance')
attendance_date = models.DateField(null=True)
in_time = models.TimeField(null=True)
out_time = models.TimeField(null=True ,blank=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return str(self.employee) + '-' + str(self.attendance_date)
class Breaks(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1)
break_in = models.TimeField(null=True, blank=True)
break_out = models.TimeField(null=True, blank=True)
attendance =models.ForeignKey(Attendance, on_delete=models.CASCADE, default=1,related_name='Breaks')
def __str__(self):
return str(self.employee) + '-' + str(self.break_in) + '-' + str(self.break_out)
def detail_attendance(request):
attendance_list = Attendance.objects.filter(employee__user_id=request.user.id)
counter = Counter()
return render(request, 'employee/detail_attendance.html', {'attendance_list': attendance_list, 'counter': counter})
def detail_break(request):
break_list=Breaks.objects.filter(employee__user_id=request.user.id )
return render(request, 'employee/detail_break.html', {'break_list': break_list})
</code></pre>
<p>I have created a function above for detail breaks. I am getting specific user data, but it is giving me the previous data as well. So I need the data for specific date for example in my attendance models I adding attendance of each user.</p>
<p>Please let me know what should I change in detail break.</p>
|
[
{
"answer_id": 74596456,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 0,
"selected": false,
"text": "Breaks.objects.filter(date__range=[\"2011-01-01\", \"2011-01-31\"])\n Breaks.objects.filter(date__year='2011', \n date__month='01')\n"
},
{
"answer_id": 74596915,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 3,
"selected": true,
"text": "from django.db.models import Q\nfrom datetime import date\n\n\nBreaks.objects.filter(\n Q(employee__user=request.user) & \n Q(attendance__attendance_date=date.today())\n)\n \nBreaks.objects.filter(\n Q(employee__user=request.user) & \n Q(attendance__attendance_date=\"2022-11-28\")\n)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20173041/"
] |
74,596,027
|
<p>I’m getting the error:</p>
<p>ModuleNotFoundError: No module named ‘webdriver_manager.Edge’. My Code is:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.edge.service import Service
from webdriver_manager.Edge import ChromeDriverManager
def Mok():
chrome_options = Options()
chrome_options.add_argument("--headless")
driver=webdriver.Edge(options=chrome_options, service=Service(EdgeDriverManager().install()))
start_url='netlify.com'
driver.get(start_url)
print(driver.page_source.encode("utf-8"))
driver.get_screenshot_as_png('reddit.png')
print(driver.title)
driver.close()
Mok()
</code></pre>
|
[
{
"answer_id": 74596456,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 0,
"selected": false,
"text": "Breaks.objects.filter(date__range=[\"2011-01-01\", \"2011-01-31\"])\n Breaks.objects.filter(date__year='2011', \n date__month='01')\n"
},
{
"answer_id": 74596915,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 3,
"selected": true,
"text": "from django.db.models import Q\nfrom datetime import date\n\n\nBreaks.objects.filter(\n Q(employee__user=request.user) & \n Q(attendance__attendance_date=date.today())\n)\n \nBreaks.objects.filter(\n Q(employee__user=request.user) & \n Q(attendance__attendance_date=\"2022-11-28\")\n)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17054993/"
] |
74,596,046
|
<p>I want to make a dataframe from web scrapping this page : <a href="https://www.airlinequality.com/airline-reviews/british-airways" rel="nofollow noreferrer">https://www.airlinequality.com/airline-reviews/british-airways</a>.</p>
<p>The value i have is reviews from passenger and rating that passenger give, but i dont know how to make it to be a dataframe</p>
<p>this is my code :</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
base_url = "https://www.airlinequality.com/airline-reviews/british-airways"
pages = 5 #10
page_size = 1 #100
reviews = []
aircraft = []
seat_type = []
route = []
recommended = []
rating = []
category = []
for i in range(1, pages + 1):
print(f"Scraping page {i}")
# Create URL to collect links from paginated data
url = f"{base_url}/page/{i}/?sortby=post_date%3ADesc&pagesize={page_size}"
# Collect HTML data from this page
response = requests.get(url)
# Parse content
content = response.content
parsed_content = BeautifulSoup(content, 'html.parser')
for para in parsed_content.find_all("div", {"class": "text_content"}):
reviews.append(para.get_text())
for para2 in parsed_content.find_all("div", {"class" : "review-stats"}):
for para3 in para2.find_all('td',{'class' : 'review-value'}):
rating.append(para3.get_text())
recomend = rating[-1]
rating = rating[:-1]
for para4 in para2.find_all('td',{'class' : 'review-rating-stars stars'}):
para5 = len(para4.find_all('span', {'class' : 'star fill'}))
rating.append(para5)
rating.append(recomend)
#print(rating)
for para6 in para2.find_all('td',{'class' : 'review-rating-header'}):
category.append(para6.get_text())
#print(category)
print(f" ---> {len(reviews)} total reviews")
</code></pre>
<p>output i get :
<a href="https://i.stack.imgur.com/Xni5F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xni5F.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/k7Lmn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k7Lmn.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/LWC4X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LWC4X.png" alt="enter image description here" /></a></p>
<p>in a simple way, that is what I was asking :</p>
<p>first looping: category is [a, b, c, d, e] rating is [1, 2, 3, 4, 5]</p>
<p>second looping: the category will append with [a, c, e, o, p, q] and rating will append with [9, 8, 7, 6, 5, 4]</p>
<p>so the final data :</p>
<p>category = [a, b, c, d, e, a, c, e, o, p, q]</p>
<p>rating = [1, 2, 3, 4, 5, 9, 8, 7, 6, 5, 4]</p>
<p>output that I want:</p>
<p><a href="https://i.stack.imgur.com/x8fG6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x8fG6.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74596094,
"author": "Kris",
"author_id": 995052,
"author_profile": "https://Stackoverflow.com/users/995052",
"pm_score": 0,
"selected": false,
"text": "DataFrame from pandas import DataFrame\n\ncategory = [\"Aircraft\", 'Type of Traveller', 'Seat Type']\nrating = ['A320', 'Solo', 'Business Class']\n\n# Create the records from both list, using zip and dict calls.\ndata_dict = dict(zip(category, rating))\n\n# Build the dataframe from the dictionary.\ndf = DataFrame.from_records(data_dict, columns=category, index=[0])\n\nprint(df)\n"
},
{
"answer_id": 74601446,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 1,
"selected": false,
"text": "cr = [(k, v) for k, v in zip(category, rating)]\nsi = [i for i, (k, v) in enumerate(cr) if k == 'Type Of Traveller']\nsi = [(i - 1) if i != 0 and cr[i - 1][0] == 'Aircraft' else i for i in si]\nsplitCr = [dict(cr[start:end]) for start, end in zip(si, (si[1:] + [len(cr)]))]\n base_url = \"https://www.airlinequality.com/airline-reviews/british-airways\"\npages = 3 # 5 # 10\npage_size = 5 # 1 # 100\n\nrevList = []\navgSelRef = {\n 'rating10': '.rating-10 span[itemprop=\"ratingValue\"]',\n 'header': 'div.info:has(h1[itemprop=\"name\"])',\n 'subheader': '.review-count',\n 'reviewBody': '.skytrax-rating-mob img.skytrax-rating[alt]'\n}\nrbSel = '.body[id^=\"anchor\"]'\nrevSelRef = {\n 'rating10': '.rating-10 span[itemprop=\"ratingValue\"]',\n 'header': f'{rbSel} h2.text_header',\n 'subheader': f'{rbSel} h3.text_sub_header',\n 'reviewBody': f'{rbSel} div[itemprop=\"reviewBody\"]'\n} \n\navgAdded = False\nfor i in range(1, pages + 1): \n print(\"\", end=f\"Scraping page {i} of {pages} \")\n\n # Create URL to collect links from paginated data\n url = f\"{base_url}/page/{i}/?sortby=post_date%3ADesc&pagesize={page_size}\"\n\n # Collect HTML data from this page\n response = requests.get(url)\n if response.status_code != 200: \n print(f' -- !ERROR: \"{response.raise_for_status()}\"\" getting {url}')\n continue\n content = response.content\n parsed_content = BeautifulSoup(content, 'html.parser')\n\n avSoups = parsed_content.select('div.review-info')\n rvSoups = parsed_content.select(f'article[itemprop=\"review\"]:has({rbSel})')\n if avSoups and not avgAdded: rvSoups += avSoups\n for r in rvSoups:\n isAvg = r.name == 'div'\n if isAvg:\n rDets = {'reviewId': '[Average]'} \n selRef = avgSelRef.items()\n avgAdded = True\n else:\n revId = r.select_one(rbSel).get('id').replace('anchor', '', 1)\n selRef = revSelRef.items()\n rDets = {'reviewId': revId} \n \n for k, s in selRef:\n rdt = r.select_one(s) \n if rdt is None: continue\n if 'img' in s and s.endswith('[alt]'):\n rDets[k] = rdt.get('alt') \n else:\n rDets[k] = ' '.join(w for w in rdt.get_text(' ').split() if w)\n\n rhSel = 'td.review-rating-header'\n rRows = r.select(f'tr:has({rhSel} + td:is(.stars, .review-value))')\n for rr in rRows: \n k = rr.select_one(rhSel).get_text(' ').strip()\n k = k.replace(' For ', ' for ').replace(' & ', ' + ') # bit of cleanup\n if k.endswith('Staff Service'): k = 'Staff Service' # bit of cleanup\n if rr.select('td.stars'): \n rDets[f'[stars] {k}'] = len(rr.select('td.stars span.star.fill'))\n else: \n rDets[k] = rr.select_one('td.review-value').get_text().strip()\n\n revList = ([rDets] + revList) if isAvg else (revList + [rDets])\n print(' - ', len(rvSoups), 'reviews --->', len(revList), 'total reviews') \n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18388803/"
] |
74,596,050
|
<p>Trying to implement user authorization through Firebase in a new React project.</p>
<pre class="lang-js prettyprint-override"><code> import { User } from '@firebase/auth-types';
// ...
const [user, setUser] = useState<User | null>(null);
const auth = getAuth();
onAuthStateChanged(auth, (newUser) => {
setUser(newUser);
});
</code></pre>
<p>Error on <code>setUser(newUser);</code> :</p>
<blockquote>
<p>Argument of type 'User | null' is not assignable to parameter of type >'SetStateAction<User | null>'.
Type 'User' is not assignable to type 'SetStateAction<User | null>'.
Type 'User' is missing the following properties from type 'User': linkAndRetrieveDataWithCredential, linkWithCredential, linkWithPhoneNumber, linkWithPopup, and 14 more.ts(2345)</p>
</blockquote>
<p>Tried doing <code>newUser: User</code> which did not fix this error. <code>useState<any | null></code> resolves it, but I believe this defeats the purpose of Typescript.</p>
<p><code>newUser: React.SetStateAction<User | null></code> results in another error:</p>
<blockquote>
<p>Argument of type '(newUser: React.SetStateAction<User | null>) => void' is not assignable to parameter of type 'NextOrObserver'.
Type '(newUser: React.SetStateAction<User | null>) => void' is not assignable to type 'NextFn<User | null>'.
Types of parameters 'newUser' and 'value' are incompatible.
Type 'User | null' is not assignable to type 'SetStateAction<User | null>'.
Type 'User' is not assignable to type 'SetStateAction<User | null>'.
Type 'User' is missing the following properties from type 'User': linkAndRetrieveDataWithCredential, linkWithCredential, linkWithPhoneNumber, linkWithPopup, and 14 more.ts(2345)</p>
</blockquote>
<p>I believe these are just warnings, since everything still works properly, but I would like to resolve this regardless. Not sure what else to try as I'm very new to Typescript.</p>
<p>Entirety of this file:</p>
<pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect } from 'react';
import { getAuth, onAuthStateChanged, createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth';
import { User } from '@firebase/auth-types';
function EmailPasswordForm(): JSX.Element {
const [isCreatingAccount, setIsCreatingAccount] = useState(false);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const auth = getAuth();
const onButtonClick = () => {
if (isCreatingAccount) {
createUserWithEmailAndPassword(auth, email, password)
.catch((error) => {
console.log(error.code, error.message);
});
} else {
signInWithEmailAndPassword(auth, email, password)
.catch((error: { code: any; message: any; }) => {
console.log(error.code, error.message);
});
}
}
const onEmailChange = (e: { target: { value: React.SetStateAction<string>; }; }) => setEmail(e.target.value);
const onPasswordChange = (e: { target: { value: React.SetStateAction<string>; }; }) => setPassword(e.target.value);
const onConfirmPasswordChange = (e: { target: { value: React.SetStateAction<string>; }; }) => setConfirmPassword(e.target.value);
const createAccountForm = (
<>
<input placeholder="e-mail" onChange={onEmailChange} />
<input placeholder="password" type="password" onChange={onPasswordChange} />
<input placeholder="confirm password" type="password" onChange={onConfirmPasswordChange} />
</>
);
const signInForm = (
<>
<input placeholder="e-mail" onChange={onEmailChange} />
<input placeholder="password" type="password" onChange={onPasswordChange} />
</>
);
return (
<>
{isCreatingAccount ? createAccountForm : signInForm}
<button type="button" onClick={onButtonClick}>{isCreatingAccount ? 'create account' : 'sign in'}</button>
<button className="text-button" type="button" onClick={() => setIsCreatingAccount(!isCreatingAccount)}>
{isCreatingAccount ? 'i don\'t have an account!' : 'i already have an account!'}
</button>
</>
);
}
function SignIn(): JSX.Element {
const [user, setUser] = useState<User | null>(null);
const auth = getAuth();
onAuthStateChanged(auth, (newUser) => {
setUser(newUser);
});
if (user != null) {
return <span>you are signed in!</span>;
}
return (
<div className="center">
<EmailPasswordForm />
</div>
);
}
export default SignIn;
</code></pre>
|
[
{
"answer_id": 74597780,
"author": "Tigran Petrosyan",
"author_id": 10422933,
"author_profile": "https://Stackoverflow.com/users/10422933",
"pm_score": 0,
"selected": false,
"text": "useEffect(() =>{\n const unlisten = onAuthStateChanged(\n authUser => {\n authUser\n ? setAuthUser(authUser)\n : setAuthUser(null);\n },\n );\n return () => {\n unlisten();\n }\n }, []);\n"
},
{
"answer_id": 74597914,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": true,
"text": "const [user, setUser] = useState<User | null>(null);\n\nuseEffect(() => {\n const auth = getAuth();\n const unsubscribe = onAuthStateChanged(auth, user => {\n if (user) {\n setUser(user);\n }\n });\n // Don't listen on stateChange anymore if component did unmount.\n return () => {\n unsubscribe();\n }\n}, []);\n import { User } from \"firebase/auth\";\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19379011/"
] |
74,596,066
|
<p>I want to perform a fill-down activity in PgSQL</p>
<p>DDL:</p>
<pre><code>create table brands
(
id int,
category varchar(20),
brand_name varchar(20)
);
insert into brands values
(1,'chocolates','5-star')
,(2,null,'dairy milk')
,(3,null,'perk')
,(4,null,'eclair')
,(5,'Biscuits','britannia')
,(6,null,'good day')
,(7,null,'boost')
,(8,'shampoo','h&s')
,(9,null,'dove');
</code></pre>
<p>Expected output is:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>category</th>
<th>brand_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>chocolates</td>
<td>5-star</td>
</tr>
<tr>
<td>chocolates</td>
<td>dairy milk</td>
</tr>
<tr>
<td>chocolates</td>
<td>perk</td>
</tr>
<tr>
<td>chocolates</td>
<td>eclair</td>
</tr>
<tr>
<td>Biscuits</td>
<td>britannia</td>
</tr>
<tr>
<td>Biscuits</td>
<td>good day</td>
</tr>
<tr>
<td>Biscuits</td>
<td>boost</td>
</tr>
<tr>
<td>Shampoo</td>
<td>h&s</td>
</tr>
<tr>
<td>Shampoo</td>
<td>dove</td>
</tr>
</tbody>
</table>
</div>
<p>I tried using the following script but it doesn't seem to work.</p>
<pre><code>select id,
first_value(category)
over(order by case when category is not null then id end desc nulls last) as category,
brand_name
from brands
</code></pre>
<p>Can someone suggest a fix.</p>
<p>In MS SQL the following snippet seems to work fine.</p>
<pre><code>select id,
first_value (category) IGNORE NULLS
over(order by id desc
rows between current row and unbounded following) as category,
brand_name
FROM brands
ORDER BY id
</code></pre>
|
[
{
"answer_id": 74596260,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 3,
"selected": true,
"text": "with cte as (\nselect id,\n category,\n count(category) over (order by id) as category_id,\n brand_name\n from brands)\nselect id,\n first_value(category) over (partition by category_id order by id) as category,\n brand_name\n from cte;\n select id,\n (array_agg(category) over (order by id))[max(case when category is null then 0 else id end) over (order by id)] as category,\n brand_name\n from brands;\n"
},
{
"answer_id": 74596855,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CTE IGNORE NULLS -- CREATE your function\nCREATE FUNCTION yourFunction(STATE anyelement, VALUE anyelement)\n RETURNS anyelement\n IMMUTABLE PARALLEL safe\nAS\n$$\nSELECT COALESCE(VALUE, STATE); -- Replace NULL values here\n$$ LANGUAGE SQL;\n -- CREATE your aggregate\nCREATE AGGREGATE yourAggregate(ANYELEMENT) (\n sfunc = yourFunction, -- Call your function here\n stype = ANYELEMENT\n);\n SELECT id, \n yourAggregate(category) -- Call your aggregate here\n OVER (ORDER BY id, category), \n brand_name\nFROM brands\nORDER BY id;\n"
},
{
"answer_id": 74596871,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "RESPECT NULLS IGNORE NULLS lead lag first_value last_value nth_value RESPECT NULLS"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16640543/"
] |
74,596,071
|
<p>I was writing a code to append a card with a new header every time a button is pressed also the header is dynamically providing by user. the problem is i cant make the function work properly for more than one card. I know the problem is that every card has the same class hence the new header will be appended to each card.I also want to add different user input lists to these cards.</p>
<pre><code> $(".add").click(function(){
let list = $("#userInp").val()
$("#mainCard").append('<div class="card col-xl-3" ><div class="card-header" id ="head" ></div><div class="card body" ><ul></ul></div></div>')
$("#mainCard").find("#head").append('<button type = "checkbox" class ="form-check-input" id = "checkbox01"></button>'+list+'')
})
</code></pre>
<p>This is my code.And thanks for helping me.</p>
|
[
{
"answer_id": 74596260,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 3,
"selected": true,
"text": "with cte as (\nselect id,\n category,\n count(category) over (order by id) as category_id,\n brand_name\n from brands)\nselect id,\n first_value(category) over (partition by category_id order by id) as category,\n brand_name\n from cte;\n select id,\n (array_agg(category) over (order by id))[max(case when category is null then 0 else id end) over (order by id)] as category,\n brand_name\n from brands;\n"
},
{
"answer_id": 74596855,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CTE IGNORE NULLS -- CREATE your function\nCREATE FUNCTION yourFunction(STATE anyelement, VALUE anyelement)\n RETURNS anyelement\n IMMUTABLE PARALLEL safe\nAS\n$$\nSELECT COALESCE(VALUE, STATE); -- Replace NULL values here\n$$ LANGUAGE SQL;\n -- CREATE your aggregate\nCREATE AGGREGATE yourAggregate(ANYELEMENT) (\n sfunc = yourFunction, -- Call your function here\n stype = ANYELEMENT\n);\n SELECT id, \n yourAggregate(category) -- Call your aggregate here\n OVER (ORDER BY id, category), \n brand_name\nFROM brands\nORDER BY id;\n"
},
{
"answer_id": 74596871,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "RESPECT NULLS IGNORE NULLS lead lag first_value last_value nth_value RESPECT NULLS"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619829/"
] |
74,596,098
|
<p>Some time ago I <code>git fetch</code> a branch from a remote repo.
Let's call it <code>origin/thebranch</code>
So I had that and also my local <code>thebranch</code>
I checkout a new branch on top of that and did my work
Later I push that new branch into the remote after rebasing it to the latest master</p>
<p>The old <code>origin/thebranch</code> stayed in the same place after the rebase</p>
<p>So now I have been told there is new work in <code>origin/thebranch</code> so I did <code>git fetch origin thebranch</code>.</p>
<p>I got</p>
<pre><code>From <remote repo url>
* branch thebranch -> FETCH_HEAD
</code></pre>
<p>and turns out nothing happened
the branch (both remote and local) are in the same place and I did not get the latests commits of "the branch"</p>
<p>What can I do here?</p>
<p>(btw <code>thebranch</code> is written by a colleague so I am limited on what I can do I suppose)</p>
|
[
{
"answer_id": 74596260,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 3,
"selected": true,
"text": "with cte as (\nselect id,\n category,\n count(category) over (order by id) as category_id,\n brand_name\n from brands)\nselect id,\n first_value(category) over (partition by category_id order by id) as category,\n brand_name\n from cte;\n select id,\n (array_agg(category) over (order by id))[max(case when category is null then 0 else id end) over (order by id)] as category,\n brand_name\n from brands;\n"
},
{
"answer_id": 74596855,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CTE IGNORE NULLS -- CREATE your function\nCREATE FUNCTION yourFunction(STATE anyelement, VALUE anyelement)\n RETURNS anyelement\n IMMUTABLE PARALLEL safe\nAS\n$$\nSELECT COALESCE(VALUE, STATE); -- Replace NULL values here\n$$ LANGUAGE SQL;\n -- CREATE your aggregate\nCREATE AGGREGATE yourAggregate(ANYELEMENT) (\n sfunc = yourFunction, -- Call your function here\n stype = ANYELEMENT\n);\n SELECT id, \n yourAggregate(category) -- Call your aggregate here\n OVER (ORDER BY id, category), \n brand_name\nFROM brands\nORDER BY id;\n"
},
{
"answer_id": 74596871,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "RESPECT NULLS IGNORE NULLS lead lag first_value last_value nth_value RESPECT NULLS"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451521/"
] |
74,596,124
|
<p>I think this problem is to use Popup or eventHandler. But when i used Popup, The circle is created but not removed.
And I have no idea how to make a circle using eventHandlers.
This First Code is use popup about this porblem.</p>
<pre><code> <MapContainer
center={[48.864716, 2.349]}
zoom={2}
scrollWheelZoom={true}
zoomControl={false}
style={{ width: "100%", height: "100%" }}
minZoom={2}
maxZoom={5}
doubleClickZoom={false}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Polygon positions={overline} />
<Marker position={[36.5, 130]} >
<Popup >Korea
<Circle center={[36.5, 130]} radius={1000000} />
</Popup>
</Marker>
</MapContainer>
</code></pre>
<p><a href="https://i.stack.imgur.com/ZhW4d.png" rel="nofollow noreferrer">Here is how it looks</a></p>
<p>The Code with eventHandler.</p>
<pre><code><MapContainer
center={[48.864716, 2.349]}
zoom={2}
scrollWheelZoom={true}
zoomControl={false}
style={{ width: "100%", height: "100%" }}
minZoom={2}
maxZoom={5}
doubleClickZoom={false}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Polygon positions={overline} />
<Marker position={[36.5, 130]} eventHandlers ={{click : (e) => drawCircle(e.latlng)}}>
<Popup >Korea</Popup>
</Marker>
</MapContainer>
</code></pre>
<p><a href="https://i.stack.imgur.com/TvyUN.png" rel="nofollow noreferrer">How it looks with event handler</a></p>
<p>Please help me</p>
<p>I used both EventHandler and popup. But I don't know how to fix it.</p>
|
[
{
"answer_id": 74596260,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 3,
"selected": true,
"text": "with cte as (\nselect id,\n category,\n count(category) over (order by id) as category_id,\n brand_name\n from brands)\nselect id,\n first_value(category) over (partition by category_id order by id) as category,\n brand_name\n from cte;\n select id,\n (array_agg(category) over (order by id))[max(case when category is null then 0 else id end) over (order by id)] as category,\n brand_name\n from brands;\n"
},
{
"answer_id": 74596855,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "CTE IGNORE NULLS -- CREATE your function\nCREATE FUNCTION yourFunction(STATE anyelement, VALUE anyelement)\n RETURNS anyelement\n IMMUTABLE PARALLEL safe\nAS\n$$\nSELECT COALESCE(VALUE, STATE); -- Replace NULL values here\n$$ LANGUAGE SQL;\n -- CREATE your aggregate\nCREATE AGGREGATE yourAggregate(ANYELEMENT) (\n sfunc = yourFunction, -- Call your function here\n stype = ANYELEMENT\n);\n SELECT id, \n yourAggregate(category) -- Call your aggregate here\n OVER (ORDER BY id, category), \n brand_name\nFROM brands\nORDER BY id;\n"
},
{
"answer_id": 74596871,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 1,
"selected": false,
"text": "RESPECT NULLS IGNORE NULLS lead lag first_value last_value nth_value RESPECT NULLS"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619840/"
] |
74,596,125
|
<p>I have this dataframe</p>
<pre><code>d = {
'geoid': ['13085970205'],
'FIPS': ['13085'],
'Year': [2024],
'parameters': [{"Year": 2024, "hpi_prediction": 304.32205}],
'geometry':[
{
"coordinates": [[[[-84.126456, 34.389734], [-84.12641, 34.39026], [-84.126323, 34.39068]]]],
"parameters": {"Year": 2024, "hpi_prediction": 304.32205},
"type": "MultiPolygon"
}
]
}
dd = pd.DataFrame(data=d)
</code></pre>
<p>When I want to write this out I use <code>import geopandas as gpd</code> to convert the data into a dataframe like this</p>
<pre><code>df_geopandas_hpi = gpd.GeoDataFrame(dd[['geoid', 'geometry']])
</code></pre>
<p>Once this happens the <code>parameters</code> key in the original dataframe gets erased. Why? Note that the type of geometry in example dataframe is <code>geojson.geometry.MultiPolygon</code>. How can I avoid this from happening?</p>
<p>What I essentially need to do is the following</p>
<pre><code>if ~os.path.exists('../verus_data'):
os.mkdir('../verus_data')
for county, df_county in dd.groupby('FIPS'):
if ~os.path.exists('../verus_data/'+str(county)):
os.mkdir('../verus_data/'+str(county))
if ~os.path.exists('../verus_data/'+str(county)+'/'+'predicted'):
os.mkdir('../verus_data/'+str(county)+'/'+'predicted')
if ~os.path.exists('../verus_data/'+str(county)+'/'+'analyzed'):
os.mkdir('../verus_data/'+str(county)+'/'+'analyzed')
df_hpi = df_county[df_county['key'] == 'hpi']
df_analyzed = df_county[df_county['key'] == 'analyzed']
for year, df_year in df_hpi.groupby('Year'):
if ~os.path.exists('../verus_data/'+str(county)+'/'+'predicted'+'/'+str(year)):
os.mkdir('../verus_data/'+str(county)+'/'+'predicted'+'/'+str(year))
df_geopandas_hpi = gpd.GeoDataFrame(df_year[['geoid', 'geometry', 'parameters']])
df_geopandas_hpi.to_file('../verus_data/'+str(county)+'/'+'predicted'+'/'+str(year)+'/'+'hpi_predictions.geojson', driver="GeoJSON")
for year, df_year in df_analyzed.groupby('Year'):
if ~os.path.exists('../verus_data/'+str(county)+'/'+'analyzed'+'/'+str(year)):
os.mkdir('../verus_data/'+str(county)+'/'+'analyzed'+'/'+str(year))
df_geopandas_analyzed = gpd.GeoDataFrame(df_year[['geoid', 'geometry', 'parameters']])
df_geopandas_analyzed.to_file('../verus_data/'+str(county)+'/'+'analyzed'+'/'+str(year)+'/'+'analyzed_values.geojson', driver="GeoJSON")
</code></pre>
<p>I need to somehow write out these geojson files while keeping parameters key intact.</p>
|
[
{
"answer_id": 74596214,
"author": "Michael Delgado",
"author_id": 3888719,
"author_profile": "https://Stackoverflow.com/users/3888719",
"pm_score": 1,
"selected": false,
"text": "shapely shapely.geometry.shape In [10]: shape = shapely.geometry.shape(\n ...: {\n ...: \"coordinates\": [[[[-84.126456, 34.389734], [-84.12641, 34.39026], [-84.126323, 34.39068]]]],\n ...: \"parameters\": {\"Year\": 2024, \"hpi_prediction\": 304.32205},\n ...: \"type\": \"MultiPolygon\"\n ...: }\n ...: )\n\nIn [11]: shape\nOut[11]: <shapely.geometry.multipolygon.MultiPolygon at 0x11040eb60>\n\nIn [12]: shape.parameters\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\nInput In [12], in <cell line: 1>()\n----> 1 shape.parameters\n\nAttributeError: 'MultiPolygon' object has no attribute 'parameters'\n \nIn [21]: gdf = gpd.GeoDataFrame(dd[[\"geoid\", \"geometry\"]])\n ...: gdf[\"parameters\"] = dd.geometry.str[\"parameters\"]\n\nIn [22]: gdf\nOut[22]:\n geoid geometry parameters\n0 13085970205 {'coordinates': [[[[-84.126456, 34.389734], [-... {'Year': 2024, 'hpi_prediction': 304.32205}\n dd In [27]: dd.loc[0, \"geometry\"][\"parameters\"][\"hpi_prediction\"]\nOut[27]: 304.32205\n"
},
{
"answer_id": 74596368,
"author": "Wolfy",
"author_id": 7700802,
"author_profile": "https://Stackoverflow.com/users/7700802",
"pm_score": 0,
"selected": false,
"text": "df_geopandas_hpi = gpd.GeoDataFrame(df_year[['geoid', 'geometry', 'parameters']])\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7700802/"
] |
74,596,129
|
<p>I'm trying to use typing with a function that has conditional parameters, that works like this:</p>
<pre><code>from typing import Optional, Union
class Foo:
some_param_to_check: str = 'foo_name'
one_param_exclusive_to_foo: int
class Bar:
some_param_to_check: str = 'bar_name'
another_param_exclusive_to_bar: str
def some_process_that_returns_a_bool(
f_or_b: Union[Foo, Bar],
a_name: str,
) -> bool:
return f_or_b.some_param_to_check == a_name
def do_something_with_foo_or_bar(
foo: Optional[Foo],
bar: Optional[Bar],
some_name: str,
) -> bool:
if not foo and not bar:
raise ValueError('You need to specify either "foo" or "bar".')
# I added this explicit type hint after the first error, hoping it would solve the issue:
foo_or_bar: Union[Foo, Bar] # later becomes Union[Foo, Bar, None]
foo_or_bar = foo if foo else bar
return some_process_that_returns_a_bool(foo_or_bar, some_name)
foo_obj = Foo()
bar_obj = Bar()
# This will work:
do_something_with_foo_or_bar(foo_obj, bar_obj, 'test_string')
# This will also work:
do_something_with_foo_or_bar(foo_obj, None, 'test_string')
# This too:
do_something_with_foo_or_bar(None, bar_obj, 'test_string')
# But this should not:
do_something_with_foo_or_bar(None, None, 'test_string')
</code></pre>
<p>To add more context:</p>
<p>The function works by expecting <code>foo</code>, or, if not available, <code>bar</code>. If <code>foo</code> is not <code>None</code>, <code>bar</code> will essentially be ignored.</p>
<p>When checking with mypy, it complains about:</p>
<pre><code>Incompatible types in assignment (expression has type "Union[Foo, Bar, None]", variable has type "Union[Foo, Bar]"
</code></pre>
<p>(I'm guessing because of the <code>Optional</code> in the parameter type hints.)</p>
<p>If I then add <code>None</code> as the type hint for <code>foo_or_bar</code> then the error becomes:</p>
<pre><code>error: Item "None" of "Union[Foo, Bar, None]" has no attribute "some_param_to_check"
</code></pre>
<p>How would I fix this so that mypy stops complaining (while still keeping the type hints)?</p>
|
[
{
"answer_id": 74596218,
"author": "Azer",
"author_id": 9246344,
"author_profile": "https://Stackoverflow.com/users/9246344",
"pm_score": 1,
"selected": false,
"text": "some_process_that_returns_a_bool some_param_to_check None None some_process_that_returns_a_bool None f_or_b None def some_process_that_returns_a_bool(\n f_or_b: Union[Foo, Bar, None],\n a_name: str,\n) -> bool:\n if f_or_b is None:\n # Handle None...\n return False\n else:\n return f_or_b.some_param_to_check == a_name\n some_param_to_check f_or_b None False f_or_b None"
},
{
"answer_id": 74596518,
"author": "Blckknght",
"author_id": 1405065,
"author_profile": "https://Stackoverflow.com/users/1405065",
"pm_score": 3,
"selected": true,
"text": "if not foo and not bar None def do_something_with_foo_or_bar(\n foo: Optional[Foo],\n bar: Optional[Bar],\n some_name: str,\n) -> bool:\n foo_or_bar: Union[Foo, Bar]\n if foo:\n foo_or_bar = foo\n elif bar:\n foo_or_bar = bar\n else:\n raise ValueError('You need to specify either \"foo\" or \"bar\".')\n\n return some_process_that_returns_a_bool(foo_or_bar, some_name)\n foo_or_bar if elif foo bar"
},
{
"answer_id": 74599323,
"author": "SUTerliakov",
"author_id": 14401160,
"author_profile": "https://Stackoverflow.com/users/14401160",
"pm_score": 1,
"selected": false,
"text": "from typing import Optional, Union, overload\n\n\nclass Foo:\n some_param_to_check: str = 'foo_name'\n one_param_exclusive_to_foo: int\n\n\nclass Bar:\n some_param_to_check: str = 'bar_name'\n another_param_exclusive_to_bar: str\n\n\ndef some_process_that_returns_a_bool(\n f_or_b: Union[Foo, Bar],\n a_name: str,\n) -> bool:\n return f_or_b.some_param_to_check == a_name\n\n@overload\ndef do_something_with_foo_or_bar(\n foo: Foo,\n bar: Optional[Bar],\n some_name: str,\n) -> bool: ...\n@overload\ndef do_something_with_foo_or_bar(\n foo: Optional[Foo],\n bar: Bar,\n some_name: str,\n) -> bool: ...\ndef do_something_with_foo_or_bar(\n foo: Optional[Foo],\n bar: Optional[Bar],\n some_name: str,\n) -> bool:\n foo_or_bar: Union[Foo, Bar] # This annotation was missing\n if foo:\n foo_or_bar = foo\n elif bar:\n foo_or_bar = bar\n else:\n raise ValueError('You need to specify either \"foo\" or \"bar\".')\n\n return some_process_that_returns_a_bool(foo_or_bar, some_name)\n \n\ndo_something_with_foo_or_bar(Foo(), Bar(), '')\ndo_something_with_foo_or_bar(None, Bar(), '')\ndo_something_with_foo_or_bar(Foo(), None, '')\ndo_something_with_foo_or_bar(None, None, '') # Line 51\n main.py:51: error: No overload variant of \"do_something_with_foo_or_bar\" matches argument types \"None\", \"None\", \"str\" [call-overload]\nmain.py:51: note: Possible overload variants:\nmain.py:51: note: def do_something_with_foo_or_bar(foo: Foo, bar: Optional[Bar], some_name: str) -> bool\nmain.py:51: note: def do_something_with_foo_or_bar(foo: Optional[Foo], bar: Bar, some_name: str) -> bool\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795433/"
] |
74,596,149
|
<p>I tried to display snackBar at the bottom when an error occurs by using the try ... catch syntax as shown below, but for some reason, it is not displayed. Does anyone have a solution for this?</p>
<pre><code> Widget _confirmButton() {
return SizedBox(
height: 54,
width: double.infinity,
child: ElevatedButton(
onPressed: () {
try {
_tryValidation();
resetPassword(userEmail).then(
(value) => Get.to(
() => CompletePasswordReset(),
),
);
} catch (e) {
const snackBar = SnackBar(
content: Text('아이디 또는 비밀번호가 맞지 않습니다.'),
backgroundColor: errorColor40,
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(30),
duration: Duration(seconds: 1),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
},
child: Text(
'가입여부 확인',
style: TextStyle(
color: baseColor10,
fontFamily: 'semi-bold',
fontSize: titleMedium,
),
),
style: ElevatedButton.styleFrom(
backgroundColor: primaryColor50,
elevation: 0,
shadowColor: Colors.transparent,
side: BorderSide(
color: Colors.transparent,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
),
),
);
}
</code></pre>
|
[
{
"answer_id": 74596870,
"author": "Paulo",
"author_id": 15649348,
"author_profile": "https://Stackoverflow.com/users/15649348",
"pm_score": 3,
"selected": true,
"text": "_tryValidation resetPassword throw 500;\n try {\n throw 500;\n} catch (e) {\n const snackBar = SnackBar(\n content: Text('아이디 또는 비밀번호가 맞지 않습니다.'),\n backgroundColor: errorColor40,\n behavior: SnackBarBehavior.floating,\n margin: EdgeInsets.all(30),\n duration: Duration(seconds: 1),\n );\n ScaffoldMessenger.of(context).showSnackBar(snackBar);\n}\n"
},
{
"answer_id": 74596926,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 1,
"selected": false,
"text": "Get.snackbar('아이디 또는 비밀번호가 맞지 않습니다', '',\n margin: EdgeInsets.all(15),\n padding: EdgeInsets.all(0),\n duration: Duration(milliseconds: 1000),\n snackPosition: SnackPosition.BOTTOM,\n );\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19443112/"
] |
74,596,166
|
<p>I have a forum system where user A refers user B. Then user B refers user C. Only then it should be allowed to view. And I want to list user C under user A as well. Here is the code I tried to use. It generated uid of B successfully. But I am unable to get to C part. Here is the code.</p>
<pre><code>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT uid FROM mybb_users WHERE referrer='24'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$abc= $row["uid"];
}
} else {
echo "0 results";
}
$sql = "SELECT uid FROM mybb_users WHERE referrer='$abc'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["uid"];
}
} else {
echo "0 results";
}
</code></pre>
<p>It would be great to know what I am doing wrong?</p>
<p>I tried to select where clause but it returns to zero result and does not work as it should be working.
The SQL I used is</p>
<pre><code>
$sql = "SELECT uid FROM mybb_users WHERE referrer='$abc'";
</code></pre>
<p>and it returns to error message 0.</p>
|
[
{
"answer_id": 74596870,
"author": "Paulo",
"author_id": 15649348,
"author_profile": "https://Stackoverflow.com/users/15649348",
"pm_score": 3,
"selected": true,
"text": "_tryValidation resetPassword throw 500;\n try {\n throw 500;\n} catch (e) {\n const snackBar = SnackBar(\n content: Text('아이디 또는 비밀번호가 맞지 않습니다.'),\n backgroundColor: errorColor40,\n behavior: SnackBarBehavior.floating,\n margin: EdgeInsets.all(30),\n duration: Duration(seconds: 1),\n );\n ScaffoldMessenger.of(context).showSnackBar(snackBar);\n}\n"
},
{
"answer_id": 74596926,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 1,
"selected": false,
"text": "Get.snackbar('아이디 또는 비밀번호가 맞지 않습니다', '',\n margin: EdgeInsets.all(15),\n padding: EdgeInsets.all(0),\n duration: Duration(milliseconds: 1000),\n snackPosition: SnackPosition.BOTTOM,\n );\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20619949/"
] |
74,596,280
|
<p>i have this parrent <strong>baby_login</strong> file
it has a google sign up button which is a componet with file name <strong>Sign</strong>
when i click on the button i want <strong>userInfo</strong> to pass from <strong>sign.js</strong> to <strong>Signupfor.js</strong> how can i achive this ?</p>
<pre><code>export default function Baby_login() {
return (
<View style={styles.prheight}>
<Image
source={require('../assets/images/mother.png')}
style={{
width: 300,
marginLeft: 20,
marginTop: 0,
justifyContent: 'center',
height: 300,
textAlign: 'center',
}}
/>
<View style={styles.buttonw}>
<Sign />
</View>
</View>
);
}
</code></pre>
<p><strong>sign.js</strong></p>
<pre><code>
export default function Sign(navigation) {
async function onGoogleButtonPress() {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
console.log(userInfo);
setuserInfo(userInfo);
}
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<GoogleSigninButton
style={{width: 192, height: 48}}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Light}
onPress={onGoogleButtonPress}
// disabled={this.state.isSigninInProgress}
/>
</View>
</View>
);
}
</code></pre>
<p><strong>Signupfor.js</strong></p>
<pre><code>
import React from 'react';
export default function Signupfor(userInfo) {
return <View style={styles.prheight}></View>;
}
</code></pre>
<p><strong>app.js</strong></p>
<p>here i have updated the app.js file so that u can see naviagtion details</p>
<pre><code>import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {Provider as PaperProvider} from 'react-native-paper';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {StyleSheet, Text, View} from 'react-native';
import Baby from './components/baby_login';
import {Avatar, Card, Title, Paragraph} from 'react-native-paper';
import {Image} from 'react-native';
import Signupfor from './components/signupfor';
import Pregnant from './components/pregent_login';
import {Button} from 'react-native';
function Dashbord({navigation}) {
const LeftContent = props => <Avatar.Icon {...props} icon="folder" />;
return (
<View style={styles.main}>
<Title
style={{
textAlign: 'center',
marginBottom: 30,
fontSize: 28,
fontFamily: 'Poppins-ExtraBold',
}}>
Tell us about you
</Title>
<Card
style={styles.main2}
onPress={() => navigation.navigate('Pregnant')}>
<Image
source={require('./assets/images/pregnant.png')}
style={{
width: 80,
marginLeft: 90,
marginTop: 0,
justifyContent: 'center',
height: 80,
textAlign: 'center',
}}
/>
{/* <Image source={require('./assets/images/pregnant.png')} /> */}
<Text
style={{
textAlign: 'center',
fontSize: 20,
fontFamily: 'Poppins-ExtraBold',
}}>
I am pregnant
</Text>
</Card>
<Card style={styles.main2} onPress={() => navigation.navigate('Baby')}>
<Image
source={require('./assets/images/mother.png')}
style={{
width: 80,
marginLeft: 90,
marginTop: 0,
justifyContent: 'center',
height: 80,
textAlign: 'center',
}}
/>
<Text
style={{
textAlign: 'center',
fontSize: 20,
fontFamily: 'Poppins-ExtraBold',
}}>
i am a mother
</Text>
</Card>
</View>
);
}
function HomeScreen({navigation}) {
return (
<View style={styles.prheight}>
<View>
<Text style={styles.r}>home</Text>
</View>
<View style={styles.buttonw}>
<Button
color="#7743DB"
title="Lets Go"
onPress={() => navigation.navigate('Dashbord')}
/>
</View>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<PaperProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
options={{headerShown: false}}
name="Home"
component={HomeScreen}
/>
<Stack.Screen name="Dashbord" component={Dashbord} />
<Stack.Screen name="Baby" component={Baby} />
<Stack.Screen name="Pregnant" component={Pregnant} />
<Stack.Screen name="Signupfor" component={Signupfor} />
</Stack.Navigator>
</NavigationContainer>
</PaperProvider>
);
}
</code></pre>
|
[
{
"answer_id": 74596516,
"author": "Asmeeta Rathod",
"author_id": 14990516,
"author_profile": "https://Stackoverflow.com/users/14990516",
"pm_score": -1,
"selected": false,
"text": "Sign export default function Baby_login(props) {\n return (\n <View style={styles.prheight}>\n <Image\n source={require('../assets/images/mother.png')}\n style={{\n width: 300,\n marginLeft: 20,\n marginTop: 0,\n justifyContent: 'center',\n\n height: 300,\n textAlign: 'center',\n }}\n />\n <View style={styles.buttonw}>\n <Sign navigation={props.navigation} />\n </View>\n </View>\n );\n}\n Sign export default function Sign(navigation) {\n \n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n console.log(userInfo);\n setuserInfo(userInfo);\n navigation.navigate(\"Signupfor\", { userInfo })\n \n }\n return (\n <View style={styles.prheight}>\n <View style={styles.buttonw}>\n <GoogleSigninButton\n style={{width: 192, height: 48}}\n size={GoogleSigninButton.Size.Wide}\n color={GoogleSigninButton.Color.Light}\n onPress={onGoogleButtonPress}\n // disabled={this.state.isSigninInProgress}\n />\n </View>\n </View>\n );\n}\n Signupfor import React from 'react';\n\nexport default function Signupfor(props) {\n const {userInfo} = props?.route?.params\n return <View style={styles.prheight}></View>;\n}\n"
},
{
"answer_id": 74596553,
"author": "Hamas Hassan",
"author_id": 13795089,
"author_profile": "https://Stackoverflow.com/users/13795089",
"pm_score": 2,
"selected": true,
"text": "export default function Sign({navigation}) {\n \n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n console.log(userInfo);\n setuserInfo(userInfo);\n navigation.navigate(\"Signupfor\", { userInfo })\n\n }\n return (\n <View style={styles.prheight}>\n <View style={styles.buttonw}>\n <GoogleSigninButton\n style={{width: 192, height: 48}}\n size={GoogleSigninButton.Size.Wide}\n color={GoogleSigninButton.Color.Light}\n onPress={onGoogleButtonPress}\n // disabled={this.state.isSigninInProgress}\n />\n </View>\n </View>\n );\n}\n import React from 'react';\n\nexport default function Signupfor(props) {\n\n const {userInfo} = props?.route?.params\n\n return <View style={styles.prheight}></View>;\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17814678/"
] |
74,596,303
|
<p>Table headings through the table are being converted into single column headings.</p>
<pre><code>url = "https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%20North%20Coast%20Koala%20Management,Valley%2C%20Clarence%20Valley%20and%20Taree."
dfs = pd.read_html(url)
df = dfs[0]
df.head()
</code></pre>
<p><img src="https://i.stack.imgur.com/wWu69.png" alt="output" /></p>
<p>Be great if I could have the High preferred use as a column that assigns to the correct species.
Tried reset_index() this did not work.
I'm lost for searching can't find anything similar.</p>
<p>Response to @Master Oogway and thanks @DYZ for the edits.</p>
<p>There are multiple "table-striped"</p>
<p><a href="https://i.stack.imgur.com/ZDnhD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZDnhD.png" alt="Screen shot inspect element - multiple class ="table-striped"" /></a></p>
<p>The amendment suggested removes the error, but does not interact with the second table.
Take White Box, Eucalyptus albens. Occurs in second table and not first.
If I export dftable and filter - no White Box:</p>
<p><a href="https://i.stack.imgur.com/xy3zF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xy3zF.png" alt="Filter no White Box" /></a></p>
<p>If I write htmltable to .txt when using find_all and search, it's there:</p>
<p><a href="https://i.stack.imgur.com/k5nbY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k5nbY.png" alt="enter image description here" /></a></p>
<p>I have never done this before and appreciate that this is annoying.
Thanks for the help so far.</p>
<p>It appears that find_all is gathering all the table data.
But the creating of dftable is limiting to the first "table-striped".</p>
|
[
{
"answer_id": 74596556,
"author": "DYZ",
"author_id": 4492932,
"author_profile": "https://Stackoverflow.com/users/4492932",
"pm_score": 2,
"selected": false,
"text": "read_html <thead> BeautifulSoup import bs4\nimport urllib.request\n\nsoup = bs4.BeautifulSoup(urllib.request.urlopen(url))\ndata = [[\"\".join(cell.strings).strip() \n for cell in row.find_all(['td', 'th'])] \n for row in soup.find_all('table')[0].find_all('tr')] \ntable = pd.DataFrame(data[1:])\\\n .rename(columns=dict(enumerate(data[0])))\\\n .dropna(how='all')\n"
},
{
"answer_id": 74597153,
"author": "Master Oogway",
"author_id": 6297478,
"author_profile": "https://Stackoverflow.com/users/6297478",
"pm_score": 2,
"selected": true,
"text": "url = \"https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%20North%20Coast%20Koala%20Management,Valley%2C%20Clarence%20Valley%20and%20Taree.\"\n\n#load html with urllib\nhtml = urllib.request.urlopen(url)\nsoup = BeautifulSoup(html.read(), 'lxml')\n\n\n#get the table you're trying to get based\n#on html elements\nhtmltable = soup.find('table', { 'class' : 'table-striped' })\n def tableDataText(table): \n \"\"\"Parses a html segment started with tag <table> followed \n by multiple <tr> (table rows) and inner <td> (table data) tags. \n It returns a list of rows with inner columns. \n Accepts only one <th> (table header/data) in the first row.\n \"\"\"\n def rowgetDataText(tr, coltag='td'): # td (data) or th (header) \n return [td.get_text(strip=True) for td in tr.find_all(coltag)] \n rows = []\n trs = table.find_all('tr')\n headerow = rowgetDataText(trs[0], 'th')\n \n\n if headerow: # if there is a header row include first\n trs = trs[1:]\n for tr in trs: # for every table row\n\n #this part is modified\n #basically we'll get the type of \n #used based of the second table header\n #in your url table html\n if(rowgetDataText(tr, 'th')):\n last_head = rowgetDataText(tr, 'th')\n\n #we'll add to the list a dict\n #that contains \"common name\", \"species name\", \"type\" (use type)\n if(rowgetDataText(tr, 'td')):\n row = rowgetDataText(tr, 'td')\n rows.append({headerow[0]: row[0], headerow[1]: row[1], 'type': last_head[0]})\n \n return rows\n \nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\nurl = \"https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%20North%20Coast%20Koala%20Management,Valley%2C%20Clarence%20Valley%20and%20Taree.\"\n\n#load html with urllib\nhtml = urllib.request.urlopen(url)\nsoup = BeautifulSoup(html.read(), 'lxml')\n\n\n#get the table you're trying to get based\n#on html elements\nhtmltable = soup.find('table', { 'class' : 'table-striped' })\n\n\n#modified function taken from: https://stackoverflow.com/a/58274853/6297478\n#to fit your data shape in a way that \n#you can use. \ndef tableDataText(table): \n \"\"\"Parses a html segment started with tag <table> followed \n by multiple <tr> (table rows) and inner <td> (table data) tags. \n It returns a list of rows with inner columns. \n Accepts only one <th> (table header/data) in the first row.\n \"\"\"\n def rowgetDataText(tr, coltag='td'): # td (data) or th (header) \n return [td.get_text(strip=True) for td in tr.find_all(coltag)] \n rows = []\n trs = table.find_all('tr')\n headerow = rowgetDataText(trs[0], 'th')\n \n\n if headerow: # if there is a header row include first\n trs = trs[1:]\n for tr in trs: # for every table row\n\n #this part is modified\n #basically we'll get the type of \n #used based of the second table header\n #in your url table html\n if(rowgetDataText(tr, 'th')):\n last_head = rowgetDataText(tr, 'th')\n\n #we'll add to the list a dict\n #that contains \"common name\", \"species name\", \"type\" (use type)\n if(rowgetDataText(tr, 'td')):\n row = rowgetDataText(tr, 'td')\n rows.append({headerow[0]: row[0], headerow[1]: row[1], 'type': last_head[0]})\n \n return rows\n\n#we store our results from the function in list_table\nlist_table = tableDataText(htmltable)\n\n#turn our table into a DataFrame\ndftable = pd.DataFrame(list_table)\ndftable\n"
},
{
"answer_id": 74597232,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 0,
"selected": false,
"text": "css selectors stripped_strings find_previous() list dicts dataframe from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nurl = \"https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%20North%20Coast%20Koala%20Management,Valley%2C%20Clarence%20Valley%20and%20Taree.\"\n\ndata = []\nsoup = BeautifulSoup(requests.get(url).text)\nfor e in soup.select('table tbody tr'):\n data.append(\n dict(\n zip(\n soup.table.thead.stripped_strings,\n [e.find_previous('th').get_text(strip=True)]+list(e.stripped_strings)\n )\n )\n )\n\npd.DataFrame(data)\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20008689/"
] |
74,596,373
|
<p>I wrote a code in C to find the odd numbers from a given interval of min and max number. The function works well when it is inside the int main() but not well when outside the program as a function.</p>
<p>What's more is that it also prints the incremented number outside the max number given.</p>
<p>This is the code...</p>
<pre><code>#include <stdio.h>
// My Function
int odd_numbers(int x, int y) {
for (int i = x; i <= y; ++i) {
if (i % 2 == 1) {
printf("%d\n",i);
}
}
}
// Main Program
int main(void) {
int min_num, max_num;
printf("Input your minimum number: ");
scanf("%d", &min_num);
printf("Input your maximum number: ");
scanf("%d", &max_num);
printf("%d",odd_numbers(min_num,max_num));
}
</code></pre>
<p>and this is the output...
<a href="https://i.stack.imgur.com/bSQCv.png" rel="nofollow noreferrer">As you can see, it adds an 11 besides the 9...</a>
How can I solve this? I've tried return 0; and it returns the value 0 but i only want to return no number except the odd numbers.</p>
|
[
{
"answer_id": 74596490,
"author": "user8811698",
"author_id": 8811698,
"author_profile": "https://Stackoverflow.com/users/8811698",
"pm_score": 1,
"selected": false,
"text": "int odd_numbers #include <stdio.h>\n\n// My Function\nvoid odd_numbers(int x, int y) \n{\n int i = 0;\n for (int i = x; i <= y; i++) \n {\n if (i % 2 != 0) \n {\n printf(\"%d\\n\", i);\n }\n }\n}\n\n// Main Program\nint main(void) {\n int min_num, max_num;\n\n printf(\"Input your minimum number: \");\n scanf(\"%d\", &min_num);\n printf(\"Input your maximum number: \");\n scanf(\"%d\", &max_num);\n\n odd_numbers(min_num, max_num);\n return 0;\n}\n"
},
{
"answer_id": 74596520,
"author": "m3ow",
"author_id": 20474278,
"author_profile": "https://Stackoverflow.com/users/20474278",
"pm_score": 3,
"selected": true,
"text": "odd_numbers odd_numbers odd_numbers #include <stdio.h>\n// My Function\nvoid odd_numbers(int x, int y) {\n for (int i = x; i <= y; i++) {\n if (i % 2 != 0) {\n printf(\"\\n%d\",i);\n }\n }\n}\n\n// Main Program\nint main(void) {\n int min_num, max_num;\n\n printf(\"Input your minimum number: \");\n scanf(\"%d\", &min_num);\n printf(\"Input your maximum number: \");\n scanf(\"%d\", &max_num);\n\n odd_numbers(min_num,max_num);\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19355117/"
] |
74,596,381
|
<p>How do I get the column name of two tables in a single query ?</p>
<pre><code>SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
where table_name = 'table_name';
</code></pre>
<p>This works for single table. But if I try</p>
<pre><code>SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
where table_name = 'table1'
AND
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
where table_name = 'table2';
</code></pre>
<p>This throws error.</p>
<pre><code>Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS where table_name = 'table2' ' at line 5
Error Code: ER_PARSE_ERROR
</code></pre>
|
[
{
"answer_id": 74596490,
"author": "user8811698",
"author_id": 8811698,
"author_profile": "https://Stackoverflow.com/users/8811698",
"pm_score": 1,
"selected": false,
"text": "int odd_numbers #include <stdio.h>\n\n// My Function\nvoid odd_numbers(int x, int y) \n{\n int i = 0;\n for (int i = x; i <= y; i++) \n {\n if (i % 2 != 0) \n {\n printf(\"%d\\n\", i);\n }\n }\n}\n\n// Main Program\nint main(void) {\n int min_num, max_num;\n\n printf(\"Input your minimum number: \");\n scanf(\"%d\", &min_num);\n printf(\"Input your maximum number: \");\n scanf(\"%d\", &max_num);\n\n odd_numbers(min_num, max_num);\n return 0;\n}\n"
},
{
"answer_id": 74596520,
"author": "m3ow",
"author_id": 20474278,
"author_profile": "https://Stackoverflow.com/users/20474278",
"pm_score": 3,
"selected": true,
"text": "odd_numbers odd_numbers odd_numbers #include <stdio.h>\n// My Function\nvoid odd_numbers(int x, int y) {\n for (int i = x; i <= y; i++) {\n if (i % 2 != 0) {\n printf(\"\\n%d\",i);\n }\n }\n}\n\n// Main Program\nint main(void) {\n int min_num, max_num;\n\n printf(\"Input your minimum number: \");\n scanf(\"%d\", &min_num);\n printf(\"Input your maximum number: \");\n scanf(\"%d\", &max_num);\n\n odd_numbers(min_num,max_num);\n}\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18743683/"
] |
74,596,393
|
<p>I have 2 lists which each have 10 value and i want to multiply the values.</p>
<pre><code>import random
n1_r = random.sample(range(1, 100), 10)
n2_r = random.sample(range(1, 100), 10)
n1 = n1_r
n2 = n2_r
</code></pre>
<p>for example I want to multiply the first value from <code>n1</code> with the first value in <code>n2</code> and so on?</p>
<p>im expecting a new list of 10 values stored in <code>n3</code></p>
|
[
{
"answer_id": 74596433,
"author": "Krishnan Suresh",
"author_id": 19590758,
"author_profile": "https://Stackoverflow.com/users/19590758",
"pm_score": 3,
"selected": true,
"text": "n3 = [a * b for a, b in zip(n1, n2)]\n"
},
{
"answer_id": 74596434,
"author": "tijko",
"author_id": 1230086,
"author_profile": "https://Stackoverflow.com/users/1230086",
"pm_score": 1,
"selected": false,
"text": "array1 = [2, 2, 2, 2]\narray2 = [3, 3, 3, 3]\narray3 = [i * j for i,j in zip(array1, array2)]\n>>> array3\n[6, 6, 6, 6]\n array3 = list(map(lambda x: x[0]*x[1], zip(array1, array2)))\n"
},
{
"answer_id": 74596658,
"author": "Thisara_Welmilla",
"author_id": 12176236,
"author_profile": "https://Stackoverflow.com/users/12176236",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\narray1 = np.array(n1_r)\narray2 = np.array(n2_r)\n \nresult = array1*array2\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434466/"
] |
74,596,396
|
<p>I'm new to Python coming from a JavaScript background. I'm trying to find a solution for the following. I want to build a dictionary from list data on the fly. I only want to add the list entries that are unique, with a count of 1. Any repeats thereafter I want to keep a count of. Hence from a list containing <code>["one", "two", "three", "one"]</code> I want to build a dictionary containing <code>{'one': 2, 'two': 1, 'three': 1}</code> I mean to use the list entries as keys and use the dict values for the respective counts. I can't seem to get Python to do it. My code follows. It's currently adding unpredictably to the dictionary totals. I only seem to be able to add the unique entries in the list this way. No luck with any totals. I wanted to ask if I'm on the wrong track or if I'm missing something with this approach. Can someone please help?</p>
<pre><code>import copy
data = ["one", "two", "three", "one"]
new_dict = {}
# build dictionary from list data and only count (not add) any redundant entries
for x in data:
dict_copy = copy.deepcopy(new_dict) # loop through a copy (safety)
for y in dict_copy:
if x in new_dict: # check if an entry exists?
new_dict[y] += 1 # this count gives unpredictable results !!
else:
new_dict[x] = 1 # new entry
else:
new_dict[x] = 1 # first entry
print(new_dict)
</code></pre>
|
[
{
"answer_id": 74596878,
"author": "Chuck",
"author_id": 1187650,
"author_profile": "https://Stackoverflow.com/users/1187650",
"pm_score": -1,
"selected": false,
"text": "data = [\"one\", \"two\", \"three\", \"one\"]\nnew_dict = {}\n\n\nfor x in data:\n if x in new_dict:\n new_dict[x] = new_dict[x] + 1\n else:\n new_dict[x] = 1\n\nprint(new_dict)\n new_dict = [[x, data.count(x)] for x in set(data)]\n"
},
{
"answer_id": 74596979,
"author": "Parag Tyagi",
"author_id": 3418784,
"author_profile": "https://Stackoverflow.com/users/3418784",
"pm_score": 0,
"selected": false,
"text": "collections.Counter In [1]: from collections import Counter\n\nIn [2]: items = [\"one\", \"two\", \"three\", \"one\"]\n\nIn [3]: Counter(items)\nOut[3]: Counter({'one': 2, 'two': 1, 'three': 1})\n\nIn [4]: dict(Counter(items))\nOut[4]: {'one': 2, 'two': 1, 'three': 1}\n\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1187650/"
] |
74,596,399
|
<p>lets say I have a dataframe like below</p>
<pre><code>+------+------+------+-------------+
| A | B | C | devisor_col |
+------+------+------+-------------+
| 2 | 4 | 10 | 2 |
| 3 | 3 | 9 | 3 |
| 10 | 25 | 40 | 10 |
+------+------+------+-------------+
</code></pre>
<p>what would be the best command to apply a formula using values from the devisor_col. Do note that I have thousand of column and rows.</p>
<p>the result should be like this:</p>
<pre><code>+------+------+------+-------------+
| A | B | V | devisor_col |
+------+------+------+-------------+
| 1 | 2 | 5 | 2 |
| 1 | 1 | 3 | 3 |
| 1 | 1.5 | 4 | 10 |
+------+------+------+-------------+
</code></pre>
<p>I tried using apply map but I dont know why I cant apply it to all columns.</p>
<pre><code>modResult = my_df.applymap(lambda x: x/x["devisor_col"]))
</code></pre>
|
[
{
"answer_id": 74596878,
"author": "Chuck",
"author_id": 1187650,
"author_profile": "https://Stackoverflow.com/users/1187650",
"pm_score": -1,
"selected": false,
"text": "data = [\"one\", \"two\", \"three\", \"one\"]\nnew_dict = {}\n\n\nfor x in data:\n if x in new_dict:\n new_dict[x] = new_dict[x] + 1\n else:\n new_dict[x] = 1\n\nprint(new_dict)\n new_dict = [[x, data.count(x)] for x in set(data)]\n"
},
{
"answer_id": 74596979,
"author": "Parag Tyagi",
"author_id": 3418784,
"author_profile": "https://Stackoverflow.com/users/3418784",
"pm_score": 0,
"selected": false,
"text": "collections.Counter In [1]: from collections import Counter\n\nIn [2]: items = [\"one\", \"two\", \"three\", \"one\"]\n\nIn [3]: Counter(items)\nOut[3]: Counter({'one': 2, 'two': 1, 'three': 1})\n\nIn [4]: dict(Counter(items))\nOut[4]: {'one': 2, 'two': 1, 'three': 1}\n\n"
}
] |
2022/11/28
|
[
"https://Stackoverflow.com/questions/74596399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377095/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.