qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,573,235
<p>I'm importing my plain HTML/CSS website to MODX. I made all of the Elements static, so I can edit them from VS Code + SFTP plugin. But I still have to use MODX Manager to create or delete new Elements.</p> <p>Is there a convenient way to manage Resources and Elements not switching to the web browser with MODX Manager opened?</p> <p>It could be a MODX Extra or VS Code plugin watching <code>/asset/template</code> and automatically creating a MODX Template when a new <code>*.template.tpl</code> file detected.</p>
[ { "answer_id": 74601479, "author": "Bram Verstraten", "author_id": 369143, "author_profile": "https://Stackoverflow.com/users/369143", "pm_score": 2, "selected": true, "text": "<?php\ntry {\n $modxBasePath = '/full/path/to/modx';\n $templatesPath = '/full/path/to/templates';\n $templatesExtension = 'tpl';\n\n require_once \"$modxBasePath/config.core.php\";\n require_once MODX_CORE_PATH.'model/modx/modx.class.php';\n \n $modx = new modX();\n $modx->initialize('mgr');\n\n if (!is_dir($templatesPath)) {\n throw new Exception(\"Path $templatesPath is not a directory\");\n }\n\n $files = glob(\"$templatesPath/*.$templatesExtension\");\n\n foreach ($files as $file) {\n $templateName = basename($file, \".$templatesExtension\");\n\n $template = $modx->getObject('modTemplate', ['templatename' => $templateName]);\n if (empty($template)) {\n $template = $modx->newObject('modTemplate', ['templatename' => $templateName]);\n }\n\n $template->set('content', file_get_contents($file));\n\n if (!$template->save()) {\n throw new Exception(\"Failed to save template $templateName.\");\n }\n }\n\n $cm = $modx->getCacheManager();\n $cm->refresh();\n \n} catch (Throwable $ex) {\n die($ex->getMessage());\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9282831/" ]
74,573,236
<p>How do you pass props to the the page.jsx of layout? (NEXT 13)</p> <pre><code>//app/blog/layout.jsx export default function RootLayout({ children }) { return ( &lt;div&gt; &lt;Navbar /&gt; &lt;Sidebar /&gt; {/*How do I pass any props from this root layout to this {children} that Im getting from page.jsx*/} {children} &lt;/div&gt; ); } </code></pre> <p>Basically, How do you pass a prop to a function prop (Next. JS 13)?</p>
[ { "answer_id": 74573344, "author": "Mayank Gupta", "author_id": 17691526, "author_profile": "https://Stackoverflow.com/users/17691526", "pm_score": 0, "selected": false, "text": "<Navbar children = {children} />\n" }, { "answer_id": 74584771, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 3, "selected": true, "text": "Rootlayout console.log(props) export default function RootLayout(props) {\n console.log(\"props in layout\",props)\n return (\n <div>\n {props.children}\n </div>\n );}\n props in layout {\n children: {\n '$$typeof': Symbol(react.element),\n type: {\n '$$typeof': Symbol(react.module.reference),\n filepath: '/home/tesla//node_modules/next/dist/client/components/layout-router.js',\n name: '',\n async: false\n },\n key: null,\n ref: null,\n props: {\n parallelRouterKey: 'children',\n segmentPath: [Array],\n error: undefined,\n errorStyles: undefined,\n loading: undefined,\n loadingStyles: undefined,\n hasLoading: false,\n template: [Object],\n templateStyles: undefined,\n notFound: [Object],\n notFoundStyles: undefined,\n childProp: [Object],\n rootLayoutIncluded: true\n },\n _owner: null,\n _store: {}\n },\n // THIS IS HOW WE PASS PROPS\n params: {}\n}\n params props.params.newProp = \"testing\";\n page.js const Page = (props) => {\n console.log(\"props in page\", props);\n return ()}\n params page.tsx params searchParams searchParams params" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19644223/" ]
74,573,238
<p>I've got a problem with a program which finds all substring in a given string. I've tried to make variable &quot;found&quot;, which would contain a position of a previously found substring and then start searching from the position. Here's my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; int main() { string str; string str1; cin &gt;&gt; str &gt;&gt; str1; int i = 0; int found = -1; while(found &lt; str1.size()){ found = str1.find(str, found + 1); cout&lt;&lt;str1.find(str, found)&lt;&lt;endl; i++; } } </code></pre> <p>for the following input: &quot;ab aabb&quot; it doesn't print anything. Could you help?</p>
[ { "answer_id": 74574443, "author": "Monogeon", "author_id": 17861720, "author_profile": "https://Stackoverflow.com/users/17861720", "pm_score": 1, "selected": false, "text": "substr(a,b) find(a) #include <iostream>\n#include <string> //not really needed here. string should already be usable\n \nusing namespace std; //in small programs is ok but with big programs this could lead to problems with using specific things that could have the same names in std and other library. So its best to avoid this and or any other using namespace you use.\n \nint main()\n{\n string str; // you should really name your variables better\n string str1;\n\n cin >> str >> str1; // your variable names are unreadable at first glance\n int i = 0; // iterator cool but why is it needed if you're just using find()\n int found = -1; // good variable although the name \"pos\" would probably be better as to further explain to the programmer what the variable does\n while(found < str1.size()){ //not really sure what you were going for here\n found = str1.find(str, found + 1); // this could have been your while logic above instead\n cout<<str1.find(str, found)<<endl; // this finds the exact same position again using more resources. your variable found stores the position so doing cout << found << here would be better\n i++; \n }\n}\n #include <iostream>\n#include <string>\n \nusing namespace std;\n \nint main()\n{\n string str;\n string str1;\n\n cin >> str >> str1; //you input ab as str and abbb as str1\n int i = 0;\n int found = -1;\n while(found < str1.size()){ //first iteration is while(-1 < 4)\n found = str1.find(str, found + 1); //<-- find needs just 1 parameter. heres your problem\n cout<<str1.find(str, found)<<endl;\n i++;\n }\n}\n #include <iostream>\n\nusing namespace std;\n\nint main()\n{\n string str;\n string str1;\n int pos;\n cin >> str >> str1;\n for(int i = 0; i < str1.size(); i++) // this or could be while(true)\n {\n pos = str1.substr(i).find(str); //finds your string in the rest of the line\n if (pos == -1)\n {\n //NOT FOUND\n break; //stops\n }\n else\n {\n //FOUND\n cout << pos + i << endl; //pos is position in the cut out after adding i we get global position\n i += pos; // skip characters after we found them to NOT be found again\n }\n }\n}\n\n" }, { "answer_id": 74576180, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 1, "selected": false, "text": "starts_with #include <iostream>\n#include <string>\n\nint main() {\n std::string str{ \"ab aab\" };\n std::string sub{ \"ab\" };\n int count{};\n size_t last_index{ str.size() > sub.size() ? str.size() - sub.size() : 0 };\n for (size_t i{0}; i <= last_index; ++i) {\n if (str.substr(i).starts_with(sub)) {\n count++;\n }\n }\n std::cout << count;\n}\n\n// Outputs: 2\n" }, { "answer_id": 74593021, "author": "qqqqq", "author_id": 1135237, "author_profile": "https://Stackoverflow.com/users/1135237", "pm_score": 0, "selected": false, "text": "int find_substr(string substr, string str) {\n\n int postion = 0;\n auto beginning = str.c_str();\n int i = 0;\n char* p = (char *)beginning;\n while (p && '\\0'!=p)\n {\n p = strstr(p, substr.c_str());\n if (!p)\n break;\n cout << \"A substring is at index:\" << p - beginning << \"\\n\";\n p++;\n };\n return 0;\n}\n\n\nvoid test()\n{\n string substr, str;\n {\n substr = \"ab\"; str = \"aabb\";\n cout << \"Finding \" << substr << \" in \" << str << \"\\n\";\n find_substr(substr, str);\n cout << \"\\n\";\n }\n {\n substr = \"ab\"; str = \"abab\";\n find_substr(substr, str);\n cout << \"\\n\";\n }\n {\n substr = \"a\"; str = \"11111111111111111111111a\";\n find_substr(substr, str);\n cout << \"\\n\";\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16208262/" ]
74,573,266
<p>I have a malformed JSON with <code>&quot;key&quot;:True</code> instead of <code>&quot;key&quot;:true</code></p> <p>So I'm getting the following error :</p> <pre><code>&quot;com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'True': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')&quot; </code></pre> <p>I can solve my problem with <code>replace(&quot;True&quot;, &quot;true&quot;)</code> on string before to parsing the JSON string.</p> <p>But I would like to do this automatically with handling error or something like that. Using Jackson config. Is it possible?</p> <pre class="lang-java prettyprint-override"><code>private static final ObjectMapper jsonMapper; </code></pre> <pre class="lang-java prettyprint-override"><code>JsonFactory f = JsonFactory.builder() .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS) .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES) .build(); jsonMapper = JsonMapper.builder(f).build(); JsonNode res = jsonMapper.readTree(content) </code></pre> <p>JSON-sample:</p> <pre class="lang-none prettyprint-override"><code>{ ..., &quot;key&quot; : True, ... } </code></pre>
[ { "answer_id": 74576186, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "boolean true false null false boolean boolean boolean" }, { "answer_id": 74594378, "author": "scndry", "author_id": 20617206, "author_profile": "https://Stackoverflow.com/users/20617206", "pm_score": 0, "selected": false, "text": "ObjectMapper" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10974166/" ]
74,573,267
<p>I'm trying to write a function that will backfill columns in a dataframe adhearing to a condition. The upfill should only be done within groups. I am however having a hard time getting the group object to ungroup. I have tried reset_index as in the example bellow but that gets an AttributeError.</p> <p>Accessing the original df through <code>result.obj</code> doesn't lead to the updated value because there is no inplace for the groupby bfill.</p> <pre><code>def upfill(df:DataFrameGroupBy)-&gt;DataFrameGroupBy: for column in df.obj.columns: if column.startswith(&quot;x&quot;): df[column].bfill(axis=&quot;rows&quot;, inplace=True) return df </code></pre> <p>Assigning the dataframe column in the function doesn't work because groupbyobject doesn't support item assingment.</p> <pre><code>def upfill(df:DataFrameGroupBy)-&gt;DataFrameGroupBy: for column in df.obj.columns: if column.startswith(&quot;x&quot;): df[column] = df[column].bfill() return df </code></pre> <p>The test I'm trying to get to pass:</p> <pre><code> def test_upfill(): df = DataFrame({ &quot;id&quot;:[1,2,3,4,5], &quot;group&quot;:[1,2,2,3,3], &quot;x_value&quot;: [4,4,None,None,5], }) grouped_df = df.groupby(&quot;group&quot;) result = upfill(grouped_df) result.reset_index() assert result[&quot;x_value&quot;].equals(Series([4,4,None,5,5])) </code></pre>
[ { "answer_id": 74576186, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "boolean true false null false boolean boolean boolean" }, { "answer_id": 74594378, "author": "scndry", "author_id": 20617206, "author_profile": "https://Stackoverflow.com/users/20617206", "pm_score": 0, "selected": false, "text": "ObjectMapper" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320619/" ]
74,573,268
<p>I am running an Ubuntu self-hosted build agent for Azure DevOps in Container Instances and container outputs only: <code>Determining matching Azure Pipelines agent.</code> and that's it.</p> <p>It has PAT with full access to whole organization, given agent pool really exists and the URL is correct as well. THe only thing that comes to my mind is that I see our URL as <code>https://XXXX.visualstudio.com/</code> but I gave the agent url like <code>https://dev.azure.com/XXX</code> which still seems to be working when used in the browser.</p> <p>How to solve this, please?</p>
[ { "answer_id": 74576186, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 1, "selected": false, "text": "boolean true false null false boolean boolean boolean" }, { "answer_id": 74594378, "author": "scndry", "author_id": 20617206, "author_profile": "https://Stackoverflow.com/users/20617206", "pm_score": 0, "selected": false, "text": "ObjectMapper" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6156353/" ]
74,573,270
<p>I've been using <code>caret::createDataPartition()</code> in order to split the data in a stratified way. Now I'm trying another approach that I found here in stack, which is <code>splitstackshape::stratified()</code>, and the reason I'm intrested in this is that it allows to stratifiy based on features that I choose manually, very handy.</p> <p>I have problem with splitting the data:</p> <pre><code>library(splitstackshape) set.seed(40) Train = stratified(Data, c('age','gender','treatment_1','treatment_2','cancers'), 0.75) </code></pre> <p>This produces the train set, but how do I get the test set? I didn't get it. I tired the <code>createDataPartition</code> way:</p> <pre><code>INDEX = stratified(Data, c('age','gender','treatment_1','treatment_2','cancers'), 0.75) Train = Data[INDEX , ] Test = Data[-INDEX ,] </code></pre> <p>But that doesn't work because <code>stratified</code> creates an actual train data, not an index.</p> <p>So how do I get the test data using this function? thanks!</p>
[ { "answer_id": 74573434, "author": "Len Greski", "author_id": 8471931, "author_profile": "https://Stackoverflow.com/users/8471931", "pm_score": 2, "selected": false, "text": "mtcars library(splitstackshape)\nset.seed(19108379) # for reproducibility\n\n# add a unique sequential ID to track rows in the sample, using mtcars\n\nmtcars$rowId <- 1:nrow(mtcars)\n\n# take a stratified sample by cyl\n\ntrain <- stratified(mtcars,\"cyl\",size = 0.6)\n\ntest <- mtcars[!(mtcars$rowId %in% train$rowId),]\n\nnrow(train) + nrow(test) # should add to 32 \n > nrow(train) + nrow(test) # should add to 32 \n[1] 32\n stratified() rowId > # list the rows included in the sample\n> train$rowId\n [1] 6 11 10 4 3 27 18 8 9 21 28 23 17 16 29 22 15 7 14\n> nrow(train)\n[1] 19\n > # illustrate the selection criteria used to extract rows not in the training data\n> !(mtcars$rowId %in% train$rowId)\n [1] TRUE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE\n[15] FALSE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE\n[29] FALSE TRUE TRUE TRUE\n> \n > # count rows to be included in test data frame \n> sum(!(mtcars$rowId %in% train$rowId)) # should add to 13\n[1] 13\n stratified() bothSets # alternative answer: use the package's bothSets argument\nset.seed(19108379)\nsampleData <- stratified(mtcars,\"cyl\",size = 0.6,bothSets = TRUE)\n\n# compare rowIds in test vs. SAMP2 data frames\nsampleData$SAMP2$rowId\ntest$rowId\n > sampleData$SAMP2$rowId\n [1] 1 2 5 12 13 19 20 24 25 26 30 31 32\n> test$rowId\n [1] 1 2 5 12 13 19 20 24 25 26 30 31 32\n> \n caret::createDataPartition() training test stratified()" }, { "answer_id": 74573503, "author": "user2974951", "author_id": 2974951, "author_profile": "https://Stackoverflow.com/users/2974951", "pm_score": 1, "selected": false, "text": "library(splitstackshape)\nstratified(mtcars,\"am\",size=0.75,bothSets=T)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17945841/" ]
74,573,309
<p>i have 2 array of objects like so,</p> <pre><code>const initial = [ { id: '1', value: '1', }, { id: '2', value: '2', } ] const current = [ { id: '1', value: '3', }, { id: '2', value: '2', }, ] </code></pre> <p>these two arrays are almost the same.</p> <p>i want to check if the current array has value different than the initial array with same id.</p> <p>so if atleast one of the object in current has value different from the initial value then it should return true. if not false.</p> <p>so in above example current array with id 1 has value 3 which is different from initial value with id '1'.</p> <p>i was trying to do something like below,</p> <pre><code>const output = current.filter(item =&gt; some(initial, {id: item.id, value: !item.value})) </code></pre> <p>but this doesnt seem to be the right way. could someone help me with this. thanks.</p>
[ { "answer_id": 74573434, "author": "Len Greski", "author_id": 8471931, "author_profile": "https://Stackoverflow.com/users/8471931", "pm_score": 2, "selected": false, "text": "mtcars library(splitstackshape)\nset.seed(19108379) # for reproducibility\n\n# add a unique sequential ID to track rows in the sample, using mtcars\n\nmtcars$rowId <- 1:nrow(mtcars)\n\n# take a stratified sample by cyl\n\ntrain <- stratified(mtcars,\"cyl\",size = 0.6)\n\ntest <- mtcars[!(mtcars$rowId %in% train$rowId),]\n\nnrow(train) + nrow(test) # should add to 32 \n > nrow(train) + nrow(test) # should add to 32 \n[1] 32\n stratified() rowId > # list the rows included in the sample\n> train$rowId\n [1] 6 11 10 4 3 27 18 8 9 21 28 23 17 16 29 22 15 7 14\n> nrow(train)\n[1] 19\n > # illustrate the selection criteria used to extract rows not in the training data\n> !(mtcars$rowId %in% train$rowId)\n [1] TRUE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE\n[15] FALSE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE\n[29] FALSE TRUE TRUE TRUE\n> \n > # count rows to be included in test data frame \n> sum(!(mtcars$rowId %in% train$rowId)) # should add to 13\n[1] 13\n stratified() bothSets # alternative answer: use the package's bothSets argument\nset.seed(19108379)\nsampleData <- stratified(mtcars,\"cyl\",size = 0.6,bothSets = TRUE)\n\n# compare rowIds in test vs. SAMP2 data frames\nsampleData$SAMP2$rowId\ntest$rowId\n > sampleData$SAMP2$rowId\n [1] 1 2 5 12 13 19 20 24 25 26 30 31 32\n> test$rowId\n [1] 1 2 5 12 13 19 20 24 25 26 30 31 32\n> \n caret::createDataPartition() training test stratified()" }, { "answer_id": 74573503, "author": "user2974951", "author_id": 2974951, "author_profile": "https://Stackoverflow.com/users/2974951", "pm_score": 1, "selected": false, "text": "library(splitstackshape)\nstratified(mtcars,\"am\",size=0.75,bothSets=T)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234477/" ]
74,573,310
<p>I want to manipulate with background-color of Component &quot;MyBox&quot; using Tabs. Background of Component has to be filled with the color, named in Tabs. One condition: you're not allowed to delete <code>@bind-ActivePanelIndex=&quot;activeIndex&quot;</code> from code (it's used for other purposes). I have a method &quot;SetColor&quot;, but I don't understand how to run it. I'll be thankfull for any help.</p> <p>Index.razor</p> <pre><code>&lt;MudTabs Elevation=&quot;0&quot; Outlined=&quot;true&quot; @bind-ActivePanelIndex=&quot;activeIndex&quot;&gt; &lt;MudTabPanel Text=&quot;Red&quot;&gt;&lt;/MudTabPanel&gt; &lt;MudTabPanel Text=&quot;Blue&quot;&gt;&lt;/MudTabPanel&gt; &lt;/MudTabs&gt; &lt;MyBox colorBox=&quot;@colorMe&quot;/&gt; @code { int activeIndex = 0; string colorMe = &quot;&quot;; void SetColor() { if(activeIndex == 0) { colorMe = &quot;red&quot;; } else if(activeIndex == 1) { colorMe = &quot;blue&quot;; } } } </code></pre> <p>MyBox.razor</p> <pre><code>&lt;MudItem Style=&quot;@($&quot;background-color:{colorBox}; padding:10px; border:1px solid black&quot;)&quot;&gt; Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum sit praesentium eos impedit. Est delectus non fugiat perferendis, quos et quis fugit iusto laborum esse voluptates sequi harum quo ab. &lt;/MudItem&gt; @code { [Parameter] public string colorBox {get; set;} } </code></pre>
[ { "answer_id": 74573434, "author": "Len Greski", "author_id": 8471931, "author_profile": "https://Stackoverflow.com/users/8471931", "pm_score": 2, "selected": false, "text": "mtcars library(splitstackshape)\nset.seed(19108379) # for reproducibility\n\n# add a unique sequential ID to track rows in the sample, using mtcars\n\nmtcars$rowId <- 1:nrow(mtcars)\n\n# take a stratified sample by cyl\n\ntrain <- stratified(mtcars,\"cyl\",size = 0.6)\n\ntest <- mtcars[!(mtcars$rowId %in% train$rowId),]\n\nnrow(train) + nrow(test) # should add to 32 \n > nrow(train) + nrow(test) # should add to 32 \n[1] 32\n stratified() rowId > # list the rows included in the sample\n> train$rowId\n [1] 6 11 10 4 3 27 18 8 9 21 28 23 17 16 29 22 15 7 14\n> nrow(train)\n[1] 19\n > # illustrate the selection criteria used to extract rows not in the training data\n> !(mtcars$rowId %in% train$rowId)\n [1] TRUE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE\n[15] FALSE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE\n[29] FALSE TRUE TRUE TRUE\n> \n > # count rows to be included in test data frame \n> sum(!(mtcars$rowId %in% train$rowId)) # should add to 13\n[1] 13\n stratified() bothSets # alternative answer: use the package's bothSets argument\nset.seed(19108379)\nsampleData <- stratified(mtcars,\"cyl\",size = 0.6,bothSets = TRUE)\n\n# compare rowIds in test vs. SAMP2 data frames\nsampleData$SAMP2$rowId\ntest$rowId\n > sampleData$SAMP2$rowId\n [1] 1 2 5 12 13 19 20 24 25 26 30 31 32\n> test$rowId\n [1] 1 2 5 12 13 19 20 24 25 26 30 31 32\n> \n caret::createDataPartition() training test stratified()" }, { "answer_id": 74573503, "author": "user2974951", "author_id": 2974951, "author_profile": "https://Stackoverflow.com/users/2974951", "pm_score": 1, "selected": false, "text": "library(splitstackshape)\nstratified(mtcars,\"am\",size=0.75,bothSets=T)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19248032/" ]
74,573,319
<p>I want to do fscanf on a .txt file, here's how it looks</p> <pre><code>7 6 [1,2]=&quot;english&quot; [1,4]=&quot;linear&quot; [2,4]=&quot;calculus&quot; [3,1]=&quot;pe&quot; [3,3]=&quot;Programming&quot; </code></pre> <p>I want to take only the 2 numbers in the brackets, the first is day, and the second is session, and I also want to take the string subject</p> <p>Here's the whole code</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; int main(){ FILE *inputFile, *outputFile; int day; int session; char subject[15]; inputFile = fopen(&quot;Schedule.txt&quot;, &quot;r&quot;); if (inputFile == NULL) { puts(&quot;File Schedule.txt Open Error.&quot;); } fscanf(inputFile, &quot;%d %d %s&quot;, &amp;day, &amp;session, subject); printf(&quot;%d&quot;, day); fclose(inputFile); return 0; } </code></pre> <p>Apparently the fscanf does not work the way i want it to.</p> <p>The expected output is storing the numbers to the variables I have assigned</p> <p>What actually happened is it only printed out '7'</p>
[ { "answer_id": 74573486, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 1, "selected": false, "text": "sscanf #include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#define LINEBUFSIZE 500\n\nint main(){\n FILE *inputFile;\n \n char line[LINEBUFSIZE];\n \n inputFile = fopen(\"Schedule.txt\", \"r\");\n if (inputFile == NULL) {\n puts(\"File Schedule.txt Open Error.\");\n }\n\n while (fgets(line, LINEBUFSIZE, inputFile)) {\n int day;\n int session;\n char subject[15];\n int r;\n // %14s because char subject[15] (14 char + null)\n r = sscanf(line, \"[%d,%d]=%14s\", &day, &session, subject);\n if (r != 3)\n // Could not read 3 elements\n continue;\n printf(\"%d %d %s\\n\", day, session, subject);\n }\n\n return 0;\n\n}\n" }, { "answer_id": 74576026, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 1, "selected": true, "text": "\"7 6\\n\" fscanf() fgets() char buf[100];\nif (fgets(buf, sizeof buf, inputFile)) {\n // Parse input like <[1,2]=\"english\"\\n>\n int day;\n int session;\n char subject[15];\n int n = 0;\n sscanf(buf, \" [%d ,%d ] = \\\"%14[^\\\"]\\\" %n\",\n &day, &session, subject, &n);\n bool Success = n > 0 && buf[n] == '\\0';\n ...\n n buf[n] \" \" \"[\" [ \"%d\" int \",\" , \"]\" ] \"\\\"\" \"%14[^\\\"]\" \"%n\" int" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20388275/" ]
74,573,336
<p>my component livewire</p> <pre><code> public $images = []; public function rules() { return [ 'images.*.name' =&gt; 'required|max:255', ]; } </code></pre> <p>blade.php</p> <pre><code> &lt;div id=&quot;images&quot;&gt; @foreach($images as $index =&gt; $image) &lt;div class=&quot;card&quot; wire:key=&quot;image-field-{{$images[$index]['id']}}&quot;&gt; &lt;img src=&quot;{{$images[$index]-&gt;original_url}}&quot; class=&quot;card-img-top&quot; alt=&quot;{{$images[$index]-&gt;name}}&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;item-{{$index}}-name&quot; id=&quot;item.{{$index}}.name&quot; wire:model=&quot;images.{{$index}}.name&quot; /&gt; &lt;div class=&quot;card-footer&quot;&gt; &lt;button wire:click=&quot;changeImageName({{$image['id']}},{{$images[$index]['name']}})&quot;&gt;Update&lt;/button&gt; {{$images[$index]-&gt;name}} &lt;/div&gt; &lt;/div&gt; @endforeach &lt;/div&gt; </code></pre> <p>so wire:model=&quot;images.{{$index}}.name&quot; not working, not changing after typing</p> <p>and update will error</p> <p>Uncaught SyntaxError: identifier starts immediately after numeric literal</p>
[ { "answer_id": 74573486, "author": "jvx8ss", "author_id": 11107859, "author_profile": "https://Stackoverflow.com/users/11107859", "pm_score": 1, "selected": false, "text": "sscanf #include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#define LINEBUFSIZE 500\n\nint main(){\n FILE *inputFile;\n \n char line[LINEBUFSIZE];\n \n inputFile = fopen(\"Schedule.txt\", \"r\");\n if (inputFile == NULL) {\n puts(\"File Schedule.txt Open Error.\");\n }\n\n while (fgets(line, LINEBUFSIZE, inputFile)) {\n int day;\n int session;\n char subject[15];\n int r;\n // %14s because char subject[15] (14 char + null)\n r = sscanf(line, \"[%d,%d]=%14s\", &day, &session, subject);\n if (r != 3)\n // Could not read 3 elements\n continue;\n printf(\"%d %d %s\\n\", day, session, subject);\n }\n\n return 0;\n\n}\n" }, { "answer_id": 74576026, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 1, "selected": true, "text": "\"7 6\\n\" fscanf() fgets() char buf[100];\nif (fgets(buf, sizeof buf, inputFile)) {\n // Parse input like <[1,2]=\"english\"\\n>\n int day;\n int session;\n char subject[15];\n int n = 0;\n sscanf(buf, \" [%d ,%d ] = \\\"%14[^\\\"]\\\" %n\",\n &day, &session, subject, &n);\n bool Success = n > 0 && buf[n] == '\\0';\n ...\n n buf[n] \" \" \"[\" [ \"%d\" int \",\" , \"]\" ] \"\\\"\" \"%14[^\\\"]\" \"%n\" int" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5717984/" ]
74,573,345
<p>This line of code is getting document count from firestore database it works fine when i call the variable inside the function but outside its undefine.</p> <pre><code> var LM35TOTALRES; // I WANT TO STORE HERE db.collection(&quot;LM35&quot;).get().then(function(querySnapshot) { LM35TOTALRES = querySnapshot.size //DATA THAT I WANT console.log(LM35TOTALRES); // THIS IS WORKING }); console.log(LM35TOTALRES); // NOT WORKING </code></pre>
[ { "answer_id": 74573389, "author": "N Hilmi", "author_id": 11943184, "author_profile": "https://Stackoverflow.com/users/11943184", "pm_score": -1, "selected": false, "text": "let LM35TOTALRES;\n" }, { "answer_id": 74573436, "author": "Ali Osman", "author_id": 10760289, "author_profile": "https://Stackoverflow.com/users/10760289", "pm_score": 2, "selected": false, "text": "const LM35TOTALRES = await (db.collection(\"LM35\").get()).size" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20599594/" ]
74,573,346
<p>So I already did this basically 1 year ago but I forgot how to do it, and its not working now though. Here is the <a href="https://blog.logrocket.com/adding-emojis-react-app/#:%7E:text=To%20include%20it%20in%20your,use%20React%2016.8%20or%20higher!" rel="nofollow noreferrer">LINK</a> basically I have a like a <strong>&quot;smile emoji icon button&quot;</strong> and then when I click it I will pass the emoji in my text but it giving me now an error <code>undefined</code>. In the link you can see that it has same thing here.</p> <pre><code>import './App.scss'; import React, { useState } from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import Picker from 'emoji-picker-react'; function App() { const [chosenEmoji, setChosenEmoji] = useState(null); const onEmojiClick = (event, emojiObject) =&gt; { setChosenEmoji(emojiObject); console.log(emojiObject) }; return ( &lt;div className=&quot;App&quot;&gt; &lt;header className=&quot;App-header&quot;&gt; {/* {isLogin &amp;&amp; user ? &lt;LoginTrue/&gt; : &lt;LoginFalse/&gt;} */} {chosenEmoji ? ( &lt;span&gt;You chose: {chosenEmoji.emoji}&lt;/span&gt; ) : ( &lt;span&gt;No emoji Chosen&lt;/span&gt; )} &lt;Picker onEmojiClick={onEmojiClick} /&gt; &lt;/header&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>but the new update of <code>emoji-picker-react</code> did get different...Is anyone can give me an idea of it? or is there another source of importing emojis..I don't want to use <code>Input-emoji-react</code> its too ugly.</p>
[ { "answer_id": 74573686, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 2, "selected": true, "text": "emoji-picker-react MaterialUI <div className=\"chat_footer\">\n {!emojiPicker ? (\n <InsertEmoticonIcon onClick={() => setEmojiPicker((prev) => !prev)} />\n ) : (\n <>\n <InsertEmoticonIcon\n onClick={() => setEmojiPicker((prev) => !prev)}\n />\n <EmojiPicker\n searchDisabled=\"true\"\n previewConfig={{ showPreview: false }}\n emojiStyle=\"google\"\n onEmojiClick={(e) => setInput((input) => input + e.emoji)}\n height={400}\n width=\"40%\"\n />\n </>\n )}\n InsertEmoticonIcon import" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17900052/" ]
74,573,355
<p>I am trying to generate a list of 12 random weights for a stock portfolio in order to determine how the portfolio would have performed in the past given different weights assigned to each stock. The sum of the weights must of course be 1 and there is an additional restriction: each stock must have a weight between 1/24 and 1/4.</p> <p>Although I am able to generate random numbers such that they all fall within the interval by using random.uniform(), as well as guarantee their sum is 1 by dividing each weighting by the sum of the weightings, I'm finding that</p> <p>a) each subsequent array of weightings is very similar. I am rarely getting values for weightings that are near the upper boundary of 1/4</p> <p>b) random.seed() does not seem to be working properly, whether I put it in the randweight() function or at the beginning of the for loop. I'm confused as to why because I thought that generating a random seed value would make my array of weights unique for each iteration. Currently, it's cyclical, with a period of 3.</p> <p>The following is my code:</p> <pre><code># boundaries on weightings n = 12 min_weight = (1/(2*n)) max_weight = 25 / 100 def rand_weight(e): random.seed() return e + np.random.uniform(min_weight, max_weight) for i in range(100): weights = np.empty(12) while not (np.all(weights &gt; min_weight) and np.all(weights &lt; max_weight)): weights = np.array(list(map(rand_weight, weights))) weights /= np.sum(weights) </code></pre> <p>I have already tried scattering the weights by changing the min_weight and max_weight inside the for loop so that rand_weight generates newer values, but this makes the runtime really slow because the &quot;not&quot; condition in the while loop takes longer to evaluate to false (since the probability of all the numbers being in the range decreases).</p>
[ { "answer_id": 74573686, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 2, "selected": true, "text": "emoji-picker-react MaterialUI <div className=\"chat_footer\">\n {!emojiPicker ? (\n <InsertEmoticonIcon onClick={() => setEmojiPicker((prev) => !prev)} />\n ) : (\n <>\n <InsertEmoticonIcon\n onClick={() => setEmojiPicker((prev) => !prev)}\n />\n <EmojiPicker\n searchDisabled=\"true\"\n previewConfig={{ showPreview: false }}\n emojiStyle=\"google\"\n onEmojiClick={(e) => setInput((input) => input + e.emoji)}\n height={400}\n width=\"40%\"\n />\n </>\n )}\n InsertEmoticonIcon import" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19567665/" ]
74,573,372
<p>I am trying to create a view using the following source code:</p> <pre><code>SQLiteDatabase db = mManagerDbHelper.getWritableDatabase(); String sql = &quot;SELECT * FROM users WHERE name = ?&quot;; String[] selectionArgs = new String[] {&quot;Bob&quot;}; db.execSQL(&quot;CREATE VIEW bob_user AS &quot; + sql, selectionArgs); </code></pre> <p>However, this code always returns this error:</p> <blockquote> <p>android.database.sqlite.SQLiteException: parameters are not allowed in views (code 1)</p> </blockquote> <p>How do I use the <code>bindArgs</code> parameter of <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#execSQL(java.lang.String,%20java.lang.Object%5B%5D)" rel="nofollow noreferrer">execSQL(String, Object[])</a> method?</p>
[ { "answer_id": 74573373, "author": "user1506104", "author_id": 1506104, "author_profile": "https://Stackoverflow.com/users/1506104", "pm_score": 0, "selected": false, "text": "SQLiteDatabase db = mManagerDbHelper.getWritableDatabase();\n\nString sql = \"SELECT * FROM users WHERE name = 'Bob'\";\ndb.execSQL(\"CREATE VIEW bob_user AS \" + sql);\n" }, { "answer_id": 74580966, "author": "MikeT", "author_id": 4744514, "author_profile": "https://Stackoverflow.com/users/4744514", "pm_score": 1, "selected": false, "text": "DROP VIEW IF EXISTS a_user;\nDROP TABLE IF EXISTS users;\nDROP TABLE IF EXISTS mimicbind;\nCREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);\nINSERT INTO users (name) VALUES('bob'),('mary'),('fred'),('sue');\nCREATE TABLE IF NOT EXISTS mimicbind (mimicname TEXT PRIMARY KEY, value TEXT);\nINSERT INTO mimicbind VALUES('a_user','bob');\nCREATE VIEW a_user AS SELECT * FROM users WHERE name = (SELECT value FROM mimicbind WHERE mimicname = 'a_user');\n\nSELECT * FROM a_user;\nUPDATE mimicbind SET value = 'sue' WHERE mimicname = 'a_user';\nSELECT * FROM a_user;\nDROP VIEW IF EXISTS a_user;\nDROP TABLE IF EXISTS users;\nDROP TABLE IF EXISTS mimicbind;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506104/" ]
74,573,382
<p>I'm trying to get min and max values from query</p> <pre><code>SELECT TABLE_NAME , COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME IN ('TABLE_A','TABLE_B') and DATA_TYPE='NUMBER' AND (DATA_PRECISION IS NULL OR DATA_SCALE IS NULL) </code></pre> <p>here what I get so far, but it shows nothing:</p> <pre><code>BEGIN DBMS_OUTPUT.ENABLE (buffer_size =&gt; NULL); END; declare l_max number; begin for &quot;CUR_R&quot; in (SELECT TABLE_NAME , COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME IN ('TABLE_A','TABLE_B') and DATA_TYPE='NUMBER' AND (DATA_PRECISION IS NULL OR DATA_SCALE IS NULL) ) loop execute immediate 'select max(' || &quot;CUR_R&quot;.&quot;COLUMN_NAME&quot; ||') from ' || &quot;CUR_R&quot;.&quot;TABLE_NAME&quot; into l_max; dbms_output.put_line(&quot;CUR_R&quot;.&quot;TABLE_NAME&quot; ||'.'|| &quot;CUR_R&quot;.&quot;COLUMN_NAME&quot; ||' -&gt; max value = '|| l_max); end loop; end; </code></pre> <p>maybe i missing something? also, I'm not an admin, just have grants to select to particular tables can't create procedure or temp table</p> <p>I expect result of this structure:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>owner</th> <th>column_name</th> <th>max_value</th> <th>min_value</th> </tr> </thead> </table> </div> <p>maybe I am missing something? also, I'm not an admin, just have grants to select to particular tables can't create procedure or temp table</p>
[ { "answer_id": 74573484, "author": "Roland", "author_id": 1845672, "author_profile": "https://Stackoverflow.com/users/1845672", "pm_score": -1, "selected": false, "text": "select max(x), min(x)\nfrom t\n" }, { "answer_id": 74573623, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 0, "selected": false, "text": "user_tab_columns SQL> SET SERVEROUTPUT ON\nSQL>\nSQL> DECLARE\n 2 l_max NUMBER;\n 3 BEGIN\n 4 FOR cur_r IN (SELECT table_name, column_name\n 5 FROM user_tab_columns\n 6 WHERE table_name IN ('EMP', 'DEPT')\n 7 AND data_type = 'NUMBER'\n 8 -- AND ( data_precision IS NULL\n 9 -- OR data_scale IS NULL)\n 10 AND 1 = 1)\n 11 LOOP\n 12 EXECUTE IMMEDIATE 'select max('\n 13 || cur_r.column_name\n 14 || ') from '\n 15 || cur_r.table_name\n 16 INTO l_max;\n 17\n 18 DBMS_OUTPUT.put_line (\n 19 cur_r.table_name\n 20 || '.'\n 21 || cur_r.column_name\n 22 || ' -> max value = '\n 23 || l_max);\n 24 END LOOP;\n 25 END;\n 26 /\nDEPT.DEPTNO -> max value = 40\nEMP.EMPNO -> max value = 7934\nEMP.MGR -> max value = 7902\nEMP.SAL -> max value = 5000\nEMP.COMM -> max value = 1400\nEMP.DEPTNO -> max value = 30\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74573770, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "NUMBER NUMBER(*,X) NUMBER(X) NUMBER(X,Y) DATA_PRECISION IS NULL OR DATA_SCALE IS NULL CREATE TABLE table_a (\n value1 NUMBER,\n value2 NUMBER(*,0),\n value3 NUMBER(10),\n value4 NUMBER(5,2)\n);\n\nINSERT INTO table_a\nSELECT LEVEL, 2*LEVEL, 3*LEVEL, 4*LEVEL FROM DUAL CONNECT BY LEVEL <= 5;\n\nCREATE TABLE table_b (\n value1 NUMBER,\n value2 NUMBER(*,0),\n value3 NUMBER(10),\n value4 NUMBER(5,2)\n);\n\nINSERT INTO table_b\nSELECT LEVEL + 5, 2*LEVEL - 2, 3*LEVEL + 3, 1/LEVEL FROM DUAL CONNECT BY LEVEL <= 4;\n DECLARE\n l_min number;\n l_max number;\nBEGIN\n DBMS_OUTPUT.ENABLE();\n\n FOR c IN (\n SELECT OWNER,\n TABLE_NAME,\n COLUMN_NAME\n FROM ALL_TAB_COLUMNS\n WHERE TABLE_NAME IN ('TABLE_A','TABLE_B')\n AND DATA_TYPE='NUMBER'\n AND (DATA_PRECISION IS NULL OR DATA_SCALE IS NULL)\n )\n LOOP\n EXECUTE IMMEDIATE\n 'select min(\"' || c.column_name ||'\"),\n max(\"' || c.column_name ||'\")\n from \"' || c.owner || '\".\"' || c.table_name || '\"'\n INTO l_min, l_max;\n DBMS_OUTPUT.PUT_LINE(\n c.owner || '.' || c.table_name ||'.'|| c.column_name\n || ' -> min_value = ' || l_min\n || ', max value = '|| l_max\n );\n END LOOP;\nEND;\n/\n FIDDLE_TNHCDFVJDASVYWAHROPU.TABLE_A.VALUE1 -> min_value = 1, max value = 5\nFIDDLE_TNHCDFVJDASVYWAHROPU.TABLE_A.VALUE2 -> min_value = 2, max value = 10\nFIDDLE_TNHCDFVJDASVYWAHROPU.TABLE_B.VALUE1 -> min_value = 6, max value = 9\nFIDDLE_TNHCDFVJDASVYWAHROPU.TABLE_B.VALUE2 -> min_value = 0, max value = 6\n value3 value4" }, { "answer_id": 74573894, "author": "Marmite Bomber", "author_id": 4808122, "author_profile": "https://Stackoverflow.com/users/4808122", "pm_score": 1, "selected": true, "text": "min max CLOB SELECT \n'select '''||TABLE_NAME||''' TABLE_NAME ,''' || COLUMN_NAME||''' COLUMN_NAME,'|| ' max('|| COLUMN_NAME ||\n') max_value,' || ' min('|| COLUMN_NAME ||') min_value from '|| TABLE_NAME ||\ncase when row_number() over (order by table_name desc, column_name desc) != 1 then ' UNION ALL' end as sql_text\nFROM ALL_TAB_COLUMNS\nWHERE TABLE_NAME IN ('TABLE_A','TABLE_B')\nand DATA_TYPE='NUMBER'\nAND (DATA_PRECISION IS NULL OR DATA_SCALE IS NULL)\norder by table_name, column_name;\n select 'TABLE_A' TABLE_NAME ,'X' COLUMN_NAME, max(X) max_value, min(X) min_value from TABLE_A UNION ALL\nselect 'TABLE_A' TABLE_NAME ,'Y' COLUMN_NAME, max(Y) max_value, min(Y) min_value from TABLE_A UNION ALL\nselect 'TABLE_B' TABLE_NAME ,'X' COLUMN_NAME, max(X) max_value, min(X) min_value from TABLE_B UNION ALL\nselect 'TABLE_B' TABLE_NAME ,'Y' COLUMN_NAME, max(Y) max_value, min(Y) min_value from TABLE_B\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20599563/" ]
74,573,386
<p>I am appending a column in data-frame column name = 'Name' which is a string comprising of a few different columns concatenation.</p> <p>Now, I want to replace certain characters with certain values. Lets say</p> <p>&amp; -&gt; and &lt; -&gt; less than</p> <blockquote> <p>-&gt; greater than ' -&gt; this is an apostrophe &quot; -&gt; this is a double quotation</p> </blockquote> <p>Now how can I efficiently apply this regex on entire column. Also, Can I put it in certain function as I need to apply the same in 4 other columns as well.</p> <p>I tried this</p> <pre><code>df = pd.DataFrame({'A': ['bat&lt;', 'foo&gt;', 'bait&amp;'], 'B': ['abc', 'bar', 'xyz']}) df.replace({'A': r'&lt;','A':r'&gt;','A':r'&amp;'}, {'A': 'less than','A': 'greater than','A': 'and'}, regex=True, inplace=True) </code></pre> <p>I am expecting this</p> <pre><code> A B 0 batless than abc 1 foogreater than bar 2 baitand xyz </code></pre> <p>But this happened.</p> <pre><code> A B 0 bat&lt; abc 1 foo&gt; bar 2 baitand xyz </code></pre>
[ { "answer_id": 74573445, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 2, "selected": false, "text": "pandas.DataFrame.apply pandas.Series.str.replace regex = r'(<|>|&)'\n\ndf_new = df.apply(lambda x: x.str.replace(regex, lambda m: 'less than' if m.group(1) == '<' else 'greater than' if m.group(1) == '>' else 'and', regex=True))\n\n[Out]:\n\n A B\n0 batless than abc\n1 foogreater than bar\n2 baitand xyz\n" }, { "answer_id": 74573526, "author": "skybaks", "author_id": 19788693, "author_profile": "https://Stackoverflow.com/users/19788693", "pm_score": 2, "selected": true, "text": "A df.replace({'A': {r'<': 'less than', r'>': 'greater than', r'&': 'and'}}, regex=True, inplace=True)\n" }, { "answer_id": 74573681, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 0, "selected": false, "text": "mapping = {'<': 'less than', '>': 'greater than', '&': 'and'}\n df.apply(lambda col: col.str.replace(\"|\".join(mapping), \n lambda match: mapping.get(match.group())))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12953677/" ]
74,573,393
<p>I've got a map:</p> <pre><code>const dataMap: { KEY01: { label: 'some string', details: {....}}, KEY02: { label: 'some other string', details: {...}}, } const copy = { title: dataMap[keyVariable].label, info: dataMap[keyVariable].details, } </code></pre> <p>so the <code>keyVariable</code> comes from a 3rd party package (with its own types). There are more possible keys 'KEY03', 'KEY04', ..., etc.</p> <p>Now I am 100% that in my app only KEY01 and KEY02 are possible. The problem is that TS complains that the other possible keyVariable options are not included in my dataMap.</p> <pre><code>Property 'KEY03' does not exist on type { here insert the shape of my dataMap } </code></pre> <p>I'd rather not do ts-ignore or ts-expect-error. I could add the missing possible keyVariables (KEY03, KEY05) to my dataMap but that's pointless and would include lots of unnecessary code. Is there a way (! - but I don't know where to put it) to tell TS, that I know the keyVariable can have many more values (other than 'KEY01' and 'KEY02') but I know they are not possible in this context?</p>
[ { "answer_id": 74573702, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 3, "selected": true, "text": "declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable].label, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n info: dataMap[keyVariable].details, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n};\n\n keyVariable declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nfunction isDataMapKey (value: unknown): value is keyof typeof dataMap {\n return value as keyof typeof dataMap in dataMap;\n}\n\nif (isDataMapKey(keyVariable)) {\n const copy = {\n title: dataMap[keyVariable].label, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n info: dataMap[keyVariable].details, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n };\n}\nelse {\n // Handle the case that your assumption is wrong, for example:\n throw new Error('Oops, I was wrong');\n}\n\n declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable as keyof typeof dataMap].label, // OK\n info: dataMap[keyVariable as keyof typeof dataMap].details, // OK\n};\n\n" }, { "answer_id": 74573925, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function assertIsValidKey(key: string): asserts key is keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n}\n\nassertIsValidKey(keyVariable);\ndataMap[keyVariable].label;\n function castValidKey(key: string): keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n return key as keyof typeof dataMap;\n}\n\ndataMap[castValidKey(keyVariable)].label;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1945363/" ]
74,573,398
<p>I am currently struggling with woo-commerce and the availability status on product pages. I am trying to display various texts (translated) on the product pages, whether the product is available and how many we have, then whether it is unavailable, whether it is available to backorder, and what I can't do is display the message that the product is in stock with disabled managing stock. There are unlimited products. But it still shows me only &quot;available places&quot;.</p> <p>There is my function.</p> <pre><code>add_filter( 'woocommerce_get_availability', 'product_stock_quantity_single', 1, 2); function product_stock_quantity_single( $availability, $_product ) { global $product; $stock = $product-&gt;get_stock_quantity(); if ( $_product-&gt;is_in_stock() ) $availability['availability'] = __('Text front ' . $stock . ' text behind', 'woocommerce'); if ( !$_product-&gt;is_in_stock() ) $availability['availability'] = __('Out of stock text', 'woocommerce'); if ( $_product-&gt;is_on_backorder() ) $availability['availability'] = __( 'On backorder text', 'woocommerce' ); return $availability; } </code></pre> <p>I've tried many different combinations and frankly, it doesn't work for me. Thanks for all the advice and help. I tried what was in the topic which was merged with mine. It's a different topic about different things I want to achieve. I need a product with disabled managing stock but still available (something like infinite stock)</p>
[ { "answer_id": 74573702, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 3, "selected": true, "text": "declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable].label, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n info: dataMap[keyVariable].details, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n};\n\n keyVariable declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nfunction isDataMapKey (value: unknown): value is keyof typeof dataMap {\n return value as keyof typeof dataMap in dataMap;\n}\n\nif (isDataMapKey(keyVariable)) {\n const copy = {\n title: dataMap[keyVariable].label, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n info: dataMap[keyVariable].details, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n };\n}\nelse {\n // Handle the case that your assumption is wrong, for example:\n throw new Error('Oops, I was wrong');\n}\n\n declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable as keyof typeof dataMap].label, // OK\n info: dataMap[keyVariable as keyof typeof dataMap].details, // OK\n};\n\n" }, { "answer_id": 74573925, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function assertIsValidKey(key: string): asserts key is keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n}\n\nassertIsValidKey(keyVariable);\ndataMap[keyVariable].label;\n function castValidKey(key: string): keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n return key as keyof typeof dataMap;\n}\n\ndataMap[castValidKey(keyVariable)].label;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20572835/" ]
74,573,411
<p><strong>I removed some code so it will become easier to read</strong></p> <blockquote> <p>But everthing is imported correctly and working correctly but i can't figure out this error <strong>i got this error but i saw a tutorial and even reactRouter site have same way but it's not working with my code</strong></p> </blockquote> <p><strong>I wan't to change Route when Enter key is pressed in keyboard</strong></p> <blockquote> <p>This is the app.js file</p> </blockquote> <pre><code>function App() { return ( &lt;div&gt; &lt;div key=&quot;navbar&quot; className=&quot;navbar&quot;&gt; &lt;Navbar /&gt; &lt;/div&gt; &lt;div key=&quot;search-box&quot; className=&quot;search-box&quot;&gt; &lt;SearchBar carddata={cards}/&gt; &lt;/div&gt; &lt;div&gt; &lt;Cards key=&quot;cards&quot; carddata={cards} /&gt; &lt;/div&gt; &lt;/div&gt; ); } export default App; </code></pre> <blockquote> <p>This is the file where All Routes are happening when useNavigate changes the Route it should Open the Route That i wan't to open ('/SearchResult')</p> </blockquote> <pre><code> const Cards = ({ carddata: cardComponent }) =&gt; { return ( //This is the file that should open when the useNavigate change Route to &quot;/SearchResult&quot; &lt;Route path=&quot;/SearchResult&quot; element={&lt;SearchResPage /&gt;}&gt;&lt;/Route&gt; &lt;/Routes&gt; &lt;div className=&quot;right-section&quot;&gt; &lt;RightCard cardData={cardComponent} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Router&gt; ); }; export default Cards; </code></pre> <p><strong>This is the file that will change the Route using useNavigate and the file i wan't to open is searchResPage (code will be below this Code)</strong></p> <pre><code> import { useNavigate } from &quot;react-router-dom&quot;; const SearchBar = ({ carddata}) =&gt; { const navigate=useNavigate(); //it's the function called onKeyDown function searchResult(e) { if (e.key === &quot;Enter&quot;) { if (e.target.value === &quot;&quot;) return; //it for changing the Route navigate('/SearchResult') //it for filtering the result passed from props and the show them carddata.filter((result) =&gt; { if (`${result.heading}`.toLowerCase().match(e.target.value)) { console.log(result) } }); } } return ( &lt;div className=&quot;flex&quot;&gt; &lt;input onKeyDown={searchResult} type=&quot;text&quot; &gt;&lt;/input&gt; &lt;/div&gt; ); }; export default SearchBar; </code></pre> <blockquote> <p>or is there any other way to change the Route when enter key is pressed without refreshing the page i was able to find out this option i don't know why it's not working</p> </blockquote>
[ { "answer_id": 74573702, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 3, "selected": true, "text": "declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable].label, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n info: dataMap[keyVariable].details, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n};\n\n keyVariable declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nfunction isDataMapKey (value: unknown): value is keyof typeof dataMap {\n return value as keyof typeof dataMap in dataMap;\n}\n\nif (isDataMapKey(keyVariable)) {\n const copy = {\n title: dataMap[keyVariable].label, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n info: dataMap[keyVariable].details, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n };\n}\nelse {\n // Handle the case that your assumption is wrong, for example:\n throw new Error('Oops, I was wrong');\n}\n\n declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable as keyof typeof dataMap].label, // OK\n info: dataMap[keyVariable as keyof typeof dataMap].details, // OK\n};\n\n" }, { "answer_id": 74573925, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function assertIsValidKey(key: string): asserts key is keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n}\n\nassertIsValidKey(keyVariable);\ndataMap[keyVariable].label;\n function castValidKey(key: string): keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n return key as keyof typeof dataMap;\n}\n\ndataMap[castValidKey(keyVariable)].label;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20393875/" ]
74,573,412
<p>let's assume an input string has given, for a particular character like '$' you want to add dynamically in the text field , so I want to find the index of a current character like <strong>'$'</strong> then it's not working properly like initially if I give '$'in any position, its reflection the position, example if I give <strong>'random text$'</strong> it returns <strong>index 11</strong> but if you type '$'in between text like <strong>'random $text$'</strong> then <strong>it should return 7, but it returns 12</strong>,<strong>so by achieving 7 I need to give extra space like 'random $ text$'</strong>, <strong>so dynamically how to get the index position of a current character($), whether It's added in first, middle, last of the text</strong></p> <pre><code> let string = &quot;random $text$&quot;; let newArray = string.split(&quot;&quot;); let store = string.length % 2 !== 0 ? newArray.findLastIndex((x) =&gt; x === &quot;$&quot;) : newArray.findIndex((x) =&gt; x === &quot;$&quot;); console.log(store); </code></pre>
[ { "answer_id": 74573702, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 3, "selected": true, "text": "declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable].label, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n info: dataMap[keyVariable].details, /*\n ~~~~~~~~~~~\n Property 'KEY03' does not exist on type... */\n};\n\n keyVariable declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nfunction isDataMapKey (value: unknown): value is keyof typeof dataMap {\n return value as keyof typeof dataMap in dataMap;\n}\n\nif (isDataMapKey(keyVariable)) {\n const copy = {\n title: dataMap[keyVariable].label, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n info: dataMap[keyVariable].details, // OK\n //^? const keyVariable: \"KEY01\" | \"KEY02\"\n };\n}\nelse {\n // Handle the case that your assumption is wrong, for example:\n throw new Error('Oops, I was wrong');\n}\n\n declare const keyVariable: 'KEY01' | 'KEY02' | 'KEY03' | 'KEY04' /* etc. */;\n\nconst dataMap = {\n KEY01: { label: 'some string', details: {someKey: 'some value'}},\n KEY02: { label: 'some other string', details: {someKey: 'some value'}},\n};\n\nconst copy = {\n title: dataMap[keyVariable as keyof typeof dataMap].label, // OK\n info: dataMap[keyVariable as keyof typeof dataMap].details, // OK\n};\n\n" }, { "answer_id": 74573925, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function assertIsValidKey(key: string): asserts key is keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n}\n\nassertIsValidKey(keyVariable);\ndataMap[keyVariable].label;\n function castValidKey(key: string): keyof typeof dataMap {\n if (!(key in dataMap)) throw new Error('Invalid key');\n return key as keyof typeof dataMap;\n}\n\ndataMap[castValidKey(keyVariable)].label;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17227120/" ]
74,573,439
<p>I want to change the paragraph text when the next arrow is clicked. I can change it once but if I want to change it to a third option, it's not working. Can someone explain why this is the case?</p> <p>I have made a Codepen with the issue: <a href="https://codepen.io/harrync92/pen/WNyJybM" rel="nofollow noreferrer">Conditional statement problem</a></p> <pre><code>&lt;div class=&quot;tutNavigation&quot;&gt; &lt;div class=&quot;flexNavigation&quot;&gt; &lt;div id=&quot;back&quot;&gt;&lt;i id=&quot;arrow-left&quot;&gt;&lt;-&lt;/i&gt;&lt;/div&gt; &lt;div class=&quot;tutorialText&quot;&gt; &lt;p&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;next&quot;&gt;&lt;i id=&quot;arrow-right&quot;&gt;-&gt;&lt;/i&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>let text = document.querySelector(&quot;p&quot;); text.textContent = &quot;text1&quot;; let backLeft = document.getElementById(&quot;back&quot;); let arrowBack = document.getElementById(&quot;arrow-left&quot;); let nextRight = document.getElementById(&quot;next&quot;); let arrowNext = document.getElementById(&quot;arrow-right&quot;); if ((text.textContent = &quot;text1&quot;)) { arrowBack.classList.add(&quot;hidden&quot;); nextRight.addEventListener(&quot;click&quot;, () =&gt; { arrowBack.classList.remove(&quot;hidden&quot;); text.textContent = &quot;text2&quot;; }); backLeft.addEventListener(&quot;click&quot;, () =&gt; { arrowBack.classList.add(&quot;hidden&quot;); text.textContent = &quot;text1&quot;; }); } else if ((text.textcontent = &quot;text2&quot;)) { nextRight.addEventListener(&quot;click&quot;, () =&gt; { text.textContent = &quot;text3&quot;; }); backLeft.addEventListener(&quot;click&quot;, () =&gt; { text.textContent = &quot;text2&quot;; }); } else { text.textContent = &quot;none&quot;; } </code></pre>
[ { "answer_id": 74573647, "author": "exphoenee", "author_id": 13804256, "author_profile": "https://Stackoverflow.com/users/13804256", "pm_score": 0, "selected": false, "text": "const text = document.querySelector(\"p\");\nconst possiblities = [\"text1\", \"text2\", \"text3\", \"text4\"];\nlet index = 0;\n\nlet backLeft = document.getElementById(\"back\");\nlet arrowBack = document.getElementById(\"arrow-left\");\n\nlet nextRight = document.getElementById(\"next\");\nlet arrowNext = document.getElementById(\"arrow-right\");\n\nconst checkAndHideArrows = () => {\n if (index >= possiblities.length - 1) {\n nextRight.classList.add(\"hidden\");\n arrowNext.classList.add(\"hidden\");\n console.log(\"hide right\");\n } else {\n nextRight.classList.remove(\"hidden\")\n arrowNext.classList.remove(\"hidden\")\n console.log(\"show right\");\n }\n \n if (index <= 0) {\n backLeft.classList.add(\"hidden\");\n arrowBack.classList.add(\"hidden\");\n console.log(\"hide left\");\n } else {\n backLeft.classList.remove(\"hidden\");\n arrowBack.classList.remove(\"hidden\");\n console.log(\"show left\");\n }\n}\n\nconst setText = () => {\n text.textContent = possiblities[index];\n console.log(possiblities[index]);\n checkAndHideArrows();\n};\n\nconst next = () => {\n if (index++ >= possiblities.length - 1) {\n index = possiblities.length - 1;\n }\n};\n\nconst prev = () => {\n if (index-- <= 0) {\n index = 0;\n }\n};\n\nsetText();\n\nnextRight.addEventListener(\"click\", () => {\n next();\n console.log(index);\n setText();\n});\n\nbackLeft.addEventListener(\"click\", () => {\n prev();\n console.log(index);\n setText();\n}); .hidden {\n color: transparent;\n} <div class=\"tutNavigation\">\n <div class=\"flexNavigation\">\n <div id=\"back\"><i id=\"arrow-left\"><-</i></div>\n <div class=\"tutorialText\">\n <p></p>\n </div>\n <div id=\"next\"><i id=\"arrow-right\">-></i></div>\n </div>\n</div>" }, { "answer_id": 74573711, "author": "Nishant", "author_id": 4632239, "author_profile": "https://Stackoverflow.com/users/4632239", "pm_score": 2, "selected": true, "text": "let text = document.querySelector(\"p\");\ntext.textContent = \"text1\";\n\nlet backLeft = document.getElementById(\"back\");\nlet arrowBack = document.getElementById(\"arrow-left\");\n\nlet nextRight = document.getElementById(\"next\");\nlet arrowNext = document.getElementById(\"arrow-right\");\n\narrowBack.classList.add(\"hidden\");\n\nnextRight.addEventListener(\"click\", () => {\n arrowBack.classList.remove(\"hidden\");\n if (text.textContent === \"text1\") {\n text.textContent = \"text2\";\n } else if (text.textContent === \"text2\") {\n text.textContent = \"text3\";\n }\n});\n\nbackLeft.addEventListener(\"click\", () => {\n\n if (text.textContent === \"text3\") {\n text.textContent = \"text2\";\n } else if (text.textContent === \"text2\") {\n text.textContent = \"text1\";\n arrowBack.classList.add(\"hidden\");\n\n }\n}); body {\n background-color: black;\n}\n\n.tutNavigation {\n display: flex;\n padding: 3rem 2rem;\n box-shadow: 0px -4px 4px rgba(0, 0, 0, 0.25);\n flex-direction: column;\n flex-wrap: nowrap;\n align-content: center;\n gap: 1rem;\n}\n\n.tutNavigation.flexNavigation {\n display: flex;\n align-items: center;\n justify-content: space-evenly;\n flex-wrap: nowrap;\n gap: 1rem;\n flex-direction: row;\n}\n\n.flexNavigation.tutorialText {\n text-align: center;\n max-width: 500px;\n}\n\np {\n color: white;\n font-size: 16px;\n line-height: 1.3rem;\n}\n\n#back,\n#next {\n padding: 1rem;\n cursor: pointer;\n border-radius: 5px;\n width: 72px;\n}\n\ni {\n font-size: 40px;\n color: white;\n}\n\n.hidden {\n display: none;\n} <div class=\"tutNavigation\">\n <div class=\"flexNavigation\">\n <div id=\"back\"><i id=\"arrow-left\"><-</i></div>\n <div class=\"tutorialText\">\n <p></p>\n </div>\n <div id=\"next\"><i id=\"arrow-right\">-></i></div>\n </div>\n</div>" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17736785/" ]
74,573,468
<p>I have the following table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Day</th> <th>Category</th> <th>Count</th> </tr> </thead> <tbody> <tr> <td>D1</td> <td>A</td> <td>10</td> </tr> <tr> <td>D1</td> <td>B</td> <td>20</td> </tr> <tr> <td>D2</td> <td>A</td> <td>8</td> </tr> <tr> <td>D2</td> <td>B</td> <td>10</td> </tr> <tr> <td>D3</td> <td>A</td> <td>6</td> </tr> <tr> <td>D3</td> <td>B</td> <td>5</td> </tr> </tbody> </table> </div> <p>I'm trying to create a percentage column by dividing the values in the third column (Count) by the value for D1 across all categories in the second column (Category; in this case 10 and 20 for A and B respectively). This should output something like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Day</th> <th>Category</th> <th>Count</th> <th>Pct</th> </tr> </thead> <tbody> <tr> <td>D1</td> <td>A</td> <td>10</td> <td>100%</td> </tr> <tr> <td>D1</td> <td>B</td> <td>20</td> <td>100%</td> </tr> <tr> <td>D2</td> <td>A</td> <td>8</td> <td>80%</td> </tr> <tr> <td>D2</td> <td>B</td> <td>10</td> <td>50%</td> </tr> <tr> <td>D3</td> <td>A</td> <td>6</td> <td>60%</td> </tr> <tr> <td>D3</td> <td>B</td> <td>5</td> <td>25%</td> </tr> </tbody> </table> </div> <p>The furthest I got is the code below, but I can't figure out how to do the division by category.</p> <pre><code> SELECT day, category, count, count/(SELECT count FROM table WHERE day = 'D1')*100 AS pct FROM table ORDER BY 1 ) </code></pre>
[ { "answer_id": 74573836, "author": "lonfo", "author_id": 20042380, "author_profile": "https://Stackoverflow.com/users/20042380", "pm_score": 0, "selected": false, "text": "SELECT\n day,\n category,\n count,\n count/(SELECT count \n FROM table as sub \n WHERE day = 'D1' \n AND sub.category = main.category)*100 AS pct\n FROM \n table as main\n" }, { "answer_id": 74573944, "author": "Asgar", "author_id": 8035759, "author_profile": "https://Stackoverflow.com/users/8035759", "pm_score": 0, "selected": false, "text": "SELECT \nmain.*, \nROUND(((main.Count/d2.Count)*100),2) \nFROM\n(SELECT * FROM day_table d1) main\n JOIN day_table d2 ON d2.Category=main.Category AND d2.Day='D1' \n ORDER BY \n main.Day, \n main.Category\n" }, { "answer_id": 74576683, "author": "nnichols", "author_id": 1191247, "author_profile": "https://Stackoverflow.com/users/1191247", "pm_score": 1, "selected": false, "text": "SELECT\n `t1`.*,\n ROUND((`t1`.`count` / `t2`.`count`) * 100) `pct`\nFROM `table` `t1`\nJOIN `table` `t2`\n ON `t1`.`category` = `t2`.`category`\n AND `t2`.`day` = 'D1'\nORDER BY 1, 2;\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20599587/" ]
74,573,518
<p>Say i have elements</p> <pre><code> &lt;div id=&quot;Test1&quot;&gt; &lt;p text=&quot;One&quot;&gt; One &lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;Test2&quot;&gt; &lt;p text=&quot;One&quot;&gt; One &lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;Test3&quot;&gt; &lt;p text=&quot;One&quot;&gt; One &lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;Test4&quot;&gt; &lt;p text=&quot;One&quot;&gt; One &lt;/p&gt; &lt;/div&gt; </code></pre> <p>Now i want to locate the text element dynamically based on div id. Something like</p> <pre class="lang-js prettyprint-override"><code>getText(divID){ cy.get(&quot;divID&quot;).find(&quot;vasErrorMessage&quot;). } </code></pre> <p>How to write code in cypress for this. Here I will send divID dynamically and divID can be Test2 or Test1</p>
[ { "answer_id": 74575459, "author": "Bouke", "author_id": 6864688, "author_profile": "https://Stackoverflow.com/users/6864688", "pm_score": 2, "selected": false, "text": "getElementById(id) {\n const selector = \"#\" + id;\n return cy.get(selector);\n}\n" }, { "answer_id": 74578108, "author": "jjhelguero", "author_id": 17917809, "author_profile": "https://Stackoverflow.com/users/17917809", "pm_score": 0, "selected": false, "text": ".contains() // gets third id=Test3 element with 'One' text\ncy.contains('#Test3', 'One')\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8069046/" ]
74,573,540
<pre><code>class AAA { int m_Int; public: AAA() : m_Int{12} {} }; class BBB { int m_Int1; public: BBB() : m_Int1{12} {} }; class CCC : public AAA, public BBB {}; AAA a; BBB b; CCC c{ a, b }; </code></pre> <p>Why can object <code>c</code> be constructed by parent class object?</p> <p>I tried to find out which standard support this syntax. I wrote the code with Visual Studio, and I found C++ 14 does not support this, but C++17 does. I also found that the construct process of <code>c</code> call <code>AAA</code> and <code>BBB</code>'s copy constructor.</p> <p>I want to know what the syntax is and where to find the item.</p>
[ { "answer_id": 74575459, "author": "Bouke", "author_id": 6864688, "author_profile": "https://Stackoverflow.com/users/6864688", "pm_score": 2, "selected": false, "text": "getElementById(id) {\n const selector = \"#\" + id;\n return cy.get(selector);\n}\n" }, { "answer_id": 74578108, "author": "jjhelguero", "author_id": 17917809, "author_profile": "https://Stackoverflow.com/users/17917809", "pm_score": 0, "selected": false, "text": ".contains() // gets third id=Test3 element with 'One' text\ncy.contains('#Test3', 'One')\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16889740/" ]
74,573,541
<p>I am trying to put the white container at the bottom of the page how I can do that, I don't want to give a padding top because this will affect other screens' sizes. Is there a way to put the whole white container at the bottom of the page it at the bottom of the screen?</p> <p>here is an image :<a href="https://i.stack.imgur.com/nBJHS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nBJHS.jpg" alt="enter image description here" /></a></p> <p>here is my code : `</p> <pre><code>class SignIn extends StatelessWidget { const SignIn({Key? key}) : super(key: key); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; return Scaffold( backgroundColor: Colors.green, body: SafeArea( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(top: 20), child: Stack( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( &quot;Text&quot;, textAlign: TextAlign.center, style: TextStyle(fontSize: 20), ), ], ), ], ), ), Stack( children: [ Container( margin: EdgeInsets.only(top: 50), padding: EdgeInsets.only( top: height * 0.05, left: 10, right: 20, ), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30), ), ), child: Column( children: [ Row( children: [ Padding( padding: const EdgeInsets.only(left: 20), child: Text( &quot;Sign In&quot;, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25, ), ), ), ], ), SizedBox( height: 25, ), SizedBox( height: 20, ), Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(&quot;End&quot;), ], ), ), ], ), ), Padding( padding: const EdgeInsets.only(top: 20), child: Align( alignment: Alignment.center, child: Padding( padding: const EdgeInsets.only(right: 50), child: Container( height: 60, width: 60, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30), color: Colors.green, ), ), ), ), ), ], ), ], ), ), ), ); } } </code></pre> <p>`</p>
[ { "answer_id": 74573862, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "Column(\n children: [\n mainAxisAlignment: MainAxisAlignment.end\n Row(\n children: [\n Padding(\n padding: const EdgeInsets.only(left: 20),\n child: Text(\n \"Sign In\",\n style: TextStyle(\n fontWeight: FontWeight.bold,\n fontSize: 25,\n ),\n ),\n ),\n ],\n ),\n" }, { "answer_id": 74574082, "author": "Kemal Yilmaz", "author_id": 20518203, "author_profile": "https://Stackoverflow.com/users/20518203", "pm_score": 1, "selected": false, "text": " @override\n Widget build(BuildContext context) {\n double width = MediaQuery.of(context).size.width;\n double height = MediaQuery.of(context).size.height;\n return Scaffold(\n backgroundColor: Colors.green,\n body: SafeArea(\n child: Column(\n children: [\n Expanded(\n child: Column(mainAxisAlignment: MainAxisAlignment.end,\n children: [\n Padding(\n padding: EdgeInsets.only(top: 20),\n child: Stack(\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Text(\n \"Text\",\n textAlign: TextAlign.center,\n style: TextStyle(fontSize: 20),\n ),\n ],\n ),\n ],\n ),\n ),\n Stack(\n children: [\n Container(\n margin: EdgeInsets.only(top: 50),\n padding: EdgeInsets.only(\n top: height * 0.05,\n left: 10,\n right: 20,\n ),\n decoration: BoxDecoration(\n color: Colors.white,\n borderRadius: BorderRadius.only(\n topLeft: Radius.circular(30),\n topRight: Radius.circular(30),\n ),\n ),\n child: Column(\n children: [\n Row(\n children: [\n Padding(\n padding: const EdgeInsets.only(left: 20),\n child: Text(\n \"Sign In\",\n style: TextStyle(\n fontWeight: FontWeight.bold,\n fontSize: 25,\n ),\n ),\n ),\n ],\n ),\n SizedBox(\n height: 25,\n ),\n SizedBox(\n height: 20,\n ),\n Container(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Text(\"End\"),\n ],\n ),\n ),\n ],\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(top: 20),\n child: Align(\n alignment: Alignment.center,\n child: Padding(\n padding: const EdgeInsets.only(right: 50),\n child: Container(\n height: 60,\n width: 60,\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(30),\n color: Colors.green,\n ),\n ),\n ),\n ),\n ),\n ],\n ),\n ],\n ),\n ),\n ],\n ),\n ),\n );\n }\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20059879/" ]
74,573,581
<p>I have an n x m array and a function 'switch(A,J)' that takes array (A) and integer(J) input and outputs an array of size n x m. I wish to split my n x m array into arrays of dimension c x c and apply the function with a fixed J to each c x c array and output the resulting array.c may not be a factor of n or m. Would anyone know how to execute this please.</p> <p>I have tried np.block to split the array and apply to each individual block but then i had trouble reconstructing the matrix. I also attempted to use the slice indexing and store the values in a new array but the issue is my function outputs complex values so these are all discarded when i try and append the new array,</p>
[ { "answer_id": 74573862, "author": "Abdalla Tawfik", "author_id": 11601491, "author_profile": "https://Stackoverflow.com/users/11601491", "pm_score": 0, "selected": false, "text": "Column(\n children: [\n mainAxisAlignment: MainAxisAlignment.end\n Row(\n children: [\n Padding(\n padding: const EdgeInsets.only(left: 20),\n child: Text(\n \"Sign In\",\n style: TextStyle(\n fontWeight: FontWeight.bold,\n fontSize: 25,\n ),\n ),\n ),\n ],\n ),\n" }, { "answer_id": 74574082, "author": "Kemal Yilmaz", "author_id": 20518203, "author_profile": "https://Stackoverflow.com/users/20518203", "pm_score": 1, "selected": false, "text": " @override\n Widget build(BuildContext context) {\n double width = MediaQuery.of(context).size.width;\n double height = MediaQuery.of(context).size.height;\n return Scaffold(\n backgroundColor: Colors.green,\n body: SafeArea(\n child: Column(\n children: [\n Expanded(\n child: Column(mainAxisAlignment: MainAxisAlignment.end,\n children: [\n Padding(\n padding: EdgeInsets.only(top: 20),\n child: Stack(\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Text(\n \"Text\",\n textAlign: TextAlign.center,\n style: TextStyle(fontSize: 20),\n ),\n ],\n ),\n ],\n ),\n ),\n Stack(\n children: [\n Container(\n margin: EdgeInsets.only(top: 50),\n padding: EdgeInsets.only(\n top: height * 0.05,\n left: 10,\n right: 20,\n ),\n decoration: BoxDecoration(\n color: Colors.white,\n borderRadius: BorderRadius.only(\n topLeft: Radius.circular(30),\n topRight: Radius.circular(30),\n ),\n ),\n child: Column(\n children: [\n Row(\n children: [\n Padding(\n padding: const EdgeInsets.only(left: 20),\n child: Text(\n \"Sign In\",\n style: TextStyle(\n fontWeight: FontWeight.bold,\n fontSize: 25,\n ),\n ),\n ),\n ],\n ),\n SizedBox(\n height: 25,\n ),\n SizedBox(\n height: 20,\n ),\n Container(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Text(\"End\"),\n ],\n ),\n ),\n ],\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(top: 20),\n child: Align(\n alignment: Alignment.center,\n child: Padding(\n padding: const EdgeInsets.only(right: 50),\n child: Container(\n height: 60,\n width: 60,\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(30),\n color: Colors.green,\n ),\n ),\n ),\n ),\n ),\n ],\n ),\n ],\n ),\n ),\n ],\n ),\n ),\n );\n }\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18850013/" ]
74,573,622
<p>Working on a demo I switched to using Combine, but just cannot seem to find a way to assign the values that I get from json decoding in sink to point to an array , below is my code , as you can see in the commented out code using URLSession it was much easier …thanks</p> <p>Currently I just see the default record</p> <pre><code>struct NewsItem: Decodable { let id: Int let title: String let strap: String let url: URL let main_image: URL let published_date: Date static let shared = NewsItem(id: 0, title: &quot;&quot;, strap: &quot;&quot;, url: URL(string: &quot;https://www.hackingwithswift.com/articles/239/wwdc21-wrap-up-and-recommended-talks&quot;)!, main_image: URL(string: &quot;https://www.hackingwithswift.com/resize/300/uploads/wwdc-21@2x.jpg&quot;)!, published_date: Date()) } struct CardView: View { @State private var news = [NewsItem]() @State private var request = Set&lt;AnyCancellable&gt;() var body: some View { List { ForEach(news, id:\.id) { news in Text(news.title) Text(&quot;\(news.published_date)&quot;) Link(&quot;Goto Link&quot;, destination: news.url) AsyncImage(url: news.main_image) .frame(width: 50, height: 50) } } .onAppear { Task { await fetchData() } } } func fetchData() async { let url = URL(string: &quot;https://www.hackingwithswift.com/samples/headlines.json&quot;)! // URLSession.shared.dataTask(with: url) { data, response, error in // if let error = error { // print(error.localizedDescription) // } else if let data = data { // let json = JSONDecoder() // // json.dateDecodingStrategy = .iso8601 // do { // let user = try json.decode([NewsItem].self, from: data) // news = user // } catch { // print(error.localizedDescription) // } // } // }.resume() URLSession.shared.dataTaskPublisher(for: url) .map(\.data) .decode(type: [NewsItem].self, decoder: JSONDecoder()) .replaceError(with: [NewsItem.shared]) .sink(receiveValue: { item in news = item }) .store(in: &amp;request) } } </code></pre>
[ { "answer_id": 74573904, "author": "burnsi", "author_id": 6950415, "author_profile": "https://Stackoverflow.com/users/6950415", "pm_score": 2, "selected": true, "text": "func fetchData() async {\n //create custom decoder and apply dateDecodingStrategy\n let decoder = JSONDecoder()\n decoder.dateDecodingStrategy = .iso8601\n let url = URL(string: \"https://www.hackingwithswift.com/samples/headlines.json\")!\n \n URLSession.shared.dataTaskPublisher(for: url)\n .map(\\.data)\n // use the custom decoder\n .decode(type: [NewsItem].self, decoder: decoder)\n // if an error occures at least print it\n .mapError({ error in\n print(error)\n return error\n })\n .replaceError(with: [NewsItem.shared])\n .sink(receiveValue: { item in\n news = item\n })\n .store(in: &request)\n}\n" }, { "answer_id": 74575702, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 0, "selected": false, "text": "ObservableObject assign @Published var .task" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3151281/" ]
74,573,656
<p>I am using FastAPI to upload a csv file, perform some modifications on it and then return it to the HTML page. I am using Jinja2 as the template engine and HTML in frontend.</p> <p>How can I upload the csv file using Jinja2 template, modify it and then return it to the client?</p> <h2>Python code</h2> <pre class="lang-py prettyprint-override"><code>from fastapi.templating import Jinja2Templates from fastapi import FastAPI, File, UploadFile, Request from io import BytesIO import pandas as pd import uvicorn app = FastAPI() templates = Jinja2Templates(directory=&quot;templates&quot;) @app.get(&quot;/&quot;) def form_post(request: Request): result = &quot;upload file&quot; return templates.TemplateResponse('home.html', context={'request': request, 'result': result}) @app.post(&quot;/&quot;) def upload(request: Request, file: UploadFile = File(...)): contents1 = file.file.read() buffer1 = BytesIO(contents1) test1 = pd.read_csv(buffer1) buffer1.close() file.file.close() test1 = dict(test1.values) return templates.TemplateResponse('home.html', context={'request': request, 'result': test1}) if __name__ == &quot;__main__&quot;: uvicorn.run(app) </code></pre> <h2>HTML code</h2> <pre class="lang-html prettyprint-override"><code>\&lt;!DOCTYPE html\&gt; \&lt;html lang=&quot;en&quot;\&gt; \&lt;head\&gt; \&lt;meta charset=&quot;UTF-8&quot;\&gt; \&lt;title\&gt;RUL_PREDICTION\&lt;/title\&gt; \&lt;/head\&gt; \&lt;body\&gt; \&lt;h1\&gt;RUL PREDICTION\&lt;/h1\&gt; \&lt;form method=&quot;post&quot;\&gt; \&lt;input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot;/\&gt; \&lt;button type=&quot;submit&quot;\&gt;upload\&lt;/button\&gt; \&lt;/form\&gt; \&lt;p\&gt;{{ result }}\&lt;/p\&gt; \&lt;/body\&gt; \&lt;/html\&gt; </code></pre>
[ { "answer_id": 74573882, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "@app.post(\"/\")\ndef upload(file: UploadFile):\n\n with open(\"temp.csv\", \"wb\") as f:\n for row in file.file:\n f.write(row)\n \n with open(\"temp.csv\", \"r\", encoding=\"utf-8\") as csv:\n # modifications\n \n\n return FileResponse(path=\"temp.csv\", filename=\"new.csv\", media_type=\"application/octet-stream\")\n" }, { "answer_id": 74588435, "author": "Chris", "author_id": 17865804, "author_profile": "https://Stackoverflow.com/users/17865804", "pm_score": 2, "selected": true, "text": "Id,name,age,height,weight\n1,Alice,20,62,120.6\n2,Freddie,21,74,190.6\n3,Bob,17,68,120.0\n from fastapi import FastAPI, File, UploadFile, Request, Response, HTTPException\nfrom fastapi.templating import Jinja2Templates\nfrom io import BytesIO\nimport pandas as pd\n\napp = FastAPI()\ntemplates = Jinja2Templates(directory='templates')\n\n@app.post('/upload')\ndef upload(file: UploadFile = File(...)):\n try:\n contents = file.file.read()\n buffer = BytesIO(contents) \n df = pd.read_csv(buffer)\n except:\n raise HTTPException(status_code=500, detail='Something went wrong')\n finally:\n buffer.close()\n file.file.close()\n\n # remove a column from the DataFrame\n df.drop('age', axis=1, inplace=True)\n \n headers = {'Content-Disposition': 'attachment; filename=\"modified_data.csv\"'}\n return Response(df.to_csv(), headers=headers, media_type='text/csv')\n \n\n@app.get('/')\ndef main(request: Request):\n return templates.TemplateResponse('index.html', {'request': request})\n <!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n </head>\n <body>\n <form method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\">\n <label for=\"csvFile\">Choose a CSV file</label>\n <input type=\"file\" id=\"csvFile\" name=\"file\" onchange=\"enableSubmitBtn();\"><br><br>\n <input type=\"submit\" id=\"submitBtn\" value=\"submit\" disabled>\n </form>\n <script>\n function enableSubmitBtn() {\n document.getElementById('submitBtn').removeAttribute(\"disabled\");\n }\n </script>\n </body>\n</html>\n pandas.DataFrame.to_html() classes to_html() class border border=0 to_html() # ... (rest of code is same as in Option 1)\n\n@app.post('/upload')\ndef upload(request: Request, file: UploadFile = File(...)):\n # ... (rest of code is same as in Option 1)\n\n context = {'request': request, 'table': df.to_html()}\n return templates.TemplateResponse('results.html', context)\n\n <!DOCTYPE html>\n<html>\n <body>{{ table | safe }}</body>\n</html>\n pandas.DataFrame.to_dict() # ... (rest of code is same as in Option 1)\n\n@app.post('/upload')\ndef upload(request: Request, file: UploadFile = File(...)):\n # ... (rest of code is same as in Option 1)\n\n context = {'request': request, 'data': df.to_dict(orient='records'), 'columns': df.columns.values}\n return templates.TemplateResponse('results.html', context)\n\n <!DOCTYPE html>\n<html>\n <body>\n <table style=\"width:50%\">\n <tr>\n {% for c in columns %}<td>{{ c }}</td>{% endfor %}\n </tr>\n {% for d in data %}\n <tr>\n {% for v in d.values() %}\n <td>{{ v }}</td>\n {% endfor %}\n <br>\n </tr>\n {% endfor %}\n </table>\n </body>\n</html>\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17158028/" ]
74,573,698
<p>I have a query</p> <pre><code> INSERT INTO FCC_CS_WL_SOURCE_REQUEST_ID_MAP ( &quot;N_WL_SOURCE_REQUEST_ID&quot;, &quot;V_SOURCE_REQUEST_ID&quot;, &quot;V_TARGET_KEY&quot;, &quot;V_TARGET_INDEXNAME&quot; ) SELECT MAP_SEQ_TEST.nextval, FCC_CUST_DIM.V_ALT_CUST_ID AS &quot;V_SOURCE_REQUEST_ID&quot;, FCC_CS_MATCHED_RESULT_BULK.V_TARGET_KEY , FCC_CS_MATCHED_RESULT_BULK.V_TARGET_INDEXNAME FROM FCC_CS_MATCHED_RESULT_BULK INNER JOIN FCC_CUST_DIM ON FCC_CS_MATCHED_RESULT_BULK.V_SOURCE_KEY =FCC_CUST_DIM.V_CUST_INTRL_ID AND FCC_CUST_DIM.F_LRI_FL ='Y' AND FCC_CUST_DIM.V_ALT_CUST_ID IS NOT NULL AND FCC_CS_MATCHED_RESULT_BULK.N_RUN_SKEY =290 </code></pre> <p>Here I need to prevent the insert into FCC_CS_WL_SOURCE_REQUEST_ID_MAP table if V_SOURCE_REQUEST_ID,V_TARGET_KEY,V_TARGET_INDEXNAME columns values is already available with same value which is going to be inserted</p> <p>How to modify this query to achieve that .?</p>
[ { "answer_id": 74573882, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "@app.post(\"/\")\ndef upload(file: UploadFile):\n\n with open(\"temp.csv\", \"wb\") as f:\n for row in file.file:\n f.write(row)\n \n with open(\"temp.csv\", \"r\", encoding=\"utf-8\") as csv:\n # modifications\n \n\n return FileResponse(path=\"temp.csv\", filename=\"new.csv\", media_type=\"application/octet-stream\")\n" }, { "answer_id": 74588435, "author": "Chris", "author_id": 17865804, "author_profile": "https://Stackoverflow.com/users/17865804", "pm_score": 2, "selected": true, "text": "Id,name,age,height,weight\n1,Alice,20,62,120.6\n2,Freddie,21,74,190.6\n3,Bob,17,68,120.0\n from fastapi import FastAPI, File, UploadFile, Request, Response, HTTPException\nfrom fastapi.templating import Jinja2Templates\nfrom io import BytesIO\nimport pandas as pd\n\napp = FastAPI()\ntemplates = Jinja2Templates(directory='templates')\n\n@app.post('/upload')\ndef upload(file: UploadFile = File(...)):\n try:\n contents = file.file.read()\n buffer = BytesIO(contents) \n df = pd.read_csv(buffer)\n except:\n raise HTTPException(status_code=500, detail='Something went wrong')\n finally:\n buffer.close()\n file.file.close()\n\n # remove a column from the DataFrame\n df.drop('age', axis=1, inplace=True)\n \n headers = {'Content-Disposition': 'attachment; filename=\"modified_data.csv\"'}\n return Response(df.to_csv(), headers=headers, media_type='text/csv')\n \n\n@app.get('/')\ndef main(request: Request):\n return templates.TemplateResponse('index.html', {'request': request})\n <!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n </head>\n <body>\n <form method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\">\n <label for=\"csvFile\">Choose a CSV file</label>\n <input type=\"file\" id=\"csvFile\" name=\"file\" onchange=\"enableSubmitBtn();\"><br><br>\n <input type=\"submit\" id=\"submitBtn\" value=\"submit\" disabled>\n </form>\n <script>\n function enableSubmitBtn() {\n document.getElementById('submitBtn').removeAttribute(\"disabled\");\n }\n </script>\n </body>\n</html>\n pandas.DataFrame.to_html() classes to_html() class border border=0 to_html() # ... (rest of code is same as in Option 1)\n\n@app.post('/upload')\ndef upload(request: Request, file: UploadFile = File(...)):\n # ... (rest of code is same as in Option 1)\n\n context = {'request': request, 'table': df.to_html()}\n return templates.TemplateResponse('results.html', context)\n\n <!DOCTYPE html>\n<html>\n <body>{{ table | safe }}</body>\n</html>\n pandas.DataFrame.to_dict() # ... (rest of code is same as in Option 1)\n\n@app.post('/upload')\ndef upload(request: Request, file: UploadFile = File(...)):\n # ... (rest of code is same as in Option 1)\n\n context = {'request': request, 'data': df.to_dict(orient='records'), 'columns': df.columns.values}\n return templates.TemplateResponse('results.html', context)\n\n <!DOCTYPE html>\n<html>\n <body>\n <table style=\"width:50%\">\n <tr>\n {% for c in columns %}<td>{{ c }}</td>{% endfor %}\n </tr>\n {% for d in data %}\n <tr>\n {% for v in d.values() %}\n <td>{{ v }}</td>\n {% endfor %}\n <br>\n </tr>\n {% endfor %}\n </table>\n </body>\n</html>\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2675190/" ]
74,573,751
<p>I need help with my Next.js project. I take the token in the cookie from the <code>serverSideProps</code> of each page and bring the profile information. The appearance of the profile information means that the user is logged in. I am using this code on every page. that didn't feel right. How will I check if the profile information exists in every query? And when is a protected route I need to redirect the user to the login page.</p> <pre class="lang-js prettyprint-override"><code>export async function getServerSideProps(context) { const token = await getToken(context); if (token) { const profile = await getProfile(token); if (profile) { return { props: { profile: profile.data.user, token, }, }; } //if user is not found redirect return { redirect: { destination: &quot;/&quot;, permanent: false, }, }; } return { props: {}, }; } </code></pre>
[ { "answer_id": 74574037, "author": "msabic22", "author_id": 8925990, "author_profile": "https://Stackoverflow.com/users/8925990", "pm_score": 0, "selected": false, "text": "getServerSideProps app.js" }, { "answer_id": 74650820, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 2, "selected": true, "text": "pages _middleware.js import { NextResponse } from \"next/server\";\n\n// we are not exporting by default\nexport async function middleware(req, ev) {\n \n const token = req ? req.cookies?.token : null;\n const profile = await getProfile(token);\n // if profile exists you want to continue. Also\n // maybe user sends request for log-in, and if a user wants to login, obviously it has no token\n const { pathname } = req.nextUrl;\n if (\n // whatever your api route for login is\n pathname.includes(\"/api/login\") || profile \n ) {\n return NextResponse.next();\n }\n\n \n if (!profile && pathname !== \"/login\") {\n // since you want to redirect the user to \"/\"\n return NextResponse.redirect(\"/\");\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19600004/" ]
74,573,773
<p>I have this code:</p> <pre><code>const database = client.db(&quot;Cluster0&quot;); const collection = database.collection(&quot;people&quot;); let data = { ...req.body} let doc = collection.updateOne( { id: req.body.id }, {$set: {}} ) </code></pre> <p>what I am trying to do is update the entire document with all the data passed from the backend. So there could be like 10 fields and if a user only updates 1 field, it will pass all 10 and update the document regardless and update all 10 fields.</p> <p>How can I do this?</p>
[ { "answer_id": 74574037, "author": "msabic22", "author_id": 8925990, "author_profile": "https://Stackoverflow.com/users/8925990", "pm_score": 0, "selected": false, "text": "getServerSideProps app.js" }, { "answer_id": 74650820, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 2, "selected": true, "text": "pages _middleware.js import { NextResponse } from \"next/server\";\n\n// we are not exporting by default\nexport async function middleware(req, ev) {\n \n const token = req ? req.cookies?.token : null;\n const profile = await getProfile(token);\n // if profile exists you want to continue. Also\n // maybe user sends request for log-in, and if a user wants to login, obviously it has no token\n const { pathname } = req.nextUrl;\n if (\n // whatever your api route for login is\n pathname.includes(\"/api/login\") || profile \n ) {\n return NextResponse.next();\n }\n\n \n if (!profile && pathname !== \"/login\") {\n // since you want to redirect the user to \"/\"\n return NextResponse.redirect(\"/\");\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15576194/" ]
74,573,803
<p>I want to get the list of <strong>last n number</strong> of table names present in a schema in a particular database. The problem is there are lots of tables and is not convenient to scroll through all of them to reach the end. Is there a way I can use something equivalent of <strong>tail -f</strong> command which is used to look at the recent updates in a log file.</p> <p>I have tried something like <strong>tail -f \dt</strong> in the current schema. But doesn't work.</p>
[ { "answer_id": 74574037, "author": "msabic22", "author_id": 8925990, "author_profile": "https://Stackoverflow.com/users/8925990", "pm_score": 0, "selected": false, "text": "getServerSideProps app.js" }, { "answer_id": 74650820, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 2, "selected": true, "text": "pages _middleware.js import { NextResponse } from \"next/server\";\n\n// we are not exporting by default\nexport async function middleware(req, ev) {\n \n const token = req ? req.cookies?.token : null;\n const profile = await getProfile(token);\n // if profile exists you want to continue. Also\n // maybe user sends request for log-in, and if a user wants to login, obviously it has no token\n const { pathname } = req.nextUrl;\n if (\n // whatever your api route for login is\n pathname.includes(\"/api/login\") || profile \n ) {\n return NextResponse.next();\n }\n\n \n if (!profile && pathname !== \"/login\") {\n // since you want to redirect the user to \"/\"\n return NextResponse.redirect(\"/\");\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16906311/" ]
74,573,830
<p>How can I check response status code when using NuxtJs <code>useFetch</code>?</p> <p>Currently I'm handling response as follows, but I cannot find anywhere how to get the exact response status code, only an error message e.g. <code>FetchError: 403 Forbidden</code>.</p> <pre class="lang-js prettyprint-override"><code>useFetch(url, options).then( (res) =&gt; { const data = res.data.value; const error = res.error.value; if (error) { console.error(error); // handle error } else { console.log(data); // handle success } }, (error) =&gt; { console.error(error); } ); </code></pre>
[ { "answer_id": 74574037, "author": "msabic22", "author_id": 8925990, "author_profile": "https://Stackoverflow.com/users/8925990", "pm_score": 0, "selected": false, "text": "getServerSideProps app.js" }, { "answer_id": 74650820, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 2, "selected": true, "text": "pages _middleware.js import { NextResponse } from \"next/server\";\n\n// we are not exporting by default\nexport async function middleware(req, ev) {\n \n const token = req ? req.cookies?.token : null;\n const profile = await getProfile(token);\n // if profile exists you want to continue. Also\n // maybe user sends request for log-in, and if a user wants to login, obviously it has no token\n const { pathname } = req.nextUrl;\n if (\n // whatever your api route for login is\n pathname.includes(\"/api/login\") || profile \n ) {\n return NextResponse.next();\n }\n\n \n if (!profile && pathname !== \"/login\") {\n // since you want to redirect the user to \"/\"\n return NextResponse.redirect(\"/\");\n }\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3030926/" ]
74,573,857
<p>How can I run kubectl apply commands from go via client-go? e.g.: I'm having a file called crds.yaml and I want to run it via client-go</p> <p>I can't find any examples about how to do so can someone please help?</p>
[ { "answer_id": 74591683, "author": "Astin Gengo", "author_id": 8443804, "author_profile": "https://Stackoverflow.com/users/8443804", "pm_score": 1, "selected": false, "text": " yamlFile, err := ioutil.ReadFile(\"custom.yaml\")\n if err != nil {\n log.Printf(\"yamlFile.Get err #%v \", err)\n }\n\n var ctx context.Context\n var c client.Client\n var actionFn ForEachObjectInYAMLActionFunc\n\n err = ForEachObjectInYAML(ctx, c, yamlFile, \"default\", actionFn)\n if err != nil {\n fmt.Println(err)\n }\n panic: runtime error: invalid memory address or nil pointer dereference\n[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10ac5cc]\n\ngoroutine 1 [running]:\nmain.ForEachObjectInYAML({0x0, 0x0}, {0x0, 0x0}, {0xc000880000?, 0xc0000021a0?, 0x200000003?}, {0x12bf20f, 0x7}, 0x0)\n apply.go:125 +0x12c\nmain.main()\n apply.go:34 +0xc5\nexit status 2\n if err := actionFn(ctx, c, obj); err != nil {\n return err\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8443804/" ]
74,573,866
<p>I'm getting the error when transpiling Typescript with npm run build:</p> <pre><code>Type 'number | null' is not assignable to type 'number'. Type 'null' is not assignable to type 'number'. </code></pre> <p>Index.ts</p> <pre><code>public init(context: ComponentFramework.Context&lt;IInputs&gt;, notifyOutputChanged: () =&gt; void, state: ComponentFramework.Dictionary, container:HTMLDivElement) { // the increment value defaults to 1 if no increment input is detected, or it is zero. this._incrementValue = 1; if(context.parameters.incrementValue != null){ if(context.parameters.incrementValue.raw != 0){ this._incrementValue = context.parameters.incrementValue.raw; } } </code></pre> <p>On this part:</p> <pre><code>this._incrementValue </code></pre> <p>Is there a way to avoid the compiler to complaint about dealing with nulls?</p>
[ { "answer_id": 74591683, "author": "Astin Gengo", "author_id": 8443804, "author_profile": "https://Stackoverflow.com/users/8443804", "pm_score": 1, "selected": false, "text": " yamlFile, err := ioutil.ReadFile(\"custom.yaml\")\n if err != nil {\n log.Printf(\"yamlFile.Get err #%v \", err)\n }\n\n var ctx context.Context\n var c client.Client\n var actionFn ForEachObjectInYAMLActionFunc\n\n err = ForEachObjectInYAML(ctx, c, yamlFile, \"default\", actionFn)\n if err != nil {\n fmt.Println(err)\n }\n panic: runtime error: invalid memory address or nil pointer dereference\n[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10ac5cc]\n\ngoroutine 1 [running]:\nmain.ForEachObjectInYAML({0x0, 0x0}, {0x0, 0x0}, {0xc000880000?, 0xc0000021a0?, 0x200000003?}, {0x12bf20f, 0x7}, 0x0)\n apply.go:125 +0x12c\nmain.main()\n apply.go:34 +0xc5\nexit status 2\n if err := actionFn(ctx, c, obj); err != nil {\n return err\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15235239/" ]
74,573,878
<p>I suppose both the pandas value_counts() and histogram gives the frequency of an item. I have a case where this is different. When I plot a histogram, I get two peaks as shown below,</p> <pre><code>d = pd.read_csv('sample.csv') d.hist() d['value'].value_counts().nlargest(3) 200000000.0 906 20.0 219 10.0 158 Name: value, dtype: int64 </code></pre> <p><a href="https://i.stack.imgur.com/pmK2v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmK2v.png" alt="enter image description here" /></a></p> <p>But when I use value_counts(), I only get the value 200000000 as the most occurring one, but instead it should be something around 0.02. Can someone explain what exactly happens here. The sample data that I used is <a href="https://raw.githubusercontent.com/MathewKevin/sample/main/sample.csv" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 74573993, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "df['value'].plot.hist()\n pandas.cut pd.cut(df['value'], bins=10).value_counts(sort=False).plot.bar()\n pd.cut(df['value'], bins=10).value_counts(sort=False) (-199999.996, 20000000.004] 1523\n(20000000.004, 40000000.003] 5\n(40000000.003, 60000000.003] 9\n(60000000.003, 80000000.002] 5\n(80000000.002, 100000000.002] 0\n(100000000.002, 120000000.002] 8\n(120000000.002, 140000000.001] 0\n(140000000.001, 160000000.001] 0\n(160000000.001, 180000000.0] 0\n(180000000.0, 200000000.0] 906\nName: value, dtype: int64\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13440925/" ]
74,573,880
<p>I have the following form with custom validators:</p> <pre><code>this.Form = this.fb.group({ cruiseId: new FormControl(this.leg.cruiseId), startDate: new FormControl(this.leg.startDate, [Validators.required]), endDate: new FormControl(this.leg.endDate) }, { validators: [this.checkDuplicates, this.checkDates] }); </code></pre> <p>In my component, I have an input property which contains all departure dates for a cruise (<code>@Input() cruiseArray!: cruiseItem[];</code>). Using the checkDuplicates function, I want to verify that we don't have 2 identical departure dates for the same cruise.</p> <pre><code>checkDuplicates(group: FormGroup) { console.log(this.cruiseArray); let sDate = group.get('startDate')?.value; if (sDate !== null &amp;&amp; this.cruiseArray.find(x =&gt; x.startDate === sDate)) { return { invalidDuplicate: true } } return null; } </code></pre> <p>My concern is that <code>this.cruiseArray</code> is alway undefined. If I try the following in my component</p> <pre><code>ngOnInit(): void { console.log(this.cruiseArray); } </code></pre> <p>it works perfectly and my array returned by the parent is populated.</p> <p>Full code:</p> <pre><code> @Component({ selector: .., templateUrl: .., styleUrls: [..] }) export class MyComponent implements OnInit { Input() cruiseArray!: cruiseItem[]; .... ngOnInit(): void { console.log(this.cruiseArray); &lt;--- DOES WORK } .... ngOnChanges(changes: SimpleChanges) { this.createForm(); } .... createForm() { this.Form = this.fb.group({ cruiseId: new FormControl(this.leg.cruiseId), startDate: new FormControl(this.leg.startDate, [Validators.required]), endDate: new FormControl(this.leg.endDate) }, { validators: [this.checkDuplicates, this.checkDates] }); } .... checkDuplicates(group: FormGroup) { console.log(this.cruiseArray); &lt;--- DOES NOT WORK let sDate = group.get('startDate')?.value; if (sDate !== null &amp;&amp; this.cruiseArray.find(x =&gt; x.startDate === sDate)) { return { invalidDuplicate: true } } return null; } } } </code></pre> <p>Why <code>this.cruiseArray</code> is undefined in my validator function even when it is populated elsewhere in my component.</p>
[ { "answer_id": 74573993, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "df['value'].plot.hist()\n pandas.cut pd.cut(df['value'], bins=10).value_counts(sort=False).plot.bar()\n pd.cut(df['value'], bins=10).value_counts(sort=False) (-199999.996, 20000000.004] 1523\n(20000000.004, 40000000.003] 5\n(40000000.003, 60000000.003] 9\n(60000000.003, 80000000.002] 5\n(80000000.002, 100000000.002] 0\n(100000000.002, 120000000.002] 8\n(120000000.002, 140000000.001] 0\n(140000000.001, 160000000.001] 0\n(160000000.001, 180000000.0] 0\n(180000000.0, 200000000.0] 906\nName: value, dtype: int64\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439959/" ]
74,573,907
<p>In EXCEL, I would like to change the array of a two columns table (A1:A91;B1:B91) to a 13 X 7 table as follows, by removing the &quot;Turnover&quot; text and replacing the cells with the turnover quantity. <a href="https://i.stack.imgur.com/sovUn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sovUn.jpg" alt="enter image description here" /></a></p> <p>I would like to use some functions such as WRAPCOLS, CHOOSEROWS and TOROW</p>
[ { "answer_id": 74575077, "author": "Ike", "author_id": 16578424, "author_profile": "https://Stackoverflow.com/users/16578424", "pm_score": 1, "selected": false, "text": "=LET(d,A1:B26,\ndOnly,FILTER(d,INDEX(d,,2)<>\"Turnover\"),\nyears,UNIQUE(FILTER(INDEX(d,,1),INDEX(d,,2) = \"Turnover\")),\nmonths,UNIQUE(INDEX(dOnly,,1)),\nHSTACK(VSTACK({\"\"},years),VSTACK(TRANSPOSE(months),WRAPROWS(INDEX(dOnly,,2),ROWS(months)))))\n" }, { "answer_id": 74575182, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": true, "text": "D1 =LET(rng, A1:B26, colA, INDEX(rng,,1), colB, INDEX(rng,,2),\n values, FILTER(colB, colB<>\"Turnover\"),\n codes, FILTER(colA, colB=\"Turnover\"),\n months, TEXT(EDATE(1, SEQUENCE(1,12,0)),\"mmm\"),\n matrix, WRAPROWS(values, 12), \n VSTACK(HSTACK(\"\",months), HSTACK(codes, matrix))\n)\n months 1 1/1/1900 TEXT mmm months mmmm EDATE(x, SEQUENCE(1,12,0)) x A2 TOROW(UNIQUE(FILTER(colA, colB<>\"Turnover\")))" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12267517/" ]
74,573,955
<p>Hi I am hoping you could help me in this python error that i could not solve</p> <pre><code>def remove_dots(string): lst = [] for i in range(len(string)): lst.append(string[i]) for i in range(len(lst)): if i &lt;= len(lst): if lst[i] == &quot;.&quot;: lst.remove(lst[i]) else: continue nstring = &quot;&quot;.join(lst) return nstring </code></pre> <p>The Error:</p> <pre><code> if lst[i] == &quot;.&quot;: IndexError: list index out of range </code></pre> <p>And this is the call of the function:</p> <pre><code>print(remove_dots(&quot;maj.d&quot;)) </code></pre> <p>So if any one can help me and thank you</p>
[ { "answer_id": 74574036, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "def remove_dots(string):\n lst = []\n\n for i in range(len(string)):\n lst.append(string[i])\n\n for i in range(len(lst)):\n\n if i< len(lst): \n\n if lst[i] == \".\":\n lst.remove(lst[i])\n\n else:\n continue\n\n nstring = \"\".join(lst)\n\n return nstring\n\nprint(remove_dots(\"maj.d\"))\n majd\n string = \"maj.d\"\nstring = string.replace(\".\", '')\nprint(string)\n majd\n" }, { "answer_id": 74574048, "author": "Kikuro", "author_id": 20600058, "author_profile": "https://Stackoverflow.com/users/20600058", "pm_score": 0, "selected": false, "text": "for i in range(len(lst))) for i in range((len(lst))-1) lst try -1" }, { "answer_id": 74574061, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "string = string.replace(\".\", \"\")\n" }, { "answer_id": 74574062, "author": "BSimjoo", "author_id": 7421566, "author_profile": "https://Stackoverflow.com/users/7421566", "pm_score": 0, "selected": false, "text": "lst.remove('.') '.' str.replace string.replace('.', '')\n" }, { "answer_id": 74574265, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 2, "selected": true, "text": "i <= len(lst) i < len(lst) lst.remove('.') if i < len(lst): def remove_dots(string):\n output = \"\"\n \n for char in string:\n if char != \".\":\n output += char\n \n return output\n string.replace(\".\", \"\")" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14315689/" ]
74,573,998
<p>Below are two arrays, <code>user_array</code> and <code>company_array</code>.</p> <p>The <code>user_list</code> is grouped by <code>vendor_id</code>. I want to create bottom <code>group_list</code> array by adding a new <code>user_list</code> key to <code>company_list</code>.</p> <p>I would like to know how to implement this one. Thank you in advance.</p> <pre class="lang-json prettyprint-override"><code>const company_list = [ { &quot;vendor_id&quot;: &quot;62d884697df5ad65745001a9&quot;, &quot;vendor_name&quot;: &quot;vender_name_1&quot;, }, { &quot;vendor_id&quot;: &quot;add8846dad5ad657450s01a&quot;, &quot;vendor_name&quot;: &quot;vender_name_2&quot;, }, { &quot;vendor_id&quot;: &quot;34d8846dad5add57450sss3&quot;, &quot;vendor_name&quot;: &quot;vender_name_3&quot;, }, ] </code></pre> <pre><code>const user_list = { &quot;62d884697df5ad65745001a9&quot;: [ { &quot;user_id&quot;: &quot;0e9a3faf-4dcc-4681-a153-2f6c7acd161d&quot;, &quot;user_name&quot;: &quot;user_1&quot;, }, { &quot;user_id&quot;: &quot;f39769cb-e567-4da9-8e2c-9e39daaba9ed&quot;, &quot;user_name&quot;: &quot;user_2&quot;, } ], &quot;add8846dad5ad657450s01a&quot;: [ { &quot;user_id&quot;: &quot;de9adfaf-4dcc-d681-ad53-2f6cdacd161d&quot;, &quot;user_name&quot;: &quot;user_3&quot;, }, { &quot;user_id&quot;: &quot;g397g9cb-e5g7-4dag-8e2cgge39daaba9&quot;, &quot;user_name&quot;: &quot;user_4&quot;, } ] &quot;34d8846dad5add57450sss3&quot;: [ { &quot;user_id&quot;: &quot;deaadfaf-4dac-d6a1-ad5a-2f6adacd161a&quot;, &quot;user_name&quot;: &quot;user_5&quot;, }, { &quot;user_id&quot;: &quot;g397b9cb-e5g7-4dab-8b2cgge39daaba9&quot;, &quot;user_name&quot;: &quot;user_6&quot;, } ] } </code></pre> <pre><code>const group_list = [ { &quot;vendor_id&quot;: &quot;62d884697df5ad65745001a9&quot;, &quot;vendor_name&quot;: &quot;vender_name_1&quot;,
 “user_list” : [ { &quot;user_id&quot;: &quot;0e9a3faf-4dcc-4681-a153-2f6c7acd161d&quot;, &quot;user_name&quot;: &quot;user_1&quot;, }, { &quot;user_id&quot;: &quot;f39769cb-e567-4da9-8e2c-9e39daaba9ed&quot;, &quot;user_name&quot;: &quot;user_2&quot;, }, ], }, { &quot;vendor_id&quot;: &quot;add8846dad5ad657450s01a&quot;, &quot;vendor_name&quot;: &quot;vender_name_2&quot;, “user_list” : [ { &quot;user_id&quot;: &quot;de9adfaf-4dcc-d681-ad53-2f6cdacd161d&quot;, &quot;user_name&quot;: &quot;user_3&quot;, }, { &quot;user_id&quot;: &quot;g397g9cb-e5g7-4dag-8e2cgge39daaba9&quot;, &quot;user_name&quot;: &quot;user_4&quot;, }, ], }, { &quot;vendor_id&quot;: &quot;34d8846dad5add57450sss3&quot;, &quot;vendor_name&quot;: &quot;vender_name_3&quot;, “user_list” : [ { &quot;user_id&quot;: &quot;deaadfaf-4dac-d6a1-ad5a-2f6adacd161a&quot;, &quot;user_name&quot;: &quot;user_5&quot;, }, { &quot;user_id&quot;: &quot;g397b9cb-e5g7-4dab-8b2cgge39daaba9&quot;, &quot;user_name&quot;: &quot;user_6&quot;, }, ], }, ] </code></pre> <p>The grouping of user_list was achieved by implementing the following But, it is stuck at the point of merging user_list into company_list.</p> <pre class="lang-js prettyprint-override"><code>const groupByCompany = async (array, key) =&gt; { const response = await array.reduce((result, currentValue) =&gt; { (result[currentValue[key]] = result[currentValue[key]] || []).push( currentValue ); return result; }, {}); return response; }; </code></pre>
[ { "answer_id": 74574036, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "def remove_dots(string):\n lst = []\n\n for i in range(len(string)):\n lst.append(string[i])\n\n for i in range(len(lst)):\n\n if i< len(lst): \n\n if lst[i] == \".\":\n lst.remove(lst[i])\n\n else:\n continue\n\n nstring = \"\".join(lst)\n\n return nstring\n\nprint(remove_dots(\"maj.d\"))\n majd\n string = \"maj.d\"\nstring = string.replace(\".\", '')\nprint(string)\n majd\n" }, { "answer_id": 74574048, "author": "Kikuro", "author_id": 20600058, "author_profile": "https://Stackoverflow.com/users/20600058", "pm_score": 0, "selected": false, "text": "for i in range(len(lst))) for i in range((len(lst))-1) lst try -1" }, { "answer_id": 74574061, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "string = string.replace(\".\", \"\")\n" }, { "answer_id": 74574062, "author": "BSimjoo", "author_id": 7421566, "author_profile": "https://Stackoverflow.com/users/7421566", "pm_score": 0, "selected": false, "text": "lst.remove('.') '.' str.replace string.replace('.', '')\n" }, { "answer_id": 74574265, "author": "fsimonjetz", "author_id": 15873043, "author_profile": "https://Stackoverflow.com/users/15873043", "pm_score": 2, "selected": true, "text": "i <= len(lst) i < len(lst) lst.remove('.') if i < len(lst): def remove_dots(string):\n output = \"\"\n \n for char in string:\n if char != \".\":\n output += char\n \n return output\n string.replace(\".\", \"\")" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74573998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18703133/" ]
74,574,016
<p>I have a set of files (FILE1.txt, FILE2.txt ...) of the form:</p> <pre><code>foo 123 bar 456 start foo 321 bar 654 </code></pre> <p>And I want to ignore everything before <code>start</code> and only read lines containing <code>foo</code> in each file.</p> <p>My attempt is this command :</p> <pre><code>awk '/start/,/EOF/ {if($1==&quot;foo&quot;){print $2}} ' FILE*.txt </code></pre> <p>And it actually works on the first file, that is it will print <code>foo 321</code> but then it will ignore the range pattern for the next files. That is, if we assume that all the files has the same content showed above, it will print:</p> <pre><code>$ awk '/start/,/EOF/ {if($1==&quot;foo&quot;){print $2}} ' FILE*.txt 321 // Expected from FILE1.txt, successfully ignore the first &quot;foo&quot; before &quot;start&quot;. 123 // Unexpected from FILE2.txt 321 // Expected from FILE2.txt 123 // Unexpected from FILE3.txt 321 // Expected from FILE3.txt ... </code></pre> <p>What am I doing wrong ? How to make the range pattern working on each file and not only once over all the files? I've actually found a workaround based on <code>find</code> but for the sake of a good understanding I'm looking toward a solution relying on <code>awk</code> only.</p>
[ { "answer_id": 74574164, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 3, "selected": true, "text": "awk awk awk '\nFNR==1 { found=0 } # FNR==1st record of new file, reset flag\n/start/ { found=1 } # found start of range, set flag\nfound && $1==\"foo\" { print $2 } # if flag set and 1st field == \"foo\" then print 2nd field\n' FILE?.txt\n /start/ start restart last time I started the car $1==\"start\" FILE{1..3}.txt 321\n321\n321\n" }, { "answer_id": 74574487, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "/EOF/ EOF EOF AWK file1.txt foo 123\nbar 456\nstart\nfoo 321\nbar 654\n file2.txt foo 1230\nbar 4560\nstart\nfoo 3210\nbar 6540\n file3.txt foo 12300\nbar 45600\nstart\nfoo 32100\nbar 65400\n awk '/start/{f=1}f&&$1==\"bar\"{print}ENDFILE{f=0}' file1.txt file2.txt file3.txt\n bar 654\nbar 6540\nbar 65400\n f 1 $1 bar print ENDFILE" }, { "answer_id": 74574568, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "$ awk -v row=\"start\" -v regx=\"foo\" '\n FNR == 1{x = 0}\n x == 1 && $1 ~ regx{print $2}\n $1 ~ row{x = 1}' file file file\n321\n321\n321\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14480564/" ]
74,574,017
<p>I am deploying, on 3 different environments (test, stage &amp; production) an API. I am used to deploy with docker-compose so I wrote 2 services (1 for my API and 1 for a database) like following:</p> <pre><code># file docker-compose.yml version: '3.3' services: api: build: context: .. dockerfile: Dockerfile image: my_api:${TAG} ports: - &quot;${API_PORT_FROM_ENV}:8000&quot; env_file: .env depends_on: - db db: image: whatever:v0.0.0 ports: - &quot;${DB_PORT_FROM_ENV}:5000&quot; env_file: - .env </code></pre> <p>In the file above, you can find the <strong>parent services</strong>. Thne, I wrote 2 files that explains my strategy to deploy <strong>on the same Virtual Machine</strong> my containers:</p> <p>-&gt; staging environment below</p> <pre><code># docker-compose.stage.yml version: &quot;3.3 services: api: container_name: api_stage environment: - environment=&quot;staging&quot; db: container_name: db_stage environment: - environment=&quot;staging&quot; volumes: - /I/Mount/a/local/volume/stage:/container/volume </code></pre> <p>-&gt; production environment below</p> <pre><code># docker-compose.prod.yml version: &quot;3.3 services: api: container_name: api_prod environment: - environment=&quot;production&quot; db: container_name: db_prod environment: - environment=&quot;production&quot; volumes: - /I/Mount/a/local/volume/prod:/container/volume </code></pre> <p><strong>My problem</strong>:</p> <p>The production is actually running. I deploy my containers with the following command:</p> <pre><code>docker-compose -f docker-compose.yml -f docker-compose.prod.yml up --build </code></pre> <p>I want to deploy a <em>staging</em> environment on the same virtual machine. I want <strong>my api_prod + db_prod running in parallel with api_stage + db_stage</strong>.</p> <p>Unfortunatly, when I run the command:</p> <pre><code>docker-compose -f docker-compose.yml -f docker-compose.stage.yml up --build </code></pre> <p>My containers called api_prod and db_prod stops. Why?</p>
[ { "answer_id": 74574164, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 3, "selected": true, "text": "awk awk awk '\nFNR==1 { found=0 } # FNR==1st record of new file, reset flag\n/start/ { found=1 } # found start of range, set flag\nfound && $1==\"foo\" { print $2 } # if flag set and 1st field == \"foo\" then print 2nd field\n' FILE?.txt\n /start/ start restart last time I started the car $1==\"start\" FILE{1..3}.txt 321\n321\n321\n" }, { "answer_id": 74574487, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "/EOF/ EOF EOF AWK file1.txt foo 123\nbar 456\nstart\nfoo 321\nbar 654\n file2.txt foo 1230\nbar 4560\nstart\nfoo 3210\nbar 6540\n file3.txt foo 12300\nbar 45600\nstart\nfoo 32100\nbar 65400\n awk '/start/{f=1}f&&$1==\"bar\"{print}ENDFILE{f=0}' file1.txt file2.txt file3.txt\n bar 654\nbar 6540\nbar 65400\n f 1 $1 bar print ENDFILE" }, { "answer_id": 74574568, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "$ awk -v row=\"start\" -v regx=\"foo\" '\n FNR == 1{x = 0}\n x == 1 && $1 ~ regx{print $2}\n $1 ~ row{x = 1}' file file file\n321\n321\n321\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9947412/" ]
74,574,022
<p>I am using Tailwind css with my react application. I am creating a form using tailwind and want to change focus border color of my input text box in teal which is blue.</p> <pre><code> function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;main className=&quot;h-screen flex items-center justify-center&quot;&gt; &lt;form className=&quot;bg-white flex rounded-lg w-1/2&quot;&gt; &lt;div className= &quot;flex-1 text-gray-700 p-20&quot;&gt; &lt;h1 className=&quot;text-3xl pb-2&quot;&gt;Lets Get Started&lt;/h1&gt; &lt;p className=&quot;text-lg text-gray-500&quot;&gt;We are herre to get you about our sdas no bonsdcbeagufpi feqwifheqfwe&lt;/p&gt; &lt;div className='mt-6'&gt; &lt;div className=&quot;pb-4&quot;&gt; &lt;label className=&quot;block text-sm pb-2&quot; htmlFor=&quot;name&quot; &gt;Name &lt;/label&gt; &lt;input className=&quot;border-2 border-gray-500 p-2 rounded-md w-1/2 focus:border-teal-500&quot; type=&quot;text&quot; name=&quot;name&quot; placeholder='Enter Your Name' /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/main&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>I did change teal color with focus:boreder-teal-500 but it is not chaging teal color when I focus or click on my text box.</p>
[ { "answer_id": 74574156, "author": "AlexThyCoolest", "author_id": 20599745, "author_profile": "https://Stackoverflow.com/users/20599745", "pm_score": -1, "selected": false, "text": "p:hover{\n color: red;\n}\n" }, { "answer_id": 74574197, "author": "godofclash", "author_id": 19559143, "author_profile": "https://Stackoverflow.com/users/19559143", "pm_score": 0, "selected": false, "text": "<div className=\"focus:border-blue border-2 border-solid\" />\n" }, { "answer_id": 74585483, "author": "RK007", "author_id": 14386098, "author_profile": "https://Stackoverflow.com/users/14386098", "pm_score": 0, "selected": false, "text": "focus:outline-none <input className=\"border-2 border-gray-500 p-2 rounded-md w-1/2 focus:border-teal-500 focus:outline-none\" type=\"text\" name=\"name\" placeholder='Enter Your Name' />\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20517610/" ]
74,574,027
<pre><code> type Tuple = []; const tup: Tuple = [ ((a, b) = { // a: number; tup 2th item // b: boolean; tup 3th item }), 1, false, // more item enble. ]; </code></pre> <p>First item is a function, parameter type are rest of the tulpe.</p> <p>i try defined the Tuple, but code error &quot;Type alias 'Tuple' circularly references itself. &quot;</p> <pre><code>type Tuple = [(...args: any) =&gt; void, ...Parameters&lt;Tuple[0]&gt;]; </code></pre>
[ { "answer_id": 74574070, "author": "Pedro A", "author_id": 4135063, "author_profile": "https://Stackoverflow.com/users/4135063", "pm_score": 0, "selected": false, "text": "type MyFunction = (a: number, b: boolean) => void;\ntype MyTuple = [MyFunction, ...Parameters<MyFunction>];\n" }, { "answer_id": 74574234, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 1, "selected": false, "text": "const createTuple = <T extends any[]>(arg: [(...args: T) => void, ...T]) => arg\n T T const tuple = createTuple([\n (a, b) => {\n a\n// ^? a: number\n\n b\n// ^? b: boolean\n },\n 1,\n false,\n])\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20599964/" ]
74,574,072
<p>I am trying to decompose my program on <code>python</code>. I have read a lot of information and other answers about how <code>import</code> works, but still cant understand how exactly.</p> <p>I want to use my module <code>Graph.Graph2D</code> for implementation in <code>InteractiveGraph2D</code>. Before importing it, I add path to this module. But it tells <code>NameError: name 'Graph2D' is not defined</code>.</p> <p>Project path:</p> <blockquote> <p>~/MyData/Python/Pygame/RoadSearchAlgorithm/src</p> </blockquote> <p>Module path:</p> <blockquote> <p>~/MyData/Python/Pygame/MY_MODULES/Graph</p> </blockquote> <p>Code:</p> <pre><code># ~/MyData/Python/Pygame/RoadSearchAlgorithm/src/Graph_package/InteractiveGraph2D.py ... sys.path.append('./') sys.path.append('/home/rayxxx/MyData/Python/MY_MODULES') try: from Graph.Graph2D import Graph2D, ... ... except Exception as e: assert (e) class InteractiveGraph2D(Graph2D): ... </code></pre> <p>What's the problem?</p> <p>I tried to look at paths, list of imported modules. The Graph module presented in it.</p>
[ { "answer_id": 74574283, "author": "Lenn Lewis", "author_id": 20593333, "author_profile": "https://Stackoverflow.com/users/20593333", "pm_score": 0, "selected": false, "text": "setup.py" }, { "answer_id": 74574358, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 2, "selected": true, "text": "~/MyData/Python/Pygame/MY_MODULES/Graph '/home/rayxxx/MyData/Python/MY_MODULES'" }, { "answer_id": 74574481, "author": "Jonathan axel Hidalgo nuñez", "author_id": 16403532, "author_profile": "https://Stackoverflow.com/users/16403532", "pm_score": 1, "selected": false, "text": "from Graph.Graph2D import Graph2D, ...\n ~/MyData/Python/Pygame/RoadSearchAlgorithm/src\n MY_MODULE MY_MODULES/" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19646723/" ]
74,574,126
<p>I have a table where I am trying to concatenate merged cell with other column values</p> <p><a href="https://i.stack.imgur.com/rp1Ki.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rp1Ki.png" alt="enter image description here" /></a> I used this formula to get the concatenation done,</p> <pre><code>=ArrayFormula(query(byrow( {lookup(row(A3:A),row(A3:A)/(A3:A&lt;&gt;&quot;&quot;),A3:A),D3:G}, lambda(r,textjoin(&quot;-&quot;,1,r))), &quot;limit &quot;&amp;-1+max(F3:G11&lt;&gt;&quot;&quot;,row(F3:G11)))) </code></pre> <p>but I want to exclude column by name <code>BF</code> from the concatenation.</p> <p>I only want <code>Name</code>, <code>Frequency</code>, <code>Old Measure</code> and <code>New Measure</code> columns to be concatenated</p> <p>Please help in guiding me here. @ztiaa @Martin</p>
[ { "answer_id": 74574908, "author": "pgSystemTester", "author_id": 11732320, "author_profile": "https://Stackoverflow.com/users/11732320", "pm_score": 3, "selected": true, "text": "byRow =ArrayFormula(query(byrow(\n{lookup(row(A3:A),row(A3:A)/(A3:A<>\"\"),A3:A),D3:D,F3:G},\nlambda(r,textjoin(\"-\",1,r))),\n\"select Col1 limit \"&-1+max(F3:G11<>\"\",row(F3:G11))))\n" }, { "answer_id": 74577247, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(LAMBDA(c, LAMBDA(a, b, BYROW({VLOOKUP(ROW(a), IF(a<>\"\", {ROW(a), a}), 2), \n IF(b=\"\",,\"-\"&b)}, LAMBDA(x, JOIN(, x))))\n (A2:INDEX(A:A, c), D2:INDEX(G:G, c)))(MAX(ROW(A:A)*(A:G<>\"\"))))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20357303/" ]
74,574,131
<pre><code>int main(){ int limit_x; int limit_y; scanf(&quot;%d&quot;, &amp;limit_x); scanf(&quot;%d&quot;, &amp;limit_y); char map[limit_x][limit_y]; for (int index_x=0;index_x&lt;limit_x;index_x++) { for (int index_y = 0; index_y &lt; limit_y; index_y++) { scanf(&quot;%c&quot;, &amp;map[index_x][index_y]); } } } </code></pre> <p>This is how I try to do it , but it is not working for me . it shows error C2057,C2466.</p> <p>Let users input the row and col, and make a dynamic 2d array map by input.</p>
[ { "answer_id": 74574908, "author": "pgSystemTester", "author_id": 11732320, "author_profile": "https://Stackoverflow.com/users/11732320", "pm_score": 3, "selected": true, "text": "byRow =ArrayFormula(query(byrow(\n{lookup(row(A3:A),row(A3:A)/(A3:A<>\"\"),A3:A),D3:D,F3:G},\nlambda(r,textjoin(\"-\",1,r))),\n\"select Col1 limit \"&-1+max(F3:G11<>\"\",row(F3:G11))))\n" }, { "answer_id": 74577247, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=INDEX(LAMBDA(c, LAMBDA(a, b, BYROW({VLOOKUP(ROW(a), IF(a<>\"\", {ROW(a), a}), 2), \n IF(b=\"\",,\"-\"&b)}, LAMBDA(x, JOIN(, x))))\n (A2:INDEX(A:A, c), D2:INDEX(G:G, c)))(MAX(ROW(A:A)*(A:G<>\"\"))))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20591238/" ]
74,574,133
<p>I'm stuck at work with a code problem in R that I can't solve. I have the following XML Data:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;Votacion xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; xmlns=&quot;http://opendata.camara.cl/camaradiputados/v1&quot;&gt; &lt;Id&gt;15446&lt;/Id&gt; &lt;Descripcion&gt;Proyecto de Acuerdo N° 574&lt;/Descripcion&gt; &lt;Fecha&gt;2012-06-13T14:47:29&lt;/Fecha&gt; &lt;TotalSi&gt;12&lt;/TotalSi&gt; &lt;TotalNo&gt;2&lt;/TotalNo&gt; &lt;TotalAbstencion&gt;2&lt;/TotalAbstencion&gt; &lt;TotalDispensado&gt;0&lt;/TotalDispensado&gt; &lt;Quorum Valor=&quot;1&quot;&gt;Quórum Simple&lt;/Quorum&gt; &lt;Resultado Valor=&quot;2&quot;&gt;Unánime&lt;/Resultado&gt; &lt;Tipo Valor=&quot;3&quot;&gt;Proyecto de Acuerdo&lt;/Tipo&gt; &lt;Votos&gt; &lt;Voto&gt; &lt;Diputado&gt; &lt;Id&gt;810&lt;/Id&gt; &lt;Nombre&gt;Gabriel&lt;/Nombre&gt; &lt;ApellidoPaterno&gt;Ascencio&lt;/ApellidoPaterno&gt; &lt;ApellidoMaterno&gt;Mansilla&lt;/ApellidoMaterno&gt; &lt;/Diputado&gt; &lt;OpcionVoto Valor=&quot;1&quot;&gt;Afirmativo&lt;/OpcionVoto&gt; &lt;/Voto&gt; &lt;Voto&gt; &lt;Diputado&gt; &lt;Id&gt;855&lt;/Id&gt; &lt;Nombre&gt;Carlos Abel&lt;/Nombre&gt; &lt;ApellidoPaterno&gt;Jarpa&lt;/ApellidoPaterno&gt; &lt;ApellidoMaterno&gt;Wevar&lt;/ApellidoMaterno&gt; &lt;/Diputado&gt; &lt;OpcionVoto Valor=&quot;1&quot;&gt;Afirmativo&lt;/OpcionVoto&gt; &lt;/Voto&gt; &lt;Voto&gt; &lt;Diputado&gt; &lt;Id&gt;862&lt;/Id&gt; &lt;Nombre&gt;Pablo&lt;/Nombre&gt; &lt;ApellidoPaterno&gt;Lorenzini&lt;/ApellidoPaterno&gt; &lt;ApellidoMaterno&gt;Basso&lt;/ApellidoMaterno&gt; &lt;/Diputado&gt; &lt;OpcionVoto Valor=&quot;0&quot;&gt;En Contra&lt;/OpcionVoto&gt; &lt;/Voto&gt; &lt;Voto&gt; &lt;Diputado&gt; &lt;Id&gt;898&lt;/Id&gt; &lt;Nombre&gt;Gabriel&lt;/Nombre&gt; &lt;ApellidoPaterno&gt;Silber&lt;/ApellidoPaterno&gt; &lt;ApellidoMaterno&gt;Romo&lt;/ApellidoMaterno&gt; &lt;/Diputado&gt; &lt;OpcionVoto Valor=&quot;1&quot;&gt;Afirmativo&lt;/OpcionVoto&gt; &lt;/Voto&gt; &lt;/Votos&gt; &lt;/Votacion&gt; </code></pre> <p>I got the data from this api <a href="https://opendata.camara.cl/camaradiputados/WServices/WSLegislativo.asmx/retornarVotacionDetalle?prmVotacionId=15446" rel="nofollow noreferrer">https://opendata.camara.cl/camaradiputados/WServices/WSLegislativo.asmx/retornarVotacionDetalle?prmVotacionId=15446</a></p> <p>I want to process the data to obtain a tibble like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>Nombre</th> <th>ApellidoPaterno</th> <th>ApellidoMaterno</th> <th>OpcionVoto</th> </tr> </thead> <tbody> <tr> <td>810</td> <td>Gabriel</td> <td>Acencio</td> <td>Mansilla</td> <td>Afirmativo</td> </tr> <tr> <td>855</td> <td>Abel</td> <td>Jarpa</td> <td>Webar</td> <td>Afirmativo</td> </tr> <tr> <td>862</td> <td>Pablo</td> <td>Lorenzini</td> <td>Basso</td> <td>En Contra</td> </tr> </tbody> </table> </div> <p>Any kind of help will be amazing, please !!!</p>
[ { "answer_id": 74574776, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "library(xml2)\nlibrary(purrr)\n\nxml <- read_xml('<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>')\n\nxml_ns(xml)\n# d1 <-> http://opendata.camara.cl/camaradiputados/v1\n# xsd <-> http://www.w3.org/2001/XMLSchema\n# xsi <-> http://www.w3.org/2001/XMLSchema-instance\n\n\nxml %>% xml_find_all(\".//d1:Voto\") %>% \n map_dfr(~ set_names(\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_text),\n .x %>% xml_child(\"d1:OpcionVoto\") %>% xml_text()),\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_name), \"OpcionVoto\")))\n\n# A tibble: 4 × 5\n# Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n# <chr> <chr> <chr> <chr> <chr> \n#1 810 Gabriel Ascencio Mansilla Afirmativo\n#2 855 Carlos Abel Jarpa Wevar Afirmativo\n#3 862 Pablo Lorenzini Basso En Contra \n#4 898 Gabriel Silber Romo Afirmativo\n" }, { "answer_id": 74575289, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "library(xml2)\nlibrary(dplyr)\nlibrary(tidyr)\n\nread_xml(xml_str) %>% \n xml_ns_strip() %>% \n xml_find_all(\"//Voto\") %>% \n as_list() %>% \n tibble(lst = .) %>% \n\n # A tibble: 4 × 1\n\n unnest_wider(lst) %>% \n\n # A tibble: 4 × 2\n # Diputado OpcionVoto\n # 1 <named list [4]> <list [1]>\n\n unnest_wider(\"Diputado\") %>% \n\n # A tibble: 4 × 5\n # Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n # <list> <list> <list> <list> <list> \n # 1 <list [1]> <list [1]> <list [1]> <list [1]> <list [1]> \n\n unnest_longer(everything())\n#> # A tibble: 4 × 5\n#> Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n#> <chr> <chr> <chr> <chr> <chr> \n#> 1 810 Gabriel Ascencio Mansilla Afirmativo\n#> 2 855 Carlos Abel Jarpa Wevar Afirmativo\n#> 3 862 Pablo Lorenzini Basso En Contra \n#> 4 898 Gabriel Silber Romo Afirmativo\n xml_str <- \n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>'\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13282579/" ]
74,574,135
<p>I want this string:</p> <pre><code>{&quot;creationtime&quot;:&quot;2022-11-25T09:12:44Z&quot;,&quot;data&quot;:[{&quot;id&quot;:&quot;78cb7b69-bbfa-4d6c-8156-ada66201bf73&quot;,&quot;id_v1&quot;:&quot;/sensors/22&quot;,&quot;motion&quot;:{&quot;motion&quot;:true,&quot;motion_valid&quot;:true},&quot;owner&quot;:{&quot;rid&quot;:&quot;4b16b918-485a-44de-82aa-4ff467f6591a&quot;,&quot;rtype&quot;:&quot;device&quot;},&quot;type&quot;:&quot;motion&quot;}],&quot;id&quot;:&quot;813e2ed1-f28e-451b-9ac6-9eef76ef7b4a&quot;,&quot;type&quot;:&quot;update&quot;},{&quot;creationtime&quot;:&quot;2022-11-25T09:12:44Z&quot;,&quot;data&quot;:[{&quot;id&quot;:&quot;6a743cb9-bcc4-44bb-8592-c4854e8fadcb&quot;,&quot;id_v1&quot;:&quot;/sensors/32&quot;,&quot;motion&quot;:{&quot;motion&quot;:true,&quot;motion_valid&quot;:true},&quot;owner&quot;:{&quot;rid&quot;:&quot;cdb31512-997f-4e26-80d1-50dca6b431a3&quot;,&quot;rtype&quot;:&quot;device&quot;},&quot;type&quot;:&quot;motion&quot;}],&quot;id&quot;:&quot;240698ea-5938-4e7c-a70c-75bad0fe2a7f&quot;,&quot;type&quot;:&quot;update&quot;},{&quot;creationtime&quot;:&quot;2022-11-25T09:12:44Z&quot;,&quot;data&quot;:[{&quot;id&quot;:&quot;f4fc5daf-a2aa-4c9f-9812-a65c9922b53e&quot;,&quot;id_v1&quot;:&quot;/sensors/2&quot;,&quot;motion&quot;:{&quot;motion&quot;:true,&quot;motion_valid&quot;:true},&quot;owner&quot;:{&quot;rid&quot;:&quot;8daa62b1-af26-44b3-8356-15d21cf6642c&quot;,&quot;rtype&quot;:&quot;device&quot;},&quot;type&quot;:&quot;motion&quot;}],&quot;id&quot;:&quot;124546d2-cf7e-4b64-a99d-2af2c047aaea&quot;,&quot;type&quot;:&quot;update&quot;} </code></pre> <p>To be split up in a list as follows:</p> <pre><code>{&quot;creationtime&quot;:&quot;2022-11-25T09:12:44Z&quot;,&quot;data&quot;:[{&quot;id&quot;:&quot;78cb7b69-bbfa-4d6c-8156-ada66201bf73&quot;,&quot;id_v1&quot;:&quot;/sensors/22&quot;,&quot;motion&quot;:{&quot;motion&quot;:true,&quot;motion_valid&quot;:true},&quot;owner&quot;:{&quot;rid&quot;:&quot;4b16b918-485a-44de-82aa-4ff467f6591a&quot;,&quot;rtype&quot;:&quot;device&quot;},&quot;type&quot;:&quot;motion&quot;}],&quot;id&quot;:&quot;813e2ed1-f28e-451b-9ac6-9eef76ef7b4a&quot;,&quot;type&quot;:&quot;update&quot;}, {&quot;creationtime&quot;:&quot;2022-11-25T09:12:44Z&quot;,&quot;data&quot;:[{&quot;id&quot;:&quot;6a743cb9-bcc4-44bb-8592-c4854e8fadcb&quot;,&quot;id_v1&quot;:&quot;/sensors/32&quot;,&quot;motion&quot;:{&quot;motion&quot;:true,&quot;motion_valid&quot;:true},&quot;owner&quot;:{&quot;rid&quot;:&quot;cdb31512-997f-4e26-80d1-50dca6b431a3&quot;,&quot;rtype&quot;:&quot;device&quot;},&quot;type&quot;:&quot;motion&quot;}],&quot;id&quot;:&quot;240698ea-5938-4e7c-a70c-75bad0fe2a7f&quot;,&quot;type&quot;:&quot;update&quot;}, {&quot;creationtime&quot;:&quot;2022-11-25T09:12:44Z&quot;,&quot;data&quot;:[{&quot;id&quot;:&quot;f4fc5daf-a2aa-4c9f-9812-a65c9922b53e&quot;,&quot;id_v1&quot;:&quot;/sensors/2&quot;,&quot;motion&quot;:{&quot;motion&quot;:true,&quot;motion_valid&quot;:true},&quot;owner&quot;:{&quot;rid&quot;:&quot;8daa62b1-af26-44b3-8356-15d21cf6642c&quot;,&quot;rtype&quot;:&quot;device&quot;},&quot;type&quot;:&quot;motion&quot;}],&quot;id&quot;:&quot;124546d2-cf7e-4b64-a99d-2af2c047aaea&quot;,&quot;type&quot;:&quot;update&quot;} </code></pre> <p>So I need the full strings for further breakdown.</p> <p>I tried many things, Google, stackoverflow etc. I do can search the 'creationtime' but the rest is omitted whatever I try. I guess I need some kind of non-greedy RE? Anyhow - It just won't work for me.</p> <p>Anyone - some help would be highly appreciated.</p>
[ { "answer_id": 74574776, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "library(xml2)\nlibrary(purrr)\n\nxml <- read_xml('<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>')\n\nxml_ns(xml)\n# d1 <-> http://opendata.camara.cl/camaradiputados/v1\n# xsd <-> http://www.w3.org/2001/XMLSchema\n# xsi <-> http://www.w3.org/2001/XMLSchema-instance\n\n\nxml %>% xml_find_all(\".//d1:Voto\") %>% \n map_dfr(~ set_names(\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_text),\n .x %>% xml_child(\"d1:OpcionVoto\") %>% xml_text()),\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_name), \"OpcionVoto\")))\n\n# A tibble: 4 × 5\n# Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n# <chr> <chr> <chr> <chr> <chr> \n#1 810 Gabriel Ascencio Mansilla Afirmativo\n#2 855 Carlos Abel Jarpa Wevar Afirmativo\n#3 862 Pablo Lorenzini Basso En Contra \n#4 898 Gabriel Silber Romo Afirmativo\n" }, { "answer_id": 74575289, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "library(xml2)\nlibrary(dplyr)\nlibrary(tidyr)\n\nread_xml(xml_str) %>% \n xml_ns_strip() %>% \n xml_find_all(\"//Voto\") %>% \n as_list() %>% \n tibble(lst = .) %>% \n\n # A tibble: 4 × 1\n\n unnest_wider(lst) %>% \n\n # A tibble: 4 × 2\n # Diputado OpcionVoto\n # 1 <named list [4]> <list [1]>\n\n unnest_wider(\"Diputado\") %>% \n\n # A tibble: 4 × 5\n # Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n # <list> <list> <list> <list> <list> \n # 1 <list [1]> <list [1]> <list [1]> <list [1]> <list [1]> \n\n unnest_longer(everything())\n#> # A tibble: 4 × 5\n#> Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n#> <chr> <chr> <chr> <chr> <chr> \n#> 1 810 Gabriel Ascencio Mansilla Afirmativo\n#> 2 855 Carlos Abel Jarpa Wevar Afirmativo\n#> 3 862 Pablo Lorenzini Basso En Contra \n#> 4 898 Gabriel Silber Romo Afirmativo\n xml_str <- \n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>'\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018105/" ]
74,574,138
<p>When trying to install the npm packages using <strong>npm i</strong> command, I am getting the following exception:</p> <p><a href="https://i.stack.imgur.com/QXmje.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QXmje.png" alt="" /></a></p> <p>My angular versions</p> <blockquote> <p>Angular CLI: 14.0.6 Node: 16.15.0 Package Manager: npm 9.1.2</p> <p>Angular: 13.3.3</p> </blockquote> <p>Below is the package I want to install.</p> <blockquote> <p>npm i @ngx-translate/core</p> </blockquote> <p><a href="https://i.stack.imgur.com/ftqeZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ftqeZ.png" alt="" /></a></p>
[ { "answer_id": 74574776, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "library(xml2)\nlibrary(purrr)\n\nxml <- read_xml('<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>')\n\nxml_ns(xml)\n# d1 <-> http://opendata.camara.cl/camaradiputados/v1\n# xsd <-> http://www.w3.org/2001/XMLSchema\n# xsi <-> http://www.w3.org/2001/XMLSchema-instance\n\n\nxml %>% xml_find_all(\".//d1:Voto\") %>% \n map_dfr(~ set_names(\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_text),\n .x %>% xml_child(\"d1:OpcionVoto\") %>% xml_text()),\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_name), \"OpcionVoto\")))\n\n# A tibble: 4 × 5\n# Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n# <chr> <chr> <chr> <chr> <chr> \n#1 810 Gabriel Ascencio Mansilla Afirmativo\n#2 855 Carlos Abel Jarpa Wevar Afirmativo\n#3 862 Pablo Lorenzini Basso En Contra \n#4 898 Gabriel Silber Romo Afirmativo\n" }, { "answer_id": 74575289, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "library(xml2)\nlibrary(dplyr)\nlibrary(tidyr)\n\nread_xml(xml_str) %>% \n xml_ns_strip() %>% \n xml_find_all(\"//Voto\") %>% \n as_list() %>% \n tibble(lst = .) %>% \n\n # A tibble: 4 × 1\n\n unnest_wider(lst) %>% \n\n # A tibble: 4 × 2\n # Diputado OpcionVoto\n # 1 <named list [4]> <list [1]>\n\n unnest_wider(\"Diputado\") %>% \n\n # A tibble: 4 × 5\n # Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n # <list> <list> <list> <list> <list> \n # 1 <list [1]> <list [1]> <list [1]> <list [1]> <list [1]> \n\n unnest_longer(everything())\n#> # A tibble: 4 × 5\n#> Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n#> <chr> <chr> <chr> <chr> <chr> \n#> 1 810 Gabriel Ascencio Mansilla Afirmativo\n#> 2 855 Carlos Abel Jarpa Wevar Afirmativo\n#> 3 862 Pablo Lorenzini Basso En Contra \n#> 4 898 Gabriel Silber Romo Afirmativo\n xml_str <- \n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>'\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1624396/" ]
74,574,159
<p>I am trying to write a piece of code that would pull from my SQL column and create one button per value in that column. For example, if I have column A with &quot;test 1&quot;, &quot;test 2&quot;, and &quot;test 3&quot;, the code should produce three buttons which also hold the text from that value.</p> <p><img src="https://i.stack.imgur.com/yanRi.png" alt="enter image description here" /></p> <p>Here is what I have tried so far. This code only gives me one button and it is blank.</p> <pre><code> private void button7_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(@&quot;connstring&quot;); string strsql; strsql = &quot;SELECT buttonID from table1 &quot;; SqlCommand cmd = new SqlCommand(strsql, conn); SqlDataReader reader = null; cmd.Connection.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { Button newButton = new Button(); newButton.Text = reader[&quot;buttonID&quot;].ToString(); newButton.Location = new Point(1, 10); newButton.Size = new Size(100, 50); this.Controls.Add(newButton); } } </code></pre> <p><strong>UPDATE</strong> As mentioned in the comments, I had no way of naming my buttons, so I have added that function in. And as to why I was only seeing one button, I am assuming it is because all of the buttons are being created on top of each other, rather than displaying in rows or in columns.</p>
[ { "answer_id": 74574776, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "library(xml2)\nlibrary(purrr)\n\nxml <- read_xml('<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>')\n\nxml_ns(xml)\n# d1 <-> http://opendata.camara.cl/camaradiputados/v1\n# xsd <-> http://www.w3.org/2001/XMLSchema\n# xsi <-> http://www.w3.org/2001/XMLSchema-instance\n\n\nxml %>% xml_find_all(\".//d1:Voto\") %>% \n map_dfr(~ set_names(\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_text),\n .x %>% xml_child(\"d1:OpcionVoto\") %>% xml_text()),\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_name), \"OpcionVoto\")))\n\n# A tibble: 4 × 5\n# Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n# <chr> <chr> <chr> <chr> <chr> \n#1 810 Gabriel Ascencio Mansilla Afirmativo\n#2 855 Carlos Abel Jarpa Wevar Afirmativo\n#3 862 Pablo Lorenzini Basso En Contra \n#4 898 Gabriel Silber Romo Afirmativo\n" }, { "answer_id": 74575289, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "library(xml2)\nlibrary(dplyr)\nlibrary(tidyr)\n\nread_xml(xml_str) %>% \n xml_ns_strip() %>% \n xml_find_all(\"//Voto\") %>% \n as_list() %>% \n tibble(lst = .) %>% \n\n # A tibble: 4 × 1\n\n unnest_wider(lst) %>% \n\n # A tibble: 4 × 2\n # Diputado OpcionVoto\n # 1 <named list [4]> <list [1]>\n\n unnest_wider(\"Diputado\") %>% \n\n # A tibble: 4 × 5\n # Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n # <list> <list> <list> <list> <list> \n # 1 <list [1]> <list [1]> <list [1]> <list [1]> <list [1]> \n\n unnest_longer(everything())\n#> # A tibble: 4 × 5\n#> Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n#> <chr> <chr> <chr> <chr> <chr> \n#> 1 810 Gabriel Ascencio Mansilla Afirmativo\n#> 2 855 Carlos Abel Jarpa Wevar Afirmativo\n#> 3 862 Pablo Lorenzini Basso En Contra \n#> 4 898 Gabriel Silber Romo Afirmativo\n xml_str <- \n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>'\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20575215/" ]
74,574,168
<p>I have a list called marbles of 10.000 items (5000 blue and 5000 red)</p> <p>I want to do a test. To pick 4 random items from the list I do this</p> <pre class="lang-py prettyprint-override"><code>import random marbles = [&quot;RED&quot; for _ in range(5000)] + [&quot;BLUE&quot; for _ in range(5000)] A = random.choices(marbles, k=4) print(A) # this will print a list of 4 random Items from the list </code></pre> <p>What I need to do is to perform this test 100 times and print the results. I want to avoid creating 100 different variables and then print them all. What can I do to optimize and avoid &gt;100 lines of code. For loops? I would appreciate any input. Thank you in advance</p> <p>Nothing with my list seemed to have a problem.</p>
[ { "answer_id": 74574776, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "library(xml2)\nlibrary(purrr)\n\nxml <- read_xml('<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>')\n\nxml_ns(xml)\n# d1 <-> http://opendata.camara.cl/camaradiputados/v1\n# xsd <-> http://www.w3.org/2001/XMLSchema\n# xsi <-> http://www.w3.org/2001/XMLSchema-instance\n\n\nxml %>% xml_find_all(\".//d1:Voto\") %>% \n map_dfr(~ set_names(\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_text),\n .x %>% xml_child(\"d1:OpcionVoto\") %>% xml_text()),\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_name), \"OpcionVoto\")))\n\n# A tibble: 4 × 5\n# Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n# <chr> <chr> <chr> <chr> <chr> \n#1 810 Gabriel Ascencio Mansilla Afirmativo\n#2 855 Carlos Abel Jarpa Wevar Afirmativo\n#3 862 Pablo Lorenzini Basso En Contra \n#4 898 Gabriel Silber Romo Afirmativo\n" }, { "answer_id": 74575289, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "library(xml2)\nlibrary(dplyr)\nlibrary(tidyr)\n\nread_xml(xml_str) %>% \n xml_ns_strip() %>% \n xml_find_all(\"//Voto\") %>% \n as_list() %>% \n tibble(lst = .) %>% \n\n # A tibble: 4 × 1\n\n unnest_wider(lst) %>% \n\n # A tibble: 4 × 2\n # Diputado OpcionVoto\n # 1 <named list [4]> <list [1]>\n\n unnest_wider(\"Diputado\") %>% \n\n # A tibble: 4 × 5\n # Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n # <list> <list> <list> <list> <list> \n # 1 <list [1]> <list [1]> <list [1]> <list [1]> <list [1]> \n\n unnest_longer(everything())\n#> # A tibble: 4 × 5\n#> Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n#> <chr> <chr> <chr> <chr> <chr> \n#> 1 810 Gabriel Ascencio Mansilla Afirmativo\n#> 2 855 Carlos Abel Jarpa Wevar Afirmativo\n#> 3 862 Pablo Lorenzini Basso En Contra \n#> 4 898 Gabriel Silber Romo Afirmativo\n xml_str <- \n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>'\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19575159/" ]
74,574,170
<p>I have one endpoint, I have been testing with comand ubuntu, the endpoint require username and password, I run this:</p> <pre><code>curl --digest -u username:pass --location --request POST 'http://url' \ --header 'Content-Type: application/json' </code></pre> <p>so I just want run in node js usign <a href="https://www.npmjs.com/package/node-libcurl" rel="nofollow noreferrer">node-libcurl</a>, so I don't found the correct way to add digest authorization(username:pass), this code:</p> <pre><code>const { curly } = require('node-libcurl') exports.test = async () =&gt; { var user = 'user'; var pass = '45213'; var auth = new Buffer.alloc(user + ':' + pass).toString('base64'); const { data } = await curly.post('http://url', { postFields: JSON.stringify({ field: 'value' }), httpHeader: [ 'Content-Type: application/json', 'Accept: application/json', `Authorization: Basic + ${auth}` ], }) console.log(data); }; </code></pre> <p>using the node-libcurl library, is there a way to add authentication validation??... using username and password</p> <p>I'm receiving this error:</p> <p><code>TypeError [ERR_INVALID_ARG_TYPE]: The &quot;size&quot; argument must be of type number.</code></p>
[ { "answer_id": 74574776, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "library(xml2)\nlibrary(purrr)\n\nxml <- read_xml('<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>')\n\nxml_ns(xml)\n# d1 <-> http://opendata.camara.cl/camaradiputados/v1\n# xsd <-> http://www.w3.org/2001/XMLSchema\n# xsi <-> http://www.w3.org/2001/XMLSchema-instance\n\n\nxml %>% xml_find_all(\".//d1:Voto\") %>% \n map_dfr(~ set_names(\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_text),\n .x %>% xml_child(\"d1:OpcionVoto\") %>% xml_text()),\n c(.x %>% xml_child(\"d1:Diputado\") %>% xml_children() %>% map(xml_name), \"OpcionVoto\")))\n\n# A tibble: 4 × 5\n# Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n# <chr> <chr> <chr> <chr> <chr> \n#1 810 Gabriel Ascencio Mansilla Afirmativo\n#2 855 Carlos Abel Jarpa Wevar Afirmativo\n#3 862 Pablo Lorenzini Basso En Contra \n#4 898 Gabriel Silber Romo Afirmativo\n" }, { "answer_id": 74575289, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 3, "selected": true, "text": "library(xml2)\nlibrary(dplyr)\nlibrary(tidyr)\n\nread_xml(xml_str) %>% \n xml_ns_strip() %>% \n xml_find_all(\"//Voto\") %>% \n as_list() %>% \n tibble(lst = .) %>% \n\n # A tibble: 4 × 1\n\n unnest_wider(lst) %>% \n\n # A tibble: 4 × 2\n # Diputado OpcionVoto\n # 1 <named list [4]> <list [1]>\n\n unnest_wider(\"Diputado\") %>% \n\n # A tibble: 4 × 5\n # Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n # <list> <list> <list> <list> <list> \n # 1 <list [1]> <list [1]> <list [1]> <list [1]> <list [1]> \n\n unnest_longer(everything())\n#> # A tibble: 4 × 5\n#> Id Nombre ApellidoPaterno ApellidoMaterno OpcionVoto\n#> <chr> <chr> <chr> <chr> <chr> \n#> 1 810 Gabriel Ascencio Mansilla Afirmativo\n#> 2 855 Carlos Abel Jarpa Wevar Afirmativo\n#> 3 862 Pablo Lorenzini Basso En Contra \n#> 4 898 Gabriel Silber Romo Afirmativo\n xml_str <- \n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Votacion xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://opendata.camara.cl/camaradiputados/v1\">\n <Id>15446</Id>\n <Descripcion>Proyecto de Acuerdo N° 574</Descripcion>\n <Fecha>2012-06-13T14:47:29</Fecha>\n <TotalSi>12</TotalSi>\n <TotalNo>2</TotalNo>\n <TotalAbstencion>2</TotalAbstencion>\n <TotalDispensado>0</TotalDispensado>\n <Quorum Valor=\"1\">Quórum Simple</Quorum>\n <Resultado Valor=\"2\">Unánime</Resultado>\n <Tipo Valor=\"3\">Proyecto de Acuerdo</Tipo>\n <Votos>\n <Voto>\n <Diputado>\n <Id>810</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Ascencio</ApellidoPaterno>\n <ApellidoMaterno>Mansilla</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>855</Id>\n <Nombre>Carlos Abel</Nombre>\n <ApellidoPaterno>Jarpa</ApellidoPaterno>\n <ApellidoMaterno>Wevar</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>862</Id>\n <Nombre>Pablo</Nombre>\n <ApellidoPaterno>Lorenzini</ApellidoPaterno>\n <ApellidoMaterno>Basso</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"0\">En Contra</OpcionVoto>\n </Voto>\n <Voto>\n <Diputado>\n <Id>898</Id>\n <Nombre>Gabriel</Nombre>\n <ApellidoPaterno>Silber</ApellidoPaterno>\n <ApellidoMaterno>Romo</ApellidoMaterno>\n </Diputado>\n <OpcionVoto Valor=\"1\">Afirmativo</OpcionVoto>\n </Voto>\n </Votos>\n</Votacion>'\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19950248/" ]
74,574,176
<p>I have a really weird issue:</p> <pre><code>TS2322: Type '(arg0: Person[]) =&gt; void' is not assignable to type '(arg0: Person | Person[]) =&gt; void'. </code></pre> <p>Wtf is going on here? Function parameter union type tells that it can be a array or not, but doesn't work. Looks like <strong>typescript bug</strong>?</p> <p>This code calls it, error is shown on onAdd:</p> <pre><code>onAdd={(item: Person[]) =&gt; { const persons = item.map((el) =&gt; el.name); }} </code></pre> <p>And the type of onAdd is this:</p> <pre><code>onAdd?: (person: Person| Person[]) =&gt; void; </code></pre>
[ { "answer_id": 74574466, "author": "Nicholas Tower", "author_id": 3794812, "author_profile": "https://Stackoverflow.com/users/3794812", "pm_score": 2, "selected": false, "text": "onAdd?: (entity: Person| Person[]) => void;\n Person Person[] onAdd onAdd={(item: Person[]) => {\n const persons = item.map((el) => el.name);\n}}\n item .map onAdd={(item: Person | Person[]) => {\n const persons = Array.isArray(item) ? item.map(el => el.name) : [item.name];\n}}\n (entity: Person | Person[]) => void;" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16536899/" ]
74,574,207
<p>Let's consider multiple objects with overlapping keys, where each key indicates a week of the year and the values are objects of integer test results, like</p> <pre><code>const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } }; const cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } }; const xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } }; </code></pre> <p>What is an elegant way to merge them to a single object that contains all weeks as keys and the values as merged-objects, such that:</p> <pre><code>const merged_tests = { week1: { a: 4, b: 6, x: 1, y: 1 }, week2: { a: 0, b: 9, c: 2, d: 5 }, week3: { c: 6, d: 7 }, week4: { x: 100, y: 123 }, }; </code></pre>
[ { "answer_id": 74574284, "author": "Majed Badawi", "author_id": 7486313, "author_profile": "https://Stackoverflow.com/users/7486313", "pm_score": 2, "selected": false, "text": "Array#reduce Object#entries Array#forEach const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } };\nconst cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } };\nconst xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } };\n\nconst merged = [ab_tests, cd_tests, xy_tests].reduce((merged, current) => {\n Object.entries(current).forEach(([key, value]) => {\n merged[key] ??= {};\n merged[key] = { ...merged[key], ...value };\n });\n return merged;\n}, {});\n\nconsole.log(merged);" }, { "answer_id": 74574329, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "const\n merge = array => array.reduce((r, o) => Object\n .entries(o)\n .reduce((t, [k, q]) => {\n Object.assign(t[k] ??= {}, q);\n return t;\n }, r),\n {}),\n ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } },\n cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } },\n xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } },\n result = merge([ab_tests, cd_tests, xy_tests]);\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }" }, { "answer_id": 74574341, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 2, "selected": false, "text": "const inputs = [ab_tests, cd_tests, xy_tests],\n output = { }\n\nfor (const o of inputs) {\n for (const key in o)\n Object.assign(output[key] ??= {}, o[key])\n}\n const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } },\n cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } },\n xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } },\n inputs = [ab_tests, cd_tests, xy_tests],\n output = {}\n\nfor (const o of inputs) {\n for (const key in o)\n Object.assign(output[key] ??= {}, o[key])\n}\n\nconsole.log(output)" }, { "answer_id": 74575235, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function merge(...tests) {\n const entries = tests.flatMap(Object.entries);\n return entries.reduce(\n (merged, [week, values]) => Object.assign(merged, {\n [week]: {...merged[week], ...values}\n }), {});\n}\n\nconsole.log(merge(ab_tests, cd_tests, xy_tests));\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3879901/" ]
74,574,232
<p>Hello I have laravel project that store data created_at as a timestamp, I would call it from database, but it still show timestamp format, how can I convert it to date format without changing my column type? <a href="https://i.stack.imgur.com/CiTFR.png" rel="nofollow noreferrer">image</a></p> <p>here is my model:</p> <pre><code>public function getCreatedAtAttribute($value) { return Carbon::parse($value)-&gt;timestamp; } //fungsi untuk merubah format tanggal diubah ke timestamp public function getUpdatedAtAttribute($value) { return Carbon::parse($value)-&gt;timestamp; } </code></pre> <p>and how should I call it in view or .blade file?? Thank you</p>
[ { "answer_id": 74574284, "author": "Majed Badawi", "author_id": 7486313, "author_profile": "https://Stackoverflow.com/users/7486313", "pm_score": 2, "selected": false, "text": "Array#reduce Object#entries Array#forEach const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } };\nconst cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } };\nconst xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } };\n\nconst merged = [ab_tests, cd_tests, xy_tests].reduce((merged, current) => {\n Object.entries(current).forEach(([key, value]) => {\n merged[key] ??= {};\n merged[key] = { ...merged[key], ...value };\n });\n return merged;\n}, {});\n\nconsole.log(merged);" }, { "answer_id": 74574329, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "const\n merge = array => array.reduce((r, o) => Object\n .entries(o)\n .reduce((t, [k, q]) => {\n Object.assign(t[k] ??= {}, q);\n return t;\n }, r),\n {}),\n ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } },\n cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } },\n xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } },\n result = merge([ab_tests, cd_tests, xy_tests]);\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }" }, { "answer_id": 74574341, "author": "adiga", "author_id": 3082296, "author_profile": "https://Stackoverflow.com/users/3082296", "pm_score": 2, "selected": false, "text": "const inputs = [ab_tests, cd_tests, xy_tests],\n output = { }\n\nfor (const o of inputs) {\n for (const key in o)\n Object.assign(output[key] ??= {}, o[key])\n}\n const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } },\n cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } },\n xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } },\n inputs = [ab_tests, cd_tests, xy_tests],\n output = {}\n\nfor (const o of inputs) {\n for (const key in o)\n Object.assign(output[key] ??= {}, o[key])\n}\n\nconsole.log(output)" }, { "answer_id": 74575235, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 1, "selected": false, "text": "function merge(...tests) {\n const entries = tests.flatMap(Object.entries);\n return entries.reduce(\n (merged, [week, values]) => Object.assign(merged, {\n [week]: {...merged[week], ...values}\n }), {});\n}\n\nconsole.log(merge(ab_tests, cd_tests, xy_tests));\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16390014/" ]
74,574,269
<p>The following code</p> <pre><code>macro_rules! test { ( $( $x1:expr ),*; blub $( $x2:expr ),* ) =&gt; { $( println!(&quot;{} * {} = {}&quot;, $x1, $x2, $x1 * $x2); )* } } fn main() { test!{1, 2, 3; blub 4, 5, 6}; } </code></pre> <p>prints:</p> <pre><code>1 * 4 = 4 2 * 5 = 10 3 * 6 = 18 </code></pre> <p>However I want to loop over both lists seperately like a nested loop. It should print:</p> <pre><code>1 * 4 = 4 1 * 5 = 5 1 * 6 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 </code></pre> <p>How do I do that?</p>
[ { "answer_id": 74574564, "author": "Jeremy Meadows", "author_id": 13843935, "author_profile": "https://Stackoverflow.com/users/13843935", "pm_score": 2, "selected": true, "text": "x2 macro_rules! test {\n ( $($x1:expr ),*; blub $($x2:expr ),* ) => {\n for x1 in [$($x1),*] {\n for x2 in [$($x2),*] {\n println!(\"{} * {} = {}\", x1, x2, x1 * x2);\n }\n }\n }\n}\n\nfn main() {\n test!{1, 2, 3; blub 4, 5, 6};\n}\n" }, { "answer_id": 74574833, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 2, "selected": false, "text": "macro_rules! test {\n // secondary invocation with a `[]` delimited list of parameters\n // as the first arguments and a single second argument.\n ( [ $( $x1:expr),* ] ; $x2:expr ) => {\n $(\n println!(\"{:?} * {:?} = {:?}\", $x1, $x2, $x1 * $x2);\n )*\n };\n\n // the main invocation of the macro, takes a token tree `x1`\n // and a `[]` delimited `,` separated list of arguments for\n // each of which it calls itself again with `x1` as first\n // parameter and the element of the list as the second\n ( $x1:tt [ $( $x2:expr ),* ] ) => {\n $(\n test!($x1; $x2);\n )*\n };\n}\n\nfn main() {\n test!{\n [1, 2, 3]\n [4, 5, 6]\n };\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6235363/" ]
74,574,276
<p>The purpose of inheritance is to inherit and extend.</p> <p>So my question is that if child class have more method that will it break the LSP ? So in my example I have 2 classes Rectangle and Square. Square is child of Rectangle. Now both have 2 different methods HelloRectangle and HelloSquare. So will it breack LSP or not ?</p> <pre class="lang-cs prettyprint-override"><code>public class Rectangle { //public int Width { get; set; } //public int Height { get; set; } public virtual int Width { get; set; } public virtual int Height { get; set; } public Rectangle() { } public Rectangle(int width, int height) { Width = width; Height = height; } public override string ToString() { return $&quot;{nameof(Width)}: {Width}, {nameof(Height)}: {Height}&quot;; } public string HelloRectangle() { return &quot;Hello Rectangle&quot;; } } public class Square : Rectangle { public override int Width // nasty side effects { set { base.Width = base.Height = value; } } public override int Height { set { base.Width = base.Height = value; } } public string HelloSquare() { return &quot;Hello Square&quot;; } } </code></pre>
[ { "answer_id": 74574564, "author": "Jeremy Meadows", "author_id": 13843935, "author_profile": "https://Stackoverflow.com/users/13843935", "pm_score": 2, "selected": true, "text": "x2 macro_rules! test {\n ( $($x1:expr ),*; blub $($x2:expr ),* ) => {\n for x1 in [$($x1),*] {\n for x2 in [$($x2),*] {\n println!(\"{} * {} = {}\", x1, x2, x1 * x2);\n }\n }\n }\n}\n\nfn main() {\n test!{1, 2, 3; blub 4, 5, 6};\n}\n" }, { "answer_id": 74574833, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 2, "selected": false, "text": "macro_rules! test {\n // secondary invocation with a `[]` delimited list of parameters\n // as the first arguments and a single second argument.\n ( [ $( $x1:expr),* ] ; $x2:expr ) => {\n $(\n println!(\"{:?} * {:?} = {:?}\", $x1, $x2, $x1 * $x2);\n )*\n };\n\n // the main invocation of the macro, takes a token tree `x1`\n // and a `[]` delimited `,` separated list of arguments for\n // each of which it calls itself again with `x1` as first\n // parameter and the element of the list as the second\n ( $x1:tt [ $( $x2:expr ),* ] ) => {\n $(\n test!($x1; $x2);\n )*\n };\n}\n\nfn main() {\n test!{\n [1, 2, 3]\n [4, 5, 6]\n };\n}\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1466261/" ]
74,574,306
<p>I am trying to capture (S3) logs in a structured way. I am capturing the access-related elements with this type of tuple:</p> <pre class="lang-py prettyprint-override"><code>class _Access(NamedTuple): time: datetime ip: str actor: str request_id: str action: str key: str request_uri: str status: int error_code: str </code></pre> <p>I then have a class that uses this named tuple as follows (edited just down to relevant code):</p> <pre class="lang-py prettyprint-override"><code>class Logs: def __init__(self, log: str): raw_logs = match(S3_LOG_REGEX, log) if raw_logs is None: raise FormatError(log) logs = raw_logs.groups() timestamp = datetime.strptime(logs[2], &quot;%d/%b/%Y:%H:%M:%S %z&quot;) http_status = int(logs[9]) access = _Access( timestamp, logs[3], logs[4], logs[5], logs[6], logs[7], logs[8], http_status, logs[10], ) self.access = access </code></pre> <p>The problem is that it is too verbose when I now want to use it:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; log_struct = Logs(raw_log) &gt;&gt;&gt; log_struct.access.action # I don't want to have to add `access` </code></pre> <p>As I mention above, I'd rather be able to do something like this:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; log_struct = Logs(raw_log) &gt;&gt;&gt; log_struct.action </code></pre> <p>But I still want to have this clean named tuple called <code>_Access</code>. How can I make everything from <code>access</code> available at the top level?</p> <p>Specifically, I have this line:</p> <pre class="lang-py prettyprint-override"><code> self.access = access </code></pre> <p>which is giving me that extra &quot;layer&quot; that I don't want. I'd like to be able to &quot;unpack&quot; it somehow, similar to how we can unpack arguments by passing the star in <code>*args</code>. But I'm not sure how I can unpack the tuple in this case.</p>
[ { "answer_id": 74622433, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 3, "selected": true, "text": "NamedTuple __new__ ip action from typing import NamedTuple\n\nclass Logs(NamedTuple):\n ip: str\n action: str\n\n @classmethod\n def parse(cls, log: str) -> 'Logs':\n return cls.__new__(cls, *log.split())\n\nlog_struct = Logs.parse('192.168.1.1 GET')\nprint(log_struct)\nprint(log_struct.ip)\nprint(log_struct.action)\n Logs(ip='192.168.1.1', action='GET')\n192.168.1.1\nGET\n" }, { "answer_id": 74623091, "author": "flakes", "author_id": 3280538, "author_profile": "https://Stackoverflow.com/users/3280538", "pm_score": 1, "selected": false, "text": "_Access __getattr__ Logs __getattr__ def __getattr__(name: str) -> Any: ...\n object.__getattribute__ __getattr__ __dict__ AttributeError __getattr__ __getattr__ from typing import NamedTuple, Any\n\n\nclass _Access(NamedTuple):\n foo: str\n bar: str\n\n\nclass Logs:\n def __init__(self, log: str) -> None:\n self.log = log\n self.access = _Access(*log.split())\n\n def __getattr__(self, name: str) -> Any:\n return getattr(self.access, name)\n Logs Logs.access logs = Logs(\"fizz buzz\")\nprint(f\"{logs.log=}, {logs.foo=}, {logs.bar=}\")\n logs.log='fizz buzz', logs.foo='fizz', logs.bar='buzz'\n Logs Logs _Access class Logs:\n def __init__(self, log: str) -> None:\n self.log = log\n self.access = _Access(*log.split())\n\n @property\n def foo(self) -> str:\n return self.access.foo\n\n @property\n def bar(self) -> str:\n return self.access.bar\n Logs" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534238/" ]
74,574,333
<p>I've developed a simple game where I have an array of values and you need to guess it. When the value match, I show on a list using insertAdjacentHTML and appendChild. This is working very well. For example: Guess which countries already played a World Cup final.</p> <p>But in this case, the list is filled in order of right answers.</p> <p><a href="https://i.stack.imgur.com/FdhFH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FdhFH.png" alt="List filled with right answers (in order)" /></a></p> <p>I've wanted to upgrade this and display the answer on specific divs, so my idea is put the right answer on right order.</p> <p><a href="https://i.stack.imgur.com/s5XJL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s5XJL.jpg" alt="How I wanted" /></a></p> <p>I tried to study about data-set-attribute, but I don't know how to set the value typed on a specific div yet.</p> <p>For example, if I type Germany, I need to show the answer only on Germany answer div.</p> <p>Any ideas?</p> <p>Thank you so much!</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 validSearch = [ "Brazil", "Germany", "Italy", "Argentine", "France", "Uruguay", "England", "Spain", "Netherlands", "Tchechoslovachia", "Hungary", "Sweden", "Croatia", ]; function sendToPage() { //get value and trim for unnecesary spaces, and set variable var q = document.getElementById("search").value.trim(), re, result; //return if textbox is empty if (!q.length &gt; 0) { return; } //set RegExp (indexOf is faster but Case Sensitive) re = new RegExp(".*" + q.replace(/\s/g, "\\s") + ".*", "ig"); //start searching validSearch.some(function(v) { result = re.exec(v); if (result) { //Remove from array the right answers validSearch.splice(validSearch.indexOf(result[0]), 1); return true; } }); //if match if (result !== null) { var el = document.createElement("li"); el.classList = "respostas"; el.insertAdjacentHTML("beforeend", result[0]); var container = document.querySelector("#right-answers"); container.appendChild(el); } else { alert("Try Again! - " + q); } //refresh input box document.getElementById("search").value = ""; document.getElementById("search").focus(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="barra-widget"&gt; &lt;div&gt; &lt;button onclick="startTimer()" id="start"&gt;Start&lt;/button&gt; &lt;/div&gt; &lt;div class="guess-bar"&gt; &lt;div class="guess-bar-input"&gt; &lt;input id="search" type="text" name="text" placeholder="Insert Country Here" disabled&gt; &lt;button onclick="sendToPage()" id="guess" disabled&gt;Guess!&lt;/button&gt; &lt;/div&gt; &lt;div class="guess-timer"&gt; &lt;span id="count"&gt;90&lt;/span&gt; sec &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;ol id="right-answers"&gt;&lt;/ol&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74622433, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 3, "selected": true, "text": "NamedTuple __new__ ip action from typing import NamedTuple\n\nclass Logs(NamedTuple):\n ip: str\n action: str\n\n @classmethod\n def parse(cls, log: str) -> 'Logs':\n return cls.__new__(cls, *log.split())\n\nlog_struct = Logs.parse('192.168.1.1 GET')\nprint(log_struct)\nprint(log_struct.ip)\nprint(log_struct.action)\n Logs(ip='192.168.1.1', action='GET')\n192.168.1.1\nGET\n" }, { "answer_id": 74623091, "author": "flakes", "author_id": 3280538, "author_profile": "https://Stackoverflow.com/users/3280538", "pm_score": 1, "selected": false, "text": "_Access __getattr__ Logs __getattr__ def __getattr__(name: str) -> Any: ...\n object.__getattribute__ __getattr__ __dict__ AttributeError __getattr__ __getattr__ from typing import NamedTuple, Any\n\n\nclass _Access(NamedTuple):\n foo: str\n bar: str\n\n\nclass Logs:\n def __init__(self, log: str) -> None:\n self.log = log\n self.access = _Access(*log.split())\n\n def __getattr__(self, name: str) -> Any:\n return getattr(self.access, name)\n Logs Logs.access logs = Logs(\"fizz buzz\")\nprint(f\"{logs.log=}, {logs.foo=}, {logs.bar=}\")\n logs.log='fizz buzz', logs.foo='fizz', logs.bar='buzz'\n Logs Logs _Access class Logs:\n def __init__(self, log: str) -> None:\n self.log = log\n self.access = _Access(*log.split())\n\n @property\n def foo(self) -> str:\n return self.access.foo\n\n @property\n def bar(self) -> str:\n return self.access.bar\n Logs" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14868813/" ]
74,574,349
<p>Every time I need to train a 'large' deep learning model I do it from Google Collab, as it allows you to use GPU acceleration.</p> <p>My pc has a dedicated GPU, I was wondering if it is possible to use it to run my notebooks locally in a fast way. Is it possible to train models using my pc GPU? In that case, how?</p> <p>I am open to work with DataSpell, VSCode or any other IDE.</p>
[ { "answer_id": 74622433, "author": "blhsing", "author_id": 6890912, "author_profile": "https://Stackoverflow.com/users/6890912", "pm_score": 3, "selected": true, "text": "NamedTuple __new__ ip action from typing import NamedTuple\n\nclass Logs(NamedTuple):\n ip: str\n action: str\n\n @classmethod\n def parse(cls, log: str) -> 'Logs':\n return cls.__new__(cls, *log.split())\n\nlog_struct = Logs.parse('192.168.1.1 GET')\nprint(log_struct)\nprint(log_struct.ip)\nprint(log_struct.action)\n Logs(ip='192.168.1.1', action='GET')\n192.168.1.1\nGET\n" }, { "answer_id": 74623091, "author": "flakes", "author_id": 3280538, "author_profile": "https://Stackoverflow.com/users/3280538", "pm_score": 1, "selected": false, "text": "_Access __getattr__ Logs __getattr__ def __getattr__(name: str) -> Any: ...\n object.__getattribute__ __getattr__ __dict__ AttributeError __getattr__ __getattr__ from typing import NamedTuple, Any\n\n\nclass _Access(NamedTuple):\n foo: str\n bar: str\n\n\nclass Logs:\n def __init__(self, log: str) -> None:\n self.log = log\n self.access = _Access(*log.split())\n\n def __getattr__(self, name: str) -> Any:\n return getattr(self.access, name)\n Logs Logs.access logs = Logs(\"fizz buzz\")\nprint(f\"{logs.log=}, {logs.foo=}, {logs.bar=}\")\n logs.log='fizz buzz', logs.foo='fizz', logs.bar='buzz'\n Logs Logs _Access class Logs:\n def __init__(self, log: str) -> None:\n self.log = log\n self.access = _Access(*log.split())\n\n @property\n def foo(self) -> str:\n return self.access.foo\n\n @property\n def bar(self) -> str:\n return self.access.bar\n Logs" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14973688/" ]
74,574,356
<p>I have multiple txt files and I would like to convert them to a dataframe by creating a new column using header. My data looks like:</p> <pre><code>Person:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.? 144 cm/35 Kg/5 YearsOld 45,34,22,26,0 78,74,82,11,0 </code></pre> <p>I use the following code to create a dataframe out of a single text file.</p> <pre><code>with open('file_directory', 'r') as f: heading_rows = [next(f) for _ in range(3)] city = re.findall(pattern = ' \w+ ', string = heading_rows[0])[0].strip() numbers_list = [re.findall(pattern='\d+', string=row) for row in heading_rows if 'cm' and 'kg' in row.lower()][0] height, weight, age = [int(numbers_list[i]) for i in range(3)] df = pd.read_csv('file_directory', sep='\s+|;|,', engine='python', skiprows=8,comment='cm', index_col=None, names=list('ABCDEF')) #df.dropna(inplace=True) df['HEIGHT'] = height df['WEIGHT'] = weight df['AGE'] = age df['CENTER'] = city </code></pre> <p>I tried to put the code (above) in a for loop so that I can read all text files in the folder so that I can convert them into a Pandas dataframe individually and save as a csv file.</p> <pre><code>lst = [] for name in glob.glob('my_directory/*'): with open(name, 'r') as f: heading_rows = [next(f) for _ in range(1)] lst.append(heading_rows) </code></pre> <p>Bu, I end up with StopIteration error in next(f) aprt of my code. How can I obtain the following dataframe while reading multiple text files? Then I would like to save each file as CSV file.</p> <p>My <strong>expectation</strong> is to have the following dataframe type:</p> <pre><code>A, B, C, D, E, height, weight, age, city 45,34,22,26,0, 144, 35, 5, NewYork 78,74,82,11,0, 144, 35, 5, NewYork </code></pre>
[ { "answer_id": 74578306, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 0, "selected": false, "text": "import re\nimport pandas as pd\n\n\ntext = \"\"\"\\\nPerson:?,?;F dob. ? MT: ? Z:C NewYork Mon.:S St.?\n\n144 cm/35 Kg/5 YearsOld\n\n\n45,34,22,26,0\n78,74,82,11,0\n\"\"\"\n\npat = re.compile(\n r\"(?sim)Z:C (\\S+).*(\\d+)\\s*cm\\D+(\\d+)\\s*kg\\D+(\\d+).*?((?:^[\\d,]+\\n)+)\"\n)\n\nm = pat.search(text)\nif m:\n city, height, weight, age, data = m.groups()\n all_data = []\n for row in data.splitlines():\n all_data.append(\n list(map(int, row.split(\",\"))) + [height, weight, age, city]\n )\n\ndf = pd.DataFrame(\n all_data,\n columns=[\"A\", \"B\", \"C\", \"D\", \"E\", \"height\", \"weight\", \"age\", \"city\"],\n)\nprint(df)\n A B C D E height weight age city\n0 45 34 22 26 0 4 35 5 NewYork\n1 78 74 82 11 0 4 35 5 NewYork\n" }, { "answer_id": 74601082, "author": "mahmutoezmen", "author_id": 10570703, "author_profile": "https://Stackoverflow.com/users/10570703", "pm_score": 2, "selected": true, "text": "import chardet\nfor name in glob.glob('file_directory/*'):\n with open(name, 'r') as f:\n heading_rows = [next(f) for _ in range(5)]\n #print(re.findall(pattern = ' \\w+ ', string = heading_rows[0])[0])\n\n# to escape errors\n try:\n city = re.findall(pattern = ' \\w+ ', string = heading_rows[0])[0].strip()\n except IndexError:\n pass\n\n numbers_list = [re.findall(pattern='\\d+', string=row) for row in heading_rows if 'cm' and 'kg' in row.lower()][0]\n\n height, weight, age = [int(numbers_list[i]) for i in range(3)]\n\n with open(name, 'rb') as file:\n encodings = chardet.detect(file.read())[\"encoding\"]\n df = pd.read_csv(name,sep='\\s+|;|,', engine='python', encoding=encodings, skiprows=1,comment='cm', index_col=None, names=list('ABCDEF'))\n\n\n df.to_csv(name+'.csv',index=False)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19948301/" ]
74,574,371
<p>I am a noobie programmer, using MAC OS and Visual Studio Code trying to build a responsive fitness routine in HTML for personal use, as a personal project.</p> <p>I am trying to get all my buttons to turn green on click, the first one is turning green fine, but the rest are not. I have uploaded a code pen here: <a href="https://codepen.io/3991chris/full/OJEZwKL" rel="nofollow noreferrer">https://codepen.io/3991chris/full/OJEZwKL</a></p> <p>Any help would be awesome!</p> <p>I tried</p> <pre><code>let btnDone = document.querySelectorAll('#done'); </code></pre>
[ { "answer_id": 74574490, "author": "Rory McCrossan", "author_id": 519413, "author_profile": "https://Stackoverflow.com/users/519413", "pm_score": 1, "selected": false, "text": "#done id class querySelectorAll('.done') toggle() removeClickHandler() document.querySelectorAll('.done').forEach(btn => {\n btn.addEventListener('click', e => e.target.classList.toggle('active'));\n}); table {\n font-family: arial, sans-serif;\n border-collapse: collapse;\n width: 100%;\n}\n\ntd,\nth {\n border: 1px solid #dddddd;\n text-align: left;\n padding: 8px;\n}\n\ntr:nth-child(even) {\n background-color: #dddddd;\n}\n\n.card {\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);\n max-width: 300px;\n margin: auto;\n text-align: center;\n font-family: arial;\n}\n\n.btn {\n display: flex;\n justify-content: center;\n}\n\n.btn .done.active {\n background-color: #4cae4c;\n}\n\nbutton {\n padding: 10px 20px;\n margin: 5px;\n background-color: black;\n color: #fff;\n border: none;\n border-radius: 5px;\n}\n\n.topnav {\n overflow: hidden;\n background-color: blue;\n flex-wrap: wrap;\n}\n\n.topnav a {\n float: left;\n color: white;\n text-align: center;\n padding: 14px 16px;\n text-decoration: none;\n font-size: 17px;\n}\n\n.topnav a:hover {\n background-color: red;\n color: white;\n}\n\n.topnav a.active {\n background-color: red;\n color: white;\n} <div class=\"card\">\n <div class=\"topnav\">\n <a href=\"index.html\">Home</a>\n <a href=\"arm day a.html\">A</a>\n <a href=\"leg day b.html\">B</a>\n <a href=\"ab & chest day c.html\">C</a>\n <a class=\"active\" href=\"leg day d.html\">D</a>\n <a href=\"arm day e.html\">E</a>\n </div>\n <h1>Leg Day D</h1>\n <div class=\"card\">\n <img src=\"images/deadlift.jpeg\" style=\"width:100%\">\n <h1>1. Deadlift</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back<br> hip stiff</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 8</td>\n <td>60 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 8</td>\n <td>65 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 8</td>\n <td>70 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 8</td>\n <td>75 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/sumosquat.png\" style=\"width:100%\">\n <h1>2. SumoSquats</h1>\n <p>Feet at 45 angle, wide legs,<br> make sure back straight</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 10</td>\n <td>70 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 10</td>\n <td>75 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 10</td>\n <td>80 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 10</td>\n <td>85 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/flexora.webp\" style=\"width:100%\">\n <h1>3. Flex Chair</h1>\n <p>alig knees with chair, <br> keep back on seat</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 10</td>\n <td>70 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 10</td>\n <td>75 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 10</td>\n <td>75 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 10</td>\n <td>70 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/stepups.png\" style=\"width:100%\">\n <h1>4. StepUps</h1>\n <p>Use bench or box <br> and do 10 each leg,<br> up and down same leg</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 20</td>\n <td>15 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 20</td>\n <td>20 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 20</td>\n <td>20 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 20</td>\n <td>25 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/adutora.webp\" style=\"width:100%\">\n <h1>5. Adutora</h1>\n <p>Stretch to allow wider leg</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 10</td>\n <td>Max kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 10</td>\n <td>Max kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 10</td>\n <td>Max kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 10</td>\n <td>Max kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/pelvicthrust.jpeg\" style=\"width:100%\">\n <h1>6. Pelvic Thrust</h1>\n <p>Top of shoulders and chest<br>should be on bench</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 10</td>\n <td>70 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 10</td>\n <td>75 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 10</td>\n <td>80 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 10</td>\n <td>80 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/gemeossentado.webp\" style=\"width:100%\">\n <h1>7. Seated Calf Raise</h1>\n <p>Make sure to go slow</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 10</td>\n <td>60 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 10</td>\n <td>65 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 10</td>\n <td>65 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 10</td>\n <td>70 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/landminesquat.webp\" style=\"width:100%\">\n <h1>8. Landmine Squat</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 8</td>\n <td>40 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 8</td>\n <td>45 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 8</td>\n <td>50 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 8</td>\n <td>55 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/pullthrough.webp\" style=\"width:100%\">\n <h1>9. Pull Through</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 8</td>\n <td>20 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 8</td>\n <td>30 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 8</td>\n <td>35 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 8</td>\n <td>40 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <img src=\"images/liedownlegcurl.jpeg\" style=\"width:100%\">\n <h1>10. Lie Down Leg Curl</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back</p>\n <div class=\"btn\">\n <button class=\"done\">Done</button>\n </div>\n <table>\n <tr>\n <th>Week</th>\n <th>Set X Rep</th>\n <th>Weight</th>\n </tr>\n <tr>\n <td>1</td>\n <td>4 * 8</td>\n <td>50 kg</td>\n </tr>\n <tr>\n <td>2</td>\n <td>5 * 8</td>\n <td>55 kg</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5 * 8</td>\n <td>60 kg</td>\n </tr>\n <tr>\n <td>4</td>\n <td>4 * 8</td>\n <td>65 kg</td>\n </tr>\n </table>\n </div>\n</div>" }, { "answer_id": 74575233, "author": "wildan maulana", "author_id": 20570652, "author_profile": "https://Stackoverflow.com/users/20570652", "pm_score": -1, "selected": false, "text": "$(document).ready(function () {\n $(\"div div button\").click(function () {\n $(this).addClass(\"activeButton\");\n });\n}); table {\n font-family: arial, sans-serif;\n border-collapse: collapse;\n width: 100%;\n}\n\ntd,\nth {\n border: 1px solid #dddddd;\n text-align: left;\n padding: 8px;\n}\n\ntr:nth-child(even) {\n background-color: #dddddd;\n}\n\n.card {\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);\n max-width: 300px;\n margin: auto;\n text-align: center;\n font-family: arial;\n}\n\n.btn {\n display: flex;\n justify-content: center;\n}\n\nbutton {\n padding: 10px 20px;\n margin: 5px;\n background-color: black;\n color: #fff;\n border: none;\n border-radius: 5px;\n}\n.topnav {\n overflow: hidden;\n background-color: blue;\n flex-wrap: wrap;\n}\n\n.topnav a {\n float: left;\n color: white;\n text-align: center;\n padding: 14px 16px;\n text-decoration: none;\n font-size: 17px;\n}\n\n.topnav a:hover {\n background-color: red;\n color: white;\n}\n\n.topnav a.active {\n background-color: red;\n color: white;\n}\n\n.activeButton {\n background-color: #4cae4c;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js\" integrity=\"sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==\" crossorigin=\"anonymous\" referrerpolicy=\"no-referrer\"></script>\n\n\n<div class=\"card\">\n <div class=\"topnav\">\n <a href=\"index.html\">Home</a>\n <a href=\"arm day a.html\">A</a>\n <a href=\"leg day b.html\">B</a>\n <a href=\"ab & chest day c.html\">C</a>\n <a class=\"active\" href=\"leg day d.html\">D</a>\n <a href=\"arm day e.html\">E</a>\n </div>\n </div>\n\n <div class=\"card\">\n <h1>Day 1</h1>\n <img src=\"images/deadlift.jpeg\" style=\"width:100%\">\n <h1>1. Deadlift</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back<br> hip stiff</p>\n <div id=\"btn\">\n <button id=\"done\" class=\"\">Done</button>\n </div>\n\n <table>\n <tr>\n <th>Week</th> <th>Set X Rep</th> <th>Weight</th>\n </tr>\n <tr>\n <td>1</td> <td>4 * 8</td> <td>60 kg</td>\n </tr>\n <tr>\n <td>2</td> <td>5 * 8</td> <td>65 kg</td>\n </tr>\n <tr>\n <td>3</td> <td>5 * 8</td> <td>70 kg</td>\n </tr>\n <tr>\n <td>4</td> <td>4 * 8</td> <td>75 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <h1>Day 2</h1>\n <img src=\"images/deadlift.jpeg\" style=\"width:100%\">\n <h1>1. Push Up</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back<br> hip stiff</p>\n <div id=\"btn\">\n <button id=\"done\" class=\"\">Done</button>\n </div>\n\n <table>\n <tr>\n <th>Week</th> <th>Set X Rep</th> <th>Weight</th>\n </tr>\n <tr>\n <td>1</td> <td>4 * 8</td> <td>60 kg</td>\n </tr>\n <tr>\n <td>2</td> <td>5 * 8</td> <td>65 kg</td>\n </tr>\n <tr>\n <td>3</td> <td>5 * 8</td> <td>70 kg</td>\n </tr>\n <tr>\n <td>4</td> <td>4 * 8</td> <td>75 kg</td>\n </tr>\n </table>\n </div>\n\n <div class=\"card\">\n <h1>Day 3</h1>\n <img src=\"images/deadlift.jpeg\" style=\"width:100%\">\n <h1>1. Jump</h1>\n <p>Feet at 45 angle, back straight,<br>shoulders back<br> hip stiff</p>\n <div id=\"btn\">\n <button id=\"done\" class=\"\">Done</button>\n </div>\n\n <table>\n <tr>\n <th>Week</th> <th>Set X Rep</th> <th>Weight</th>\n </tr>\n <tr>\n <td>1</td> <td>4 * 8</td> <td>60 kg</td>\n </tr>\n <tr>\n <td>2</td> <td>5 * 8</td> <td>65 kg</td>\n </tr>\n <tr>\n <td>3</td> <td>5 * 8</td> <td>70 kg</td>\n </tr>\n <tr>\n <td>4</td> <td>4 * 8</td> <td>75 kg</td>\n </tr>\n </table>\n </div>" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549509/" ]
74,574,377
<p><strong>Environment:</strong> I'm using Databricks with spark 3.3.0 and Python 3.</p> <p><strong>Problem trying to solve:</strong> I'm trying to replace some of the attribute values of a json struct column. I have a dataframe that contains a struct type column that has the following json content structure:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>myCol</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>{&quot;att1&quot;: &quot;abcde&quot;, &quot;att2&quot;: &quot;def&quot;, &quot;att3&quot;: &quot;defg&quot;, &quot;att4&quot;: &quot;defabc&quot;}</td> </tr> <tr> <td>2</td> <td>{&quot;att1&quot;: &quot;xyfp&quot;, &quot;att2&quot;: &quot;asdf&quot;, &quot;att3&quot;: &quot;ertyui&quot;, &quot;att4&quot;: &quot;asdfg&quot;}</td> </tr> <tr> <td>3</td> <td>{&quot;att1&quot;: &quot;fjhj&quot;, &quot;att2&quot;: &quot;zxcxzvc&quot;, &quot;att3&quot;: &quot;wtwert&quot;, &quot;att4&quot;: &quot;mjgkj&quot;}</td> </tr> </tbody> </table> </div> <p>The dataframe contains thousands of records, I'm a bit new to spark programming so I've been having a hard time to come up with a way to replace the values of &quot;att1&quot; and &quot;att3&quot; in all rows in the dataframe with the same value but leaving only the first two characters and masking the rest, i.e from the example above:</p> <p>Expected Output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>myCol</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>{&quot;att1&quot;: &quot;ab---&quot;, &quot;att2&quot;: &quot;def&quot;, &quot;att3&quot;: &quot;de--&quot;, &quot;att4&quot;: &quot;defabc&quot;}</td> </tr> <tr> <td>2</td> <td>{&quot;att1&quot;: &quot;xy--&quot;, &quot;att2&quot;: &quot;asdf&quot;, &quot;att3&quot;: &quot;er----&quot;, &quot;att4&quot;: &quot;asdfg&quot;}</td> </tr> <tr> <td>3</td> <td>{&quot;att1&quot;: &quot;fj--&quot;, &quot;att2&quot;: &quot;zxcxzvc&quot;, &quot;att3&quot;: &quot;wt----&quot;, &quot;att4&quot;: &quot;mjgkj&quot;}</td> </tr> </tbody> </table> </div> <p>I was looking into maybe using <code>org.apache.spark.sql.functions.regexp_replace</code> but i don't know how to replace only part of the value, i.e from <code>&quot;abcde&quot;</code> to <code>&quot;ab---&quot;</code>, i've looked at similar examples online except every single one of them replaces the entire value and the value is known beforehand such as this one <a href="https://stackoverflow.com/a/68899109/1994202">https://stackoverflow.com/a/68899109/1994202</a>, however, i need to leave the first two original characters and the value is not static.</p> <p>Any suggestions? performance would also be important</p>
[ { "answer_id": 74585772, "author": "Kombajn zbożowy", "author_id": 2890093, "author_profile": "https://Stackoverflow.com/users/2890093", "pm_score": 3, "selected": true, "text": "(?<=..). df.withColumn(\"myCol\", col(\"myCol\").withField(\"att1\", regexp_replace(col(\"myCol.att1\"), \"(?<=..).\", \"-\"))\n .withField(\"att3\", regexp_replace(col(\"myCol.att3\"), \"(?<=..).\", \"-\"))).show()\n" }, { "answer_id": 74600632, "author": "Banu", "author_id": 7241100, "author_profile": "https://Stackoverflow.com/users/7241100", "pm_score": 0, "selected": false, "text": " from pyspark.sql.types import *\n data = [\n (1, {\"att1\": \"abcde\", \"att2\": \"def\", \"att3\": \"defg\", \"att4\": \"defabc\"}),\n (2, {\"att1\": \"xyfp\", \"att2\": \"asdf\", \"att3\": \"ertyui\", \"att4\": \"asdfg\"}),\n (3, {\"att1\": \"fjhj\", \"att2\": \"zxcxzvc\", \"att3\": \"wtwert\", \"att4\": \"mjgkj\"})\n ]\n\n schema = StructType([\n StructField(\"ID\",IntegerType(), True),\n StructField('myCol', MapType(StringType(),StringType()),True)\n ])\n\n\n df = spark.createDataFrame(data,schema = schema)\n df.show(truncate=False)\n df.withColumn('myCol',create_map\n (\n lit('att1'),regexp_replace(col(\"myCol.att1\"), \"(?<=..).\", \"-\"),\n lit('att2'),col(\"myCol.att2\"),\n lit('att3'),regexp_replace(col(\"myCol.att3\"), \"(?<=..).\", \"-\"),\n lit('att4'),col(\"myCol.att4\"),\n )\n ).show(truncate=False)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1994202/" ]
74,574,381
<p>I am trying to create a view to fetch data from a bucket by excluding certain folders inside S3 on Hive. I was able to successfully create view on Athena, but couldn't do the same on Hive.</p> <p><strong>Athena View:</strong></p> <pre><code>CREATE VIEW test as SELECT * FROM TABLE_A WHERE NOT (&quot;$PATH LIKE '%PASSENGER_DATA%') AND NOT (&quot;$PATH LIKE '%CUSTOMER_DATA%'); </code></pre> <p>Could you please advise how the same could be achieved on Hive?</p>
[ { "answer_id": 74585772, "author": "Kombajn zbożowy", "author_id": 2890093, "author_profile": "https://Stackoverflow.com/users/2890093", "pm_score": 3, "selected": true, "text": "(?<=..). df.withColumn(\"myCol\", col(\"myCol\").withField(\"att1\", regexp_replace(col(\"myCol.att1\"), \"(?<=..).\", \"-\"))\n .withField(\"att3\", regexp_replace(col(\"myCol.att3\"), \"(?<=..).\", \"-\"))).show()\n" }, { "answer_id": 74600632, "author": "Banu", "author_id": 7241100, "author_profile": "https://Stackoverflow.com/users/7241100", "pm_score": 0, "selected": false, "text": " from pyspark.sql.types import *\n data = [\n (1, {\"att1\": \"abcde\", \"att2\": \"def\", \"att3\": \"defg\", \"att4\": \"defabc\"}),\n (2, {\"att1\": \"xyfp\", \"att2\": \"asdf\", \"att3\": \"ertyui\", \"att4\": \"asdfg\"}),\n (3, {\"att1\": \"fjhj\", \"att2\": \"zxcxzvc\", \"att3\": \"wtwert\", \"att4\": \"mjgkj\"})\n ]\n\n schema = StructType([\n StructField(\"ID\",IntegerType(), True),\n StructField('myCol', MapType(StringType(),StringType()),True)\n ])\n\n\n df = spark.createDataFrame(data,schema = schema)\n df.show(truncate=False)\n df.withColumn('myCol',create_map\n (\n lit('att1'),regexp_replace(col(\"myCol.att1\"), \"(?<=..).\", \"-\"),\n lit('att2'),col(\"myCol.att2\"),\n lit('att3'),regexp_replace(col(\"myCol.att3\"), \"(?<=..).\", \"-\"),\n lit('att4'),col(\"myCol.att4\"),\n )\n ).show(truncate=False)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11252662/" ]
74,574,390
<p>Im writting a simple python application where the user selects a file from their local file manager and tries to upload using strealit</p> <p>Im able to succesfully take the file the user had given using streamlit.uploader and stored the file in a temp directory from the stramlit app folder but the issue is i cant give the path of the file of the file stored in the newly created directory in order to send the application into my gcp clouds bucket</p> <p>Adding my snippet below any help is appreciated :)</p> <pre><code> import streamlit as st from google.oauth2 import service_account from google.cloud import storage import os from os import listdir from os.path import isfile, join from pathlib import Path from PIL import Image, ImageOps bucketName=('survey-appl-dev-public') # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets[&quot;gcp_service_account&quot;] ) client = storage.Client(credentials=credentials) #create a bucket object to get bucket details bucket = client.get_bucket(bucketName) file = st.file_uploader(&quot;Upload An file&quot;) def main(): if file is not None: file_details = {&quot;FileName&quot;:file.name,&quot;FileType&quot;:file.type} st.write(file_details) #img = load_image(image_file) #st.image(img, caption='Sunrise by the mountains') with open(os.path.join(&quot;tempDir&quot;,file.name),&quot;wb&quot;) as f: f.write(file.getbuffer()) st.success(&quot;Saved File&quot;) object_name_in_gcs_bucket = bucket.blob(&quot;.&quot;,file.name) object_name_in_gcs_bucket.upload_from_filename(&quot;tempDir&quot;,file.name) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>ive tried importing the path of the file using cwd command and also tried os library for file path but nothing worked</p> <p>edited: All i wanted to implement is make a file upload that is selected by customer using the dropbox of file_uploader option im able to save the file into a temporary directory after the file is selected using the file.getbuffer as shown in the code but i couldnt amke the code uploaded into the gcs bucket since its refering as str cannnot be converted into int while i press the upload button may be its the path issue &quot;the code is unable to find the path of the file stored in the temp directory &quot; but im unable to figure iut how to give the path to the upload function</p> <pre><code>error coding im facing TypeError: '&gt;' not supported between instances of 'str' and 'int' Traceback: File &quot;/home/raviteja/.local/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py&quot;, line 564, in _run_script exec(code, module.__dict__) File &quot;/home/raviteja/test/streamlit/test.py&quot;, line 43, in &lt;module&gt; main() File &quot;/home/raviteja/test/streamlit/test.py&quot;, line 29, in main object_name_in_gcs_bucket = bucket.blob(&quot;.&quot;,file.name) File &quot;/home/raviteja/.local/lib/python3.10/site-packages/google/cloud/storage/bucket.py&quot;, line 795, in blob return Blob( File &quot;/home/raviteja/.local/lib/python3.10/site-packages/google/cloud/storage/blob.py&quot;, line 219, in __init__ self.chunk_size = chunk_size # Check that setter accepts value. File &quot;/home/raviteja/.local/lib/python3.10/site-packages/google/cloud/storage/blob.py&quot;, line 262, in chunk_size if value is not None and value &gt; 0 and value % self._CHUNK_SIZE_MULTIPLE != 0: </code></pre>
[ { "answer_id": 74575900, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 0, "selected": false, "text": "def main():\n file = st.file_uploader(\"Upload file\")\n if file is not None:\n file_details = {\"FileName\":file.name,\"FileType\":file.type}\n st.write(file_details)\n \n file_path = os.path.join(\"tempDir/\", file.name)\n with open(file_path,\"wb\") as f: \n f.write(file.getbuffer()) \n st.success(\"Saved File\")\n\n print(file_path)\n\n\n def upload():\n file_name = file_path\n read_file(file_name)\n st.write(file_name)\n\n st.session_state[\"upload_state\"] = \"Saved successfully!\"\n object_name_in_gcs_bucket = bucket.blob(\"gcp-bucket-destination-path\"+ file.name)\n object_name_in_gcs_bucket.upload_from_filename(file_path)\n \n st.write(\"Youre uploading to bucket\", bucketName)\n st.button(\"Upload file to GoogleCloud\", on_click=upload)\n\n\nif __name__ == \"__main__\":\n main() \n" }, { "answer_id": 74609119, "author": "ferdy", "author_id": 17197068, "author_profile": "https://Stackoverflow.com/users/17197068", "pm_score": 0, "selected": false, "text": "import streamlit as st\nfrom google.oauth2 import service_account\nfrom google.cloud import storage\nimport os\n\nSTREAMLIT_SCRIPT_FILE_PATH = os.path.dirname(os.path.abspath(__file__))\n\ncredentials = service_account.Credentials.from_service_account_info(\n st.secrets[\"gcp_service_account\"]\n)\nclient = storage.Client(credentials=credentials)\n\ndef main():\n bucketName = 'survey-appl-dev-public'\n file = st.file_uploader(\"Upload file\")\n if file is not None:\n file_details = {\"FileName\":file.name,\"FileType\":file.type}\n st.write(file_details)\n\n with open(os.path.join(\"tempDir\", file.name), \"wb\") as f:\n f.write(file.getbuffer())\n\n st.success(\"Saved File\")\n\n bucket = client.bucket(bucketName)\n object_name_in_gcs_bucket = bucket.blob(file.name)\n\n # src_relative = f'./tempDir/{file.name}' # also works\n src_absolute = f'{STREAMLIT_SCRIPT_FILE_PATH}/tempDir/{file.name}'\n object_name_in_gcs_bucket.upload_from_filename(src_absolute)\n\nif __name__ == '__main__':\n main()\n upload_from_string() credentials = service_account.Credentials.from_service_account_info(\n st.secrets[\"gcp_service_account\"]\n)\nclient = storage.Client(credentials=credentials)\n\ndef gcs_upload_data():\n bucket_name = 'your_gcs_bucket_name'\n\n file = st.file_uploader(\"Upload file\")\n if file is not None:\n fname = file.name\n ftype = file.type\n\n file_details = {\"FileName\":fname,\"FileType\":ftype}\n st.write(file_details)\n\n # Define gcs bucket.\n bucket = client.bucket(bucket_name)\n bblob = bucket.blob(fname)\n\n # Upload the bytes directly instead of a disk file.\n bblob.upload_from_string(file.getvalue(), ftype)\n\nif __name__ == '__main__':\n gcs_upload_data()\n" }, { "answer_id": 74610901, "author": "tarunratan", "author_id": 18098873, "author_profile": "https://Stackoverflow.com/users/18098873", "pm_score": 1, "selected": false, "text": " object_name_in_gcs_bucket = bucket.blob(\"path-to-upload\"+file.name)\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18098873/" ]
74,574,422
<p>by mistake I pushed to main branch my code, it was an empty project so main branch didn't have any commit</p> <p>I need move the pushed commits to the main branch to another branch and keep the main branch as empty or at least with just a new readme file (the initial main branch was totally empty so no readme nor any other file) to make matters worse, the initial commit pushed to the main branch already contains code and not just a readme</p> <p>My idea was renaming the branches but because main branch didn't have any initial commit I cannot restore to that state, I think that a cherry pick could not work neither for the same reason</p> <p>is there an easy way to achieve this in a clear way? by the way, there are not other contributors in the project right now so restart the branch hopefully will not cause any trouble... thank guys!</p>
[ { "answer_id": 74574571, "author": "j6t", "author_id": 6868543, "author_profile": "https://Stackoverflow.com/users/6868543", "pm_score": 2, "selected": true, "text": "git checkout --orphan new-branch\n new-branch git add README.txt\ngit commit\n new-branch git branch -m main old-main\ngit branch -m new-branch main\n main" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050817/" ]
74,574,438
<p>I have a list of 0s, named &quot;variables&quot;. One of the 0s will become -1 spontaneously, and I'm trying to print the element which does. For example, this is my code:</p> <pre><code>while True: if any(variables): print(variables[i]) </code></pre> <p>Now, obviously &quot;i&quot; doesn't correlate to anything, but I'd like it to represent the index of the non-zero variable in the list &quot;variables&quot;. Should I enumerate? Is there an easy way to do this with list comprehension? Thank you!</p>
[ { "answer_id": 74574571, "author": "j6t", "author_id": 6868543, "author_profile": "https://Stackoverflow.com/users/6868543", "pm_score": 2, "selected": true, "text": "git checkout --orphan new-branch\n new-branch git add README.txt\ngit commit\n new-branch git branch -m main old-main\ngit branch -m new-branch main\n main" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8840978/" ]
74,574,442
<p>I have a function D(x,y,z) in which I want to evaluate (via interpolation) planes within the z, y, and z axis. i.e. I want the output of my interpolations to be a 2D plane holding one of the values fixed, D(x,y,0) for example.</p> <p>I have created an interpolating function via scipy using some given values of D, D_values, for my input values of x,y,z.</p> <pre><code>from scipy.interpolate import RegularGridInterpolator as rgi D_interp=rgi((x_positions,y_positions,z_positions), D_values) </code></pre> <p>Now I can get any point interpolated by just calling</p> <pre><code>D_interpolated=D_interp(xi,yi,zi) </code></pre> <p>I understand how I can evaluate individual points from this, but how would I interpolate a plane? For example, in my case, D_values is of size 345x155x303 and I want to interpolate 345x155 planes all along the z axis corresponding to the x and y input values, at z=0, z=1, z=2, etc.</p> <p>My attempt at a solution is to feed in the x_positions, y_positions vectors individually into D_interp keeping z fixed, but this just gets me a set of D values evaluated at specific positions, rather than organized into a grid like the planar output I'd actually like. Syntax doesn't allow me to call something like</p> <pre><code>Plane=D_interp(x_positions,y_positions,0) </code></pre> <p>so I was not quite sure about the syntax of calling this function to have planar output.</p> <p>any help appreciated</p> <p>Thanks,</p>
[ { "answer_id": 74621024, "author": "Markus", "author_id": 18667225, "author_profile": "https://Stackoverflow.com/users/18667225", "pm_score": 0, "selected": false, "text": "x_positions = np.arange(0, 355)\ny_positions = np.arange(0, 155)\nz_positions = np.arange(0, 303)\n\nz_mesh, x_mesh, y_mesh = np.meshgrid(z_positions, x_positions, y_positions, indexing='ij')\npts = np.vstack([x_mesh.ravel(), y_mesh.ravel(), z_mesh.ravel()]).transpose()\nplane = np.reshape(interp(pts), x_mesh.shape)\n z_positions" }, { "answer_id": 74621407, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 2, "selected": true, "text": "x_positions = np.linspace(0, 10, 101)\ny_positions = np.linspace(-10, 10, 201)\nz_positions = np.linspace(-5, 5, 101)\nD_values = np.sin(2 * np.pi * x_positions[:, None, None] * y_positions[:, None] / 100) + np.cos(2 * np.pi * y_positions[:, None] * z_positions / 50)\n D_values *_positions x_positions (101, 1, 1) y_positions (201, 1) z_positions (101,) D_values (101, 201, 101) D_values D_interp = rgi((x_positions, y_positions, z_positions), D_values)\n z = 0 x_interp = np.linspace(0.05, 0.95, 200)\ny_interp = np.linspace(-9.95, 9.95, 400)\nz_interp = 0\nD_xy_interp = D_interp((x_interp[:, None], y_interp, z_interp))\n D_xy_interp (len(x_interp), len(y_interp)) D_values 0 (400, 200) D_interp((x_interp, y_interp[:, None], z_interp))\n (100, 4, 100, 2) D_interp((x_interp.reshape(-1, 2), y_interp.reshape(-1, 4, 1, 1), z_interp))\n D_values D_xy_values = np.sin(2 * np.pi * x_interp[:, None] * y_interp / 100) + np.cos(2 * np.pi * y_interp * z_interp / 50)\n\nfig, ax = plt.subplots(subplot_kw={'projection': '3d'})\nax.plot_surface(x_interp[:, None], y_interp, D_xy_interp, label='Interp')\nax.plot_surface(x_interp[:, None], y_interp, D_xy_values, label='Values')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n >>> np.sqrt(np.mean((D_xy_values - D_xy_interp)**2))\n4.707625623185639e-05\n" }, { "answer_id": 74638637, "author": "xentwo", "author_id": 9743356, "author_profile": "https://Stackoverflow.com/users/9743356", "pm_score": 1, "selected": false, "text": "RegularGridInterpolator __call__ from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate the plane at z=0\nplane = D_interp(z=0)\n plane from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate all the planes along the z-axis\nplanes = []\nfor z in z_positions:\n plane = D_interp(z=z)\n planes.append(plane)\n planes z_positions" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13423905/" ]
74,574,484
<p>I am trying to synchronize access to external memory across 2 processes on android vulkan, my system is telling me that it is only supporting</p> <pre><code>VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT </code></pre> <p>which can be exported as as copy, not as a reference.</p> <p>What I am doing is this in process A ( exporting fd )</p> <pre><code>CALL_VK(vkQueueSubmit(queue, 1, &amp;submit_info, fence)); int fd; VkFenceGetFdInfoKHR getFdInfo{}; getFdInfo.sType = VK_STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR; getFdInfo.handleType = VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT; getFdInfo.fence = fence; CALL_VK(vkGetFenceFdKHR(device.device_, &amp;getFdInfo, &amp;fd)); </code></pre> <p>and then this in process B ( importing copy of a payload from a fd)</p> <pre><code>VkImportFenceFdInfoKHR importFenceFdInfo{}; importFenceFdInfo.sType = VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR; importFenceFdInfo.handleType = VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT; importFenceFdInfo.fd = fd; importFenceFdInfo.fence = fence; importFenceFdInfo.flags = VK_FENCE_IMPORT_TEMPORARY_BIT; CALL_VK(vkImportFenceFdKHR(device.device_, &amp;importFenceFdInfo)); </code></pre> <p>The thing is if in the process B the fence I've got back is still unsignalled ( it was pending after vkQueueSubmit ) then since this is a copy and not a reference it will never be signalled and I will never know when my GPU runtime will have been finished. I am getting a freeze in the following call in my process B</p> <pre><code>VkResult result = vkWaitForFences(device, 1, &amp;fence, VK_TRUE, -1); </code></pre> <p>Then what is the point in all this?</p> <p>I am expecting that I shall be able to get the state of the fence updated in my process B once it is signalled by GPU.</p>
[ { "answer_id": 74621024, "author": "Markus", "author_id": 18667225, "author_profile": "https://Stackoverflow.com/users/18667225", "pm_score": 0, "selected": false, "text": "x_positions = np.arange(0, 355)\ny_positions = np.arange(0, 155)\nz_positions = np.arange(0, 303)\n\nz_mesh, x_mesh, y_mesh = np.meshgrid(z_positions, x_positions, y_positions, indexing='ij')\npts = np.vstack([x_mesh.ravel(), y_mesh.ravel(), z_mesh.ravel()]).transpose()\nplane = np.reshape(interp(pts), x_mesh.shape)\n z_positions" }, { "answer_id": 74621407, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 2, "selected": true, "text": "x_positions = np.linspace(0, 10, 101)\ny_positions = np.linspace(-10, 10, 201)\nz_positions = np.linspace(-5, 5, 101)\nD_values = np.sin(2 * np.pi * x_positions[:, None, None] * y_positions[:, None] / 100) + np.cos(2 * np.pi * y_positions[:, None] * z_positions / 50)\n D_values *_positions x_positions (101, 1, 1) y_positions (201, 1) z_positions (101,) D_values (101, 201, 101) D_values D_interp = rgi((x_positions, y_positions, z_positions), D_values)\n z = 0 x_interp = np.linspace(0.05, 0.95, 200)\ny_interp = np.linspace(-9.95, 9.95, 400)\nz_interp = 0\nD_xy_interp = D_interp((x_interp[:, None], y_interp, z_interp))\n D_xy_interp (len(x_interp), len(y_interp)) D_values 0 (400, 200) D_interp((x_interp, y_interp[:, None], z_interp))\n (100, 4, 100, 2) D_interp((x_interp.reshape(-1, 2), y_interp.reshape(-1, 4, 1, 1), z_interp))\n D_values D_xy_values = np.sin(2 * np.pi * x_interp[:, None] * y_interp / 100) + np.cos(2 * np.pi * y_interp * z_interp / 50)\n\nfig, ax = plt.subplots(subplot_kw={'projection': '3d'})\nax.plot_surface(x_interp[:, None], y_interp, D_xy_interp, label='Interp')\nax.plot_surface(x_interp[:, None], y_interp, D_xy_values, label='Values')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n >>> np.sqrt(np.mean((D_xy_values - D_xy_interp)**2))\n4.707625623185639e-05\n" }, { "answer_id": 74638637, "author": "xentwo", "author_id": 9743356, "author_profile": "https://Stackoverflow.com/users/9743356", "pm_score": 1, "selected": false, "text": "RegularGridInterpolator __call__ from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate the plane at z=0\nplane = D_interp(z=0)\n plane from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate all the planes along the z-axis\nplanes = []\nfor z in z_positions:\n plane = D_interp(z=z)\n planes.append(plane)\n planes z_positions" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8908561/" ]
74,574,492
<p>i want to be able to add, subtract, divide, multiply etc with integers in a list and in order.</p> <p>I know you can use sum() to add, but i also want to be able to subtract, etc in order... so i tried making a for loop idk if thats the right thing to do, but it doesn't give me the right output and it really confuses me because it really seems like it should work. I was wondering if anyone knows how to fix this or explain why its not giving me the same output as i expected.</p> <pre><code>my_list = [100, 15, 3] for i in my_list: i -= i print(i) # 100 - 15 - 3 = 82 # Wanted output: 82 # Actual output: 0 my_list = [100, 15] for i in my_list: i += i print(i) # 100 + 15 = 115 # Wanted output: 115 # Actual output: 30 </code></pre>
[ { "answer_id": 74621024, "author": "Markus", "author_id": 18667225, "author_profile": "https://Stackoverflow.com/users/18667225", "pm_score": 0, "selected": false, "text": "x_positions = np.arange(0, 355)\ny_positions = np.arange(0, 155)\nz_positions = np.arange(0, 303)\n\nz_mesh, x_mesh, y_mesh = np.meshgrid(z_positions, x_positions, y_positions, indexing='ij')\npts = np.vstack([x_mesh.ravel(), y_mesh.ravel(), z_mesh.ravel()]).transpose()\nplane = np.reshape(interp(pts), x_mesh.shape)\n z_positions" }, { "answer_id": 74621407, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 2, "selected": true, "text": "x_positions = np.linspace(0, 10, 101)\ny_positions = np.linspace(-10, 10, 201)\nz_positions = np.linspace(-5, 5, 101)\nD_values = np.sin(2 * np.pi * x_positions[:, None, None] * y_positions[:, None] / 100) + np.cos(2 * np.pi * y_positions[:, None] * z_positions / 50)\n D_values *_positions x_positions (101, 1, 1) y_positions (201, 1) z_positions (101,) D_values (101, 201, 101) D_values D_interp = rgi((x_positions, y_positions, z_positions), D_values)\n z = 0 x_interp = np.linspace(0.05, 0.95, 200)\ny_interp = np.linspace(-9.95, 9.95, 400)\nz_interp = 0\nD_xy_interp = D_interp((x_interp[:, None], y_interp, z_interp))\n D_xy_interp (len(x_interp), len(y_interp)) D_values 0 (400, 200) D_interp((x_interp, y_interp[:, None], z_interp))\n (100, 4, 100, 2) D_interp((x_interp.reshape(-1, 2), y_interp.reshape(-1, 4, 1, 1), z_interp))\n D_values D_xy_values = np.sin(2 * np.pi * x_interp[:, None] * y_interp / 100) + np.cos(2 * np.pi * y_interp * z_interp / 50)\n\nfig, ax = plt.subplots(subplot_kw={'projection': '3d'})\nax.plot_surface(x_interp[:, None], y_interp, D_xy_interp, label='Interp')\nax.plot_surface(x_interp[:, None], y_interp, D_xy_values, label='Values')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n >>> np.sqrt(np.mean((D_xy_values - D_xy_interp)**2))\n4.707625623185639e-05\n" }, { "answer_id": 74638637, "author": "xentwo", "author_id": 9743356, "author_profile": "https://Stackoverflow.com/users/9743356", "pm_score": 1, "selected": false, "text": "RegularGridInterpolator __call__ from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate the plane at z=0\nplane = D_interp(z=0)\n plane from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate all the planes along the z-axis\nplanes = []\nfor z in z_positions:\n plane = D_interp(z=z)\n planes.append(plane)\n planes z_positions" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600218/" ]
74,574,508
<p>I am making a drawing app with React and Canvas. However, if I set the <code>isMouseDown</code> variable as <code>useState</code> instead of <code>useRef</code>, the canvas is not drawing and I cannot seem to find why. Here is the component:</p> <pre class="lang-js prettyprint-override"><code>function App() { const [isMouseDown, setIsMouseDown] = useState(false); const isMouseDownRef = useRef(false); const canvasRef = useRef(null); const ctx = useRef(null); function triggerMouseDown() { setIsMouseDown(true); //isMouseDownRef.current = true; } function triggerMouseUp() { setIsMouseDown(false); //isMouseDownRef.current = false; } useEffect(() =&gt; { if(canvasRef.current) { ctx.current = canvasRef.current.getContext(&quot;2d&quot;); canvasRef.current.width = 720; canvasRef.current.height = 480; canvasRef.current.addEventListener(&quot;mousemove&quot;, (e) =&gt; { draw( e.clientX - canvasRef.current.getBoundingClientRect().left, e.clientY - canvasRef.current.getBoundingClientRect().top ) }) canvasRef.current.addEventListener(&quot;mousedown&quot;, triggerMouseDown) window.addEventListener(&quot;mouseup&quot;, triggerMouseUp) } return () =&gt; { canvasRef.current.removeEventListener(&quot;mousedown&quot;, triggerMouseDown); window.removeEventListener(&quot;mouseup&quot;, triggerMouseUp) } }, []) function draw(x, y) { if(isMouseDown) { ctx.current.beginPath(); ctx.current.fillStyle = &quot;blue&quot;; ctx.current.arc(x, y, 20, 0, 2 * Math.PI); ctx.current.stroke(); } } return ( &lt;div className=&quot;App&quot;&gt; &lt;canvas id=&quot;canvas1&quot; ref={canvasRef}&gt;&lt;/canvas&gt; &lt;h1&gt;{JSON.stringify(isMouseDown)}&lt;/h1&gt; &lt;/div&gt; ); } </code></pre> <p>I know it's not supposed to be a <code>useState</code>, beacause it would rerender too much, but I am interested in why it's not working with <code>useState</code> in particular.</p>
[ { "answer_id": 74621024, "author": "Markus", "author_id": 18667225, "author_profile": "https://Stackoverflow.com/users/18667225", "pm_score": 0, "selected": false, "text": "x_positions = np.arange(0, 355)\ny_positions = np.arange(0, 155)\nz_positions = np.arange(0, 303)\n\nz_mesh, x_mesh, y_mesh = np.meshgrid(z_positions, x_positions, y_positions, indexing='ij')\npts = np.vstack([x_mesh.ravel(), y_mesh.ravel(), z_mesh.ravel()]).transpose()\nplane = np.reshape(interp(pts), x_mesh.shape)\n z_positions" }, { "answer_id": 74621407, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 2, "selected": true, "text": "x_positions = np.linspace(0, 10, 101)\ny_positions = np.linspace(-10, 10, 201)\nz_positions = np.linspace(-5, 5, 101)\nD_values = np.sin(2 * np.pi * x_positions[:, None, None] * y_positions[:, None] / 100) + np.cos(2 * np.pi * y_positions[:, None] * z_positions / 50)\n D_values *_positions x_positions (101, 1, 1) y_positions (201, 1) z_positions (101,) D_values (101, 201, 101) D_values D_interp = rgi((x_positions, y_positions, z_positions), D_values)\n z = 0 x_interp = np.linspace(0.05, 0.95, 200)\ny_interp = np.linspace(-9.95, 9.95, 400)\nz_interp = 0\nD_xy_interp = D_interp((x_interp[:, None], y_interp, z_interp))\n D_xy_interp (len(x_interp), len(y_interp)) D_values 0 (400, 200) D_interp((x_interp, y_interp[:, None], z_interp))\n (100, 4, 100, 2) D_interp((x_interp.reshape(-1, 2), y_interp.reshape(-1, 4, 1, 1), z_interp))\n D_values D_xy_values = np.sin(2 * np.pi * x_interp[:, None] * y_interp / 100) + np.cos(2 * np.pi * y_interp * z_interp / 50)\n\nfig, ax = plt.subplots(subplot_kw={'projection': '3d'})\nax.plot_surface(x_interp[:, None], y_interp, D_xy_interp, label='Interp')\nax.plot_surface(x_interp[:, None], y_interp, D_xy_values, label='Values')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n >>> np.sqrt(np.mean((D_xy_values - D_xy_interp)**2))\n4.707625623185639e-05\n" }, { "answer_id": 74638637, "author": "xentwo", "author_id": 9743356, "author_profile": "https://Stackoverflow.com/users/9743356", "pm_score": 1, "selected": false, "text": "RegularGridInterpolator __call__ from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate the plane at z=0\nplane = D_interp(z=0)\n plane from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate all the planes along the z-axis\nplanes = []\nfor z in z_positions:\n plane = D_interp(z=z)\n planes.append(plane)\n planes z_positions" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15338366/" ]
74,574,527
<p>I'm struggling in creating multiple ranges using hugo.</p> <pre><code> {{ range (.Paginate (where site.RegularPages &quot;Section&quot; &quot;research&quot;)).Pages }} {{ partial &quot;research-card&quot; .}} {{ end }} {{ range (.Paginate (where site.RegularPages &quot;Section&quot; &quot;services&quot;)).Pages }} {{ partial &quot;services-card&quot; .}} {{ end }} </code></pre> <p>I want to use each of these to create cards for different sections however they are in the same html file. The issue I am having is that when I add the second range it removes the cards from the first one and if I create pages for each I get nil variable errors.</p> <p>Is there a way to use more than one range on the same page in hugo to create a home page that loads different sections?</p>
[ { "answer_id": 74621024, "author": "Markus", "author_id": 18667225, "author_profile": "https://Stackoverflow.com/users/18667225", "pm_score": 0, "selected": false, "text": "x_positions = np.arange(0, 355)\ny_positions = np.arange(0, 155)\nz_positions = np.arange(0, 303)\n\nz_mesh, x_mesh, y_mesh = np.meshgrid(z_positions, x_positions, y_positions, indexing='ij')\npts = np.vstack([x_mesh.ravel(), y_mesh.ravel(), z_mesh.ravel()]).transpose()\nplane = np.reshape(interp(pts), x_mesh.shape)\n z_positions" }, { "answer_id": 74621407, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 2, "selected": true, "text": "x_positions = np.linspace(0, 10, 101)\ny_positions = np.linspace(-10, 10, 201)\nz_positions = np.linspace(-5, 5, 101)\nD_values = np.sin(2 * np.pi * x_positions[:, None, None] * y_positions[:, None] / 100) + np.cos(2 * np.pi * y_positions[:, None] * z_positions / 50)\n D_values *_positions x_positions (101, 1, 1) y_positions (201, 1) z_positions (101,) D_values (101, 201, 101) D_values D_interp = rgi((x_positions, y_positions, z_positions), D_values)\n z = 0 x_interp = np.linspace(0.05, 0.95, 200)\ny_interp = np.linspace(-9.95, 9.95, 400)\nz_interp = 0\nD_xy_interp = D_interp((x_interp[:, None], y_interp, z_interp))\n D_xy_interp (len(x_interp), len(y_interp)) D_values 0 (400, 200) D_interp((x_interp, y_interp[:, None], z_interp))\n (100, 4, 100, 2) D_interp((x_interp.reshape(-1, 2), y_interp.reshape(-1, 4, 1, 1), z_interp))\n D_values D_xy_values = np.sin(2 * np.pi * x_interp[:, None] * y_interp / 100) + np.cos(2 * np.pi * y_interp * z_interp / 50)\n\nfig, ax = plt.subplots(subplot_kw={'projection': '3d'})\nax.plot_surface(x_interp[:, None], y_interp, D_xy_interp, label='Interp')\nax.plot_surface(x_interp[:, None], y_interp, D_xy_values, label='Values')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n >>> np.sqrt(np.mean((D_xy_values - D_xy_interp)**2))\n4.707625623185639e-05\n" }, { "answer_id": 74638637, "author": "xentwo", "author_id": 9743356, "author_profile": "https://Stackoverflow.com/users/9743356", "pm_score": 1, "selected": false, "text": "RegularGridInterpolator __call__ from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate the plane at z=0\nplane = D_interp(z=0)\n plane from scipy.interpolate import RegularGridInterpolator as rgi\n\n# Define the input values for the x, y, and z dimensions\nx_positions = ...\ny_positions = ...\nz_positions = ...\n\n# Define the values of the function D at each point in the grid\nD_values = ...\n\n# Create the interpolator object\nD_interp = rgi((x_positions, y_positions, z_positions), D_values)\n\n# Interpolate all the planes along the z-axis\nplanes = []\nfor z in z_positions:\n plane = D_interp(z=z)\n planes.append(plane)\n planes z_positions" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12398800/" ]
74,574,539
<p>I am trying to work with sympy and work with manipulation of expressions.</p> <pre><code>import sympy as sym from sympy.abc import t x0,v0 = sym.symbols(&quot;x0 v0 &quot;, real=True) wn = sym.symbols(&quot;omega_n&quot;, positive = True, real=True) z = sym.symbols(&quot;zeta&quot;, positive = True, real=True) x = sym.Function('x') Dx = sym.Derivative(x(t), t) Dx2= sym.Derivative(x(t), t,2) res = sym.dsolve(Dx2 +2*z*wn*Dx+ wn**2*x(t), x(t), ics = { x(0): x0, Dx.subs(t,0):v0}) </code></pre> <p>The above yields the following expression</p> <p><a href="https://i.stack.imgur.com/NIJtj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NIJtj.png" alt="enter image description here" /></a></p> <p>The part circled in red can be further simplified to <a href="https://i.stack.imgur.com/LPYOl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LPYOl.png" alt="enter image description here" /></a>, however I can't figure out how is it possible to simplify selected portions of the expression.</p> <p>If I take a simpler exampler <code>wn*x0*z**2/(2*wn*z**2-2*wn)</code> then its possible to cancel out the terms with simplify(), but I could find anywhere some good documentation on how to work and substitute parts of the equation.</p> <hr /> <p>Another similar issue is with the term <a href="https://i.stack.imgur.com/sEAau.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sEAau.png" alt="enter image description here" /></a>, which I would like to transform to <a href="https://i.stack.imgur.com/lf8OP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lf8OP.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74575296, "author": "Davide_sd", "author_id": 2329968, "author_profile": "https://Stackoverflow.com/users/2329968", "pm_score": 2, "selected": false, "text": "z**2 # search the expression tree and select all multiplications\n# containing a power with exponent 2\nw = sym.Wild(\"w\", properties=[\n lambda e: e.is_Mul and any(t.is_Pow and t.exp == 2 for t in e.args)\n])\nt = list(res.find(w))[0]\nprint(t)\n# out: omega_n*x0*zeta**2/(2*omega_n*zeta**2 - 2*omega_n)\n\n# Perform the simplification and substitution\nres = res.subs(t, t.simplify())\n # loop over each exponential term and apply a\n# powsimp to its argument.\nfor t in res.find(sym.exp):\n res = res.subs(t, sym.exp(t.args[0].powsimp()))\nprint(res)\n" }, { "answer_id": 74575658, "author": "Oscar Benjamin", "author_id": 9450991, "author_profile": "https://Stackoverflow.com/users/9450991", "pm_score": 1, "selected": false, "text": "rhs In [58]: res.rhs\nOut[58]: \n ⎛ _______ _______⎞ ⎛ 2 _______ _______ _______ _______⎞ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ ωₙ⋅x₀⋅ζ ωₙ⋅x₀⋅ζ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ωₙ⋅x₀ v₀⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────────────── + ── - ────────────────────────⎟⋅ℯ + ⎜────────────── + ─────────────────────────── - ────────────── + ──────────────────────⎟⋅ℯ \n⎜ _______ _______ 2 _______ _______⎟ ⎜ 2 2 2 2 ⎟ \n⎝ 2⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 2⋅ωₙ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎝2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ ⎠ \n wn rhs wn In [45]: res.rhs.collect(wn)\nOut[45]: \n ⎛ _______ _______⎞ ⎛ 2 _______ _______ _______ _______⎞ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 x₀ v₀⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────────────── + ── - ────────────────────────⎟⋅ℯ + ⎜──────── + ──────────────────────── - ──────── + ──────────────────────⎟⋅ℯ \n⎜ _______ _______ 2 _______ _______⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎝ 2⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 2⋅ωₙ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n sqrt(z-1)*sqrt(z+1) sqrt(z**2 - 1) z powsimp In [46]: res.rhs.collect(wn).powsimp()\nOut[46]: \n ⎛ ________ ________⎞ \n ⎛ _______ _______⎞ ⎜ 2 ╱ 2 ╱ 2 ⎟ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 x₀ v₀⋅╲╱ ζ - 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────── + ── - ────────────────⎟⋅ℯ + ⎜──────── + ──────────────── - ──────── + ──────────────⎟⋅ℯ \n⎜ ________ 2 ________⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n⎝ 2⋅╲╱ ζ - 1 2⋅ωₙ⋅╲╱ ζ - 1 ⎠ \n powsimp deep=True In [47]: res.rhs.collect(wn).powsimp(deep=True)\nOut[47]: \n ⎛ ________⎞ ⎛ ________ ________⎞ ⎛ ________⎞\n ⎜ ╱ 2 ⎟ ⎜ 2 ╱ 2 ╱ 2 ⎟ ⎜ ╱ 2 ⎟\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 x₀ v₀⋅╲╱ ζ - 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜- ───────────── + ── - ────────────────⎟⋅ℯ + ⎜──────── + ──────────────── - ──────── + ──────────────⎟⋅ℯ \n⎜ ________ 2 ________⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n⎝ 2⋅╲╱ ζ - 1 2⋅ωₙ⋅╲╱ ζ - 1 ⎠ \n 2 factor_terms In [48]: factor_terms(res.rhs.collect(wn).powsimp(deep=True))\nOut[48]: \n ⎛ ________⎞ ⎛ ________⎞\n ⎜ ╱ 2 ⎟ ⎛ 2 ⎞ ⎜ ╱ 2 ⎟\n⎛ x₀⋅ζ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜x₀⋅ζ x₀⋅ζ x₀ v₀ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜- ─────────── + x₀ - ──────────────⎟⋅ℯ + ⎜────── + ─────────── - ────── + ──────────────⎟⋅ℯ \n⎜ ________ ________⎟ ⎜ 2 ________ 2 ________⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎜ζ - 1 ╱ 2 ζ - 1 ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ωₙ⋅╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ωₙ⋅╲╱ ζ - 1 ⎠ \n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n 2 \n z**2 - 1 In [55]: factor_terms(res.rhs.collect(wn).powsimp(deep=True)).collect(z**2 - 1)\nOut[55]: \n⎛ v₀⎞ ⎛ ________⎞ ⎛ v₀ ⎞ ⎛ ________⎞\n⎜ -x₀⋅ζ - ──⎟ ⎜ ╱ 2 ⎟ ⎜ 2 x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟\n⎜ ωₙ⎟ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜x₀⋅ζ - x₀ ωₙ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜x₀ + ───────────⎟⋅ℯ ⎜────────── + ───────────⎟⋅ℯ \n⎜ ________⎟ ⎜ 2 ________⎟ \n⎜ ╱ 2 ⎟ ⎜ ζ - 1 ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ⎠ \n─────────────────────────────────────────── + ───────────────────────────────────────────────────\n 2 2 \n factor_terms In [56]: factor_terms(res.rhs.collect(wn).powsimp(deep=True)).collect(z**2 - 1, factor_terms)\nOut[56]: \n⎛ v₀ ⎞ ⎛ ________⎞ ⎛ v₀ ⎞ ⎛ ________⎞\n⎜ x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟ ⎜ x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟\n⎜ ωₙ ⎟ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜ ωₙ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜x₀ - ───────────⎟⋅ℯ ⎜x₀ + ───────────⎟⋅ℯ \n⎜ ________⎟ ⎜ ________⎟ \n⎜ ╱ 2 ⎟ ⎜ ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ⎠ \n─────────────────────────────────────────── + ───────────────────────────────────────────\n 2 2\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1940485/" ]
74,574,544
<p>With my dataframe that looks like this (I have in total 1322 rows) :</p> <p><img src="https://i.stack.imgur.com/RDZeP.png" alt="My dataframe" /></p> <p>I'd like to make a bar plot with the percentage of rating of the CFS score. It should look similar to this :</p> <p><img src="https://i.stack.imgur.com/iQ6H4.png" alt="enter image description here" /></p> <p>With this code, I can make a single bar plot for the column cfs_triage :</p> <pre><code>ggplot(data = df) + geom_bar(mapping = aes(x = cfs_triage, y = (..count..)/sum(..count..))) </code></pre> <p><img src="https://i.stack.imgur.com/2XPE5.png" alt="My very basic barplot" /></p> <p>But I can't find out to make one with the three varaibles next to another.</p> <p>Thank you in advance to all of you that will help me with making this barplot with the percentage of rating for this three variable !(I'm not sure that my explanations are very clear, but I hope that it's the case :))</p>
[ { "answer_id": 74575296, "author": "Davide_sd", "author_id": 2329968, "author_profile": "https://Stackoverflow.com/users/2329968", "pm_score": 2, "selected": false, "text": "z**2 # search the expression tree and select all multiplications\n# containing a power with exponent 2\nw = sym.Wild(\"w\", properties=[\n lambda e: e.is_Mul and any(t.is_Pow and t.exp == 2 for t in e.args)\n])\nt = list(res.find(w))[0]\nprint(t)\n# out: omega_n*x0*zeta**2/(2*omega_n*zeta**2 - 2*omega_n)\n\n# Perform the simplification and substitution\nres = res.subs(t, t.simplify())\n # loop over each exponential term and apply a\n# powsimp to its argument.\nfor t in res.find(sym.exp):\n res = res.subs(t, sym.exp(t.args[0].powsimp()))\nprint(res)\n" }, { "answer_id": 74575658, "author": "Oscar Benjamin", "author_id": 9450991, "author_profile": "https://Stackoverflow.com/users/9450991", "pm_score": 1, "selected": false, "text": "rhs In [58]: res.rhs\nOut[58]: \n ⎛ _______ _______⎞ ⎛ 2 _______ _______ _______ _______⎞ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ ωₙ⋅x₀⋅ζ ωₙ⋅x₀⋅ζ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ωₙ⋅x₀ v₀⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────────────── + ── - ────────────────────────⎟⋅ℯ + ⎜────────────── + ─────────────────────────── - ────────────── + ──────────────────────⎟⋅ℯ \n⎜ _______ _______ 2 _______ _______⎟ ⎜ 2 2 2 2 ⎟ \n⎝ 2⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 2⋅ωₙ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎝2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ ⎠ \n wn rhs wn In [45]: res.rhs.collect(wn)\nOut[45]: \n ⎛ _______ _______⎞ ⎛ 2 _______ _______ _______ _______⎞ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 x₀ v₀⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────────────── + ── - ────────────────────────⎟⋅ℯ + ⎜──────── + ──────────────────────── - ──────── + ──────────────────────⎟⋅ℯ \n⎜ _______ _______ 2 _______ _______⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎝ 2⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 2⋅ωₙ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n sqrt(z-1)*sqrt(z+1) sqrt(z**2 - 1) z powsimp In [46]: res.rhs.collect(wn).powsimp()\nOut[46]: \n ⎛ ________ ________⎞ \n ⎛ _______ _______⎞ ⎜ 2 ╱ 2 ╱ 2 ⎟ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 x₀ v₀⋅╲╱ ζ - 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────── + ── - ────────────────⎟⋅ℯ + ⎜──────── + ──────────────── - ──────── + ──────────────⎟⋅ℯ \n⎜ ________ 2 ________⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n⎝ 2⋅╲╱ ζ - 1 2⋅ωₙ⋅╲╱ ζ - 1 ⎠ \n powsimp deep=True In [47]: res.rhs.collect(wn).powsimp(deep=True)\nOut[47]: \n ⎛ ________⎞ ⎛ ________ ________⎞ ⎛ ________⎞\n ⎜ ╱ 2 ⎟ ⎜ 2 ╱ 2 ╱ 2 ⎟ ⎜ ╱ 2 ⎟\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 x₀ v₀⋅╲╱ ζ - 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜- ───────────── + ── - ────────────────⎟⋅ℯ + ⎜──────── + ──────────────── - ──────── + ──────────────⎟⋅ℯ \n⎜ ________ 2 ________⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n⎝ 2⋅╲╱ ζ - 1 2⋅ωₙ⋅╲╱ ζ - 1 ⎠ \n 2 factor_terms In [48]: factor_terms(res.rhs.collect(wn).powsimp(deep=True))\nOut[48]: \n ⎛ ________⎞ ⎛ ________⎞\n ⎜ ╱ 2 ⎟ ⎛ 2 ⎞ ⎜ ╱ 2 ⎟\n⎛ x₀⋅ζ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜x₀⋅ζ x₀⋅ζ x₀ v₀ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜- ─────────── + x₀ - ──────────────⎟⋅ℯ + ⎜────── + ─────────── - ────── + ──────────────⎟⋅ℯ \n⎜ ________ ________⎟ ⎜ 2 ________ 2 ________⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎜ζ - 1 ╱ 2 ζ - 1 ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ωₙ⋅╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ωₙ⋅╲╱ ζ - 1 ⎠ \n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n 2 \n z**2 - 1 In [55]: factor_terms(res.rhs.collect(wn).powsimp(deep=True)).collect(z**2 - 1)\nOut[55]: \n⎛ v₀⎞ ⎛ ________⎞ ⎛ v₀ ⎞ ⎛ ________⎞\n⎜ -x₀⋅ζ - ──⎟ ⎜ ╱ 2 ⎟ ⎜ 2 x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟\n⎜ ωₙ⎟ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜x₀⋅ζ - x₀ ωₙ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜x₀ + ───────────⎟⋅ℯ ⎜────────── + ───────────⎟⋅ℯ \n⎜ ________⎟ ⎜ 2 ________⎟ \n⎜ ╱ 2 ⎟ ⎜ ζ - 1 ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ⎠ \n─────────────────────────────────────────── + ───────────────────────────────────────────────────\n 2 2 \n factor_terms In [56]: factor_terms(res.rhs.collect(wn).powsimp(deep=True)).collect(z**2 - 1, factor_terms)\nOut[56]: \n⎛ v₀ ⎞ ⎛ ________⎞ ⎛ v₀ ⎞ ⎛ ________⎞\n⎜ x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟ ⎜ x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟\n⎜ ωₙ ⎟ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜ ωₙ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜x₀ - ───────────⎟⋅ℯ ⎜x₀ + ───────────⎟⋅ℯ \n⎜ ________⎟ ⎜ ________⎟ \n⎜ ╱ 2 ⎟ ⎜ ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ⎠ \n─────────────────────────────────────────── + ───────────────────────────────────────────\n 2 2\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600300/" ]
74,574,551
<p>I noticed that there are several polygons overlaid when I plot the Netherlands map using ggplot and mapdata in R. I attached the plot. Could anyone help me understand why this happens? Is it possible to have only one layer? I attached the code.</p> <p>Thanks very much!</p> <pre><code>we=map_data(map = &quot;world&quot;, region = c(&quot;Netherlands&quot;)) ggplot()+ geom_polygon(data =we, aes(x=long, y=lat, group=group), fill = &quot;red&quot;, color = &quot;white&quot;,size=0.2,alpha=0.4)+ theme( plot.margin = unit(c(0,0,0,0), &quot;cm&quot;), legend.title = element_blank(), legend.margin=margin(), legend.position = &quot;bottom&quot;, strip.background = element_blank(), panel.background = element_rect(fill = &quot;white&quot;, colour = &quot;white&quot;, size= 0.5), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.title = element_blank()) </code></pre> <p><a href="https://i.stack.imgur.com/hFQfb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hFQfb.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74575296, "author": "Davide_sd", "author_id": 2329968, "author_profile": "https://Stackoverflow.com/users/2329968", "pm_score": 2, "selected": false, "text": "z**2 # search the expression tree and select all multiplications\n# containing a power with exponent 2\nw = sym.Wild(\"w\", properties=[\n lambda e: e.is_Mul and any(t.is_Pow and t.exp == 2 for t in e.args)\n])\nt = list(res.find(w))[0]\nprint(t)\n# out: omega_n*x0*zeta**2/(2*omega_n*zeta**2 - 2*omega_n)\n\n# Perform the simplification and substitution\nres = res.subs(t, t.simplify())\n # loop over each exponential term and apply a\n# powsimp to its argument.\nfor t in res.find(sym.exp):\n res = res.subs(t, sym.exp(t.args[0].powsimp()))\nprint(res)\n" }, { "answer_id": 74575658, "author": "Oscar Benjamin", "author_id": 9450991, "author_profile": "https://Stackoverflow.com/users/9450991", "pm_score": 1, "selected": false, "text": "rhs In [58]: res.rhs\nOut[58]: \n ⎛ _______ _______⎞ ⎛ 2 _______ _______ _______ _______⎞ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ ωₙ⋅x₀⋅ζ ωₙ⋅x₀⋅ζ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ωₙ⋅x₀ v₀⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────────────── + ── - ────────────────────────⎟⋅ℯ + ⎜────────────── + ─────────────────────────── - ────────────── + ──────────────────────⎟⋅ℯ \n⎜ _______ _______ 2 _______ _______⎟ ⎜ 2 2 2 2 ⎟ \n⎝ 2⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 2⋅ωₙ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎝2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ 2⋅ωₙ⋅ζ - 2⋅ωₙ ⎠ \n wn rhs wn In [45]: res.rhs.collect(wn)\nOut[45]: \n ⎛ _______ _______⎞ ⎛ 2 _______ _______ _______ _______⎞ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 x₀ v₀⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────────────── + ── - ────────────────────────⎟⋅ℯ + ⎜──────── + ──────────────────────── - ──────── + ──────────────────────⎟⋅ℯ \n⎜ _______ _______ 2 _______ _______⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎝ 2⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 2⋅ωₙ⋅╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n sqrt(z-1)*sqrt(z+1) sqrt(z**2 - 1) z powsimp In [46]: res.rhs.collect(wn).powsimp()\nOut[46]: \n ⎛ ________ ________⎞ \n ⎛ _______ _______⎞ ⎜ 2 ╱ 2 ╱ 2 ⎟ ⎛ _______ _______⎞\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 x₀ v₀⋅╲╱ ζ - 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⋅╲╱ ζ + 1 ⎠\n⎜- ───────────── + ── - ────────────────⎟⋅ℯ + ⎜──────── + ──────────────── - ──────── + ──────────────⎟⋅ℯ \n⎜ ________ 2 ________⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n⎝ 2⋅╲╱ ζ - 1 2⋅ωₙ⋅╲╱ ζ - 1 ⎠ \n powsimp deep=True In [47]: res.rhs.collect(wn).powsimp(deep=True)\nOut[47]: \n ⎛ ________⎞ ⎛ ________ ________⎞ ⎛ ________⎞\n ⎜ ╱ 2 ⎟ ⎜ 2 ╱ 2 ╱ 2 ⎟ ⎜ ╱ 2 ⎟\n⎛ x₀⋅ζ x₀ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜ x₀⋅ζ x₀⋅ζ⋅╲╱ ζ - 1 x₀ v₀⋅╲╱ ζ - 1 ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜- ───────────── + ── - ────────────────⎟⋅ℯ + ⎜──────── + ──────────────── - ──────── + ──────────────⎟⋅ℯ \n⎜ ________ 2 ________⎟ ⎜ 2 2 2 ⎛ 2 ⎞ ⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎝2⋅ζ - 2 2⋅ζ - 2 2⋅ζ - 2 ωₙ⋅⎝2⋅ζ - 2⎠ ⎠ \n⎝ 2⋅╲╱ ζ - 1 2⋅ωₙ⋅╲╱ ζ - 1 ⎠ \n 2 factor_terms In [48]: factor_terms(res.rhs.collect(wn).powsimp(deep=True))\nOut[48]: \n ⎛ ________⎞ ⎛ ________⎞\n ⎜ ╱ 2 ⎟ ⎛ 2 ⎞ ⎜ ╱ 2 ⎟\n⎛ x₀⋅ζ v₀ ⎞ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜x₀⋅ζ x₀⋅ζ x₀ v₀ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜- ─────────── + x₀ - ──────────────⎟⋅ℯ + ⎜────── + ─────────── - ────── + ──────────────⎟⋅ℯ \n⎜ ________ ________⎟ ⎜ 2 ________ 2 ________⎟ \n⎜ ╱ 2 ╱ 2 ⎟ ⎜ζ - 1 ╱ 2 ζ - 1 ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ωₙ⋅╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ωₙ⋅╲╱ ζ - 1 ⎠ \n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n 2 \n z**2 - 1 In [55]: factor_terms(res.rhs.collect(wn).powsimp(deep=True)).collect(z**2 - 1)\nOut[55]: \n⎛ v₀⎞ ⎛ ________⎞ ⎛ v₀ ⎞ ⎛ ________⎞\n⎜ -x₀⋅ζ - ──⎟ ⎜ ╱ 2 ⎟ ⎜ 2 x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟\n⎜ ωₙ⎟ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜x₀⋅ζ - x₀ ωₙ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜x₀ + ───────────⎟⋅ℯ ⎜────────── + ───────────⎟⋅ℯ \n⎜ ________⎟ ⎜ 2 ________⎟ \n⎜ ╱ 2 ⎟ ⎜ ζ - 1 ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ⎠ \n─────────────────────────────────────────── + ───────────────────────────────────────────────────\n 2 2 \n factor_terms In [56]: factor_terms(res.rhs.collect(wn).powsimp(deep=True)).collect(z**2 - 1, factor_terms)\nOut[56]: \n⎛ v₀ ⎞ ⎛ ________⎞ ⎛ v₀ ⎞ ⎛ ________⎞\n⎜ x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟ ⎜ x₀⋅ζ + ── ⎟ ⎜ ╱ 2 ⎟\n⎜ ωₙ ⎟ -ωₙ⋅t⋅⎝ζ + ╲╱ ζ - 1 ⎠ ⎜ ωₙ ⎟ ωₙ⋅t⋅⎝-ζ + ╲╱ ζ - 1 ⎠\n⎜x₀ - ───────────⎟⋅ℯ ⎜x₀ + ───────────⎟⋅ℯ \n⎜ ________⎟ ⎜ ________⎟ \n⎜ ╱ 2 ⎟ ⎜ ╱ 2 ⎟ \n⎝ ╲╱ ζ - 1 ⎠ ⎝ ╲╱ ζ - 1 ⎠ \n─────────────────────────────────────────── + ───────────────────────────────────────────\n 2 2\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15112746/" ]
74,574,627
<p>I've a django application with waitress (gunicorn doesn't work on windows) to serve it. Because its production code and its based on windows 2012 server. But I want the django application to run in daemon mode is it possible?</p> <p>Daemon mode - app running without command prompt visible also I'll be helpful to open shell without even closing the server. AutoStart if for some reason system has to restart.</p> <p>Note:</p> <p>Restrictions: The project cannot be moved to UNIX based system. Third Party application like any .exe file cannot be used.</p>
[ { "answer_id": 74574671, "author": "Artem Milosevic", "author_id": 15077686, "author_profile": "https://Stackoverflow.com/users/15077686", "pm_score": 0, "selected": false, "text": "&" }, { "answer_id": 74599712, "author": "Shen", "author_id": 16037571, "author_profile": "https://Stackoverflow.com/users/16037571", "pm_score": 2, "selected": false, "text": "from waitress import serve\n \nfrom myapp.wsgi import application\n \nif __name__ == '__main__':\n serve(application, port='8000')\n Start-Process python -NoNewWindow -ArgumentList \"server.py\"" }, { "answer_id": 74678920, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "python manage.py installservice\n net start <service name>\n sc config <service name> start=auto\n python manage.py shell\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12201407/" ]
74,574,637
<p>I have a task where I have to iterate thru a string and return a predefined number of chars in a row. So f.i. the string is &quot;Thisisatest&quot; and I have to start on the first position and return two characters. Have to proof them for som uniques (outside that scope) and if not proofed I have to shift the start be one and start on the second position and return two characters. Have to repeat this as long as I found a unique pair of chars or reached the end of the string.</p> <p>So f.i. first loop: returns Th, then hi, is, si, is, sa, at...</p> <p>Used this script:</p> <pre><code>function setInitials(Start,Num,Str){ var initials=&quot;&quot; if(Number(Start)+Number(Num)-1 &lt; Str.length){ for (var i = Number(Start); i &lt; Number(Num); i++) { initials += Str[i]; } } return initials } </code></pre> <p>where Start ist my Starting point, Num the Number of Chars to return ans Str the string.</p> <p>But if I try setInitials(&quot;2&quot;,&quot;2&quot;,&quot;Thisiaatrest&quot;) I will get back nothing</p>
[ { "answer_id": 74574671, "author": "Artem Milosevic", "author_id": 15077686, "author_profile": "https://Stackoverflow.com/users/15077686", "pm_score": 0, "selected": false, "text": "&" }, { "answer_id": 74599712, "author": "Shen", "author_id": 16037571, "author_profile": "https://Stackoverflow.com/users/16037571", "pm_score": 2, "selected": false, "text": "from waitress import serve\n \nfrom myapp.wsgi import application\n \nif __name__ == '__main__':\n serve(application, port='8000')\n Start-Process python -NoNewWindow -ArgumentList \"server.py\"" }, { "answer_id": 74678920, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "python manage.py installservice\n net start <service name>\n sc config <service name> start=auto\n python manage.py shell\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549661/" ]
74,574,647
<p>I want to build a dashboard where I can select a year and a application and want to have the top 5 clients shown up.</p> <p>I build a example Sheet ofr showing: <a href="https://docs.google.com/spreadsheets/d/13yk_SIsv52bZbskOkEzkz4f1aOMnb5yLDk2oo5BawXs/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/13yk_SIsv52bZbskOkEzkz4f1aOMnb5yLDk2oo5BawXs/edit?usp=sharing</a></p> <p>On the left side I have listed all top clients ob every year and per application. On the right side I have a little selection tool and I want in the yellow marked area the correct data from the left side.</p> <p>Thanks for your help</p>
[ { "answer_id": 74575100, "author": "Nabnub", "author_id": 9538684, "author_profile": "https://Stackoverflow.com/users/9538684", "pm_score": 0, "selected": false, "text": "= Query(A1:E; \"Select C,D,E \n where A contains '\"&I3&\"'\n and B contains '\"&I4&\"'\n Order by E Desc Limit 5 \")\n" }, { "answer_id": 74577088, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 2, "selected": true, "text": "=INDEX(QUERY({\"\"&A1:B\\ C1:E}; \n \"select Col3,Col4,Col5 \n where 3=3 \"&\n IF(I3=\"\";;\" and Col1 contains '\"&I3&\"'\")&\n IF(I4=\"\";;\" and Col2 contains '\"&I4&\"'\")&\n \"order by Col5 desc \n limit 5\"; ))\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19893042/" ]
74,574,664
<p>there is a different structure to show projects Project 1 and 2 are in the same Project 3 is in a different Project 4 and 5 are in the same Project 6 is in a different it goes on like this</p> <p>div will open if $i == 1</p> <p>If $i == 2 the div will be closed</p> <p>If $i == 3 the div will be opened and closed</p> <p>my code</p> <pre><code>@foreach($projects as $project) @if($loop-&gt;iteration % 3 === 0 || $loop-&gt;first || $loop-&gt;iteration % 2 === 0) &lt;div class=&quot;project&quot;&gt; @endif &lt;img src=&quot;{{ Voyager::image($project-&gt;image) }}&quot; alt=&quot;{{ $project-&gt;title }}&quot;&gt; @if($loop-&gt;iteration % 3 === 0 || $loop-&gt;last || $loop-&gt;iteration % 2 === 0) &lt;/div&gt; @endif @endforeach </code></pre> <p>my code result</p> <pre><code> &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project1.jpg&quot; alt=&quot;&quot;&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project2.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project3.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project4.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;img src=&quot;project5.jpg&quot; alt=&quot;&quot;&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project6.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;img src=&quot;project7.jpg&quot; alt=&quot;&quot;&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project8.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project9.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; </code></pre> <p>the result i want</p> <pre><code> &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project1.jpg&quot; alt=&quot;&quot;&gt; &lt;img src=&quot;project2.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project3.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project4.jpg&quot; alt=&quot;&quot;&gt; &lt;img src=&quot;project5.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project6.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project7.jpg&quot; alt=&quot;&quot;&gt; &lt;img src=&quot;project8.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;project&quot;&gt; &lt;img src=&quot;project9.jpg&quot; alt=&quot;&quot;&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74580528, "author": "Mayuresh", "author_id": 2598305, "author_profile": "https://Stackoverflow.com/users/2598305", "pm_score": 0, "selected": false, "text": "@foreach($projects as $project)\n@if($loop->first)\n <div class=\"project\"> @endif\n \n\n @if($loop->iteration % 3 === 0) </div>\n<div class=\"project\">\n @endif\n <img src=\"{{ Voyager::image($project->image) }}\" alt=\"{{ $project->title }}\">\n@if($loop->iteration % 3 === 0) </div>\n<div class=\"project\">\n\n@endif\n@if($loop->last)\n </div> \n@endif\n@endforeach\n" }, { "answer_id": 74584538, "author": "Ross_102", "author_id": 3657308, "author_profile": "https://Stackoverflow.com/users/3657308", "pm_score": 1, "selected": false, "text": "@foreach ($projects\n ->chunk(3)\n ->map(function ($item) {\n return $item->chunk(2);\n })\n ->flatten(1) as $projectData)\n <div class=\"project\">\n @foreach ($projectData as $project)\n <img src=\"{{ Voyager::image($project->image) }}\" alt=\"{{ $project->title }}\">\n @endforeach\n </div>\n@endforeach\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18751480/" ]
74,574,694
<p>I'm currently working on a .net 4.6.2 application.</p> <p>I need to serialize an OData Api call and it works perfectly fine.</p> <p>Unfortunately I'm getting a Sonar Qube Error:</p> <p><strong>Update this implementation of 'ISerializable' to conform to the recommended serialization pattern.</strong></p> <p><a href="https://i.stack.imgur.com/qP9UP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qP9UP.png" alt="enter image description here" /></a></p> <p>To get my OData into C#, I use the following class structure:</p> <pre><code>[Serializable] public class Record : Dictionary&lt;string, dynamic&gt; { } [DataContract] public class Records { [DataMember(Name = &quot;@odata.context&quot;)] public string Context { get; set; } [DataMember(Name = &quot;@odata.count&quot;)] public int Count { get; set; } [DataMember(Name = &quot;value&quot;)] public IEnumerable&lt;Record&gt; Value { get; set; } } </code></pre> <p>The serialization works fine, but I don't know how to solve this Sonar Qube error.</p> <p>How to properly use ISerializable together with DataContract, is it actually possible?</p> <p>Do you know how to solve this issue?</p>
[ { "answer_id": 74574836, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 1, "selected": false, "text": "#pragma warning disable S3925 // \"ISerializable\" should be implemented correctly\n public class Record : Dictionary<string, string> { }\n#pragma warning restore S3925 // \"ISerializable\" should be implemented correctly\n ISerializable public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, ISerializable, IDeserializationCallback\n {\n" }, { "answer_id": 74576587, "author": "Bender.", "author_id": 16841473, "author_profile": "https://Stackoverflow.com/users/16841473", "pm_score": 0, "selected": false, "text": "[DataMember(Name = \"value\")]\npublic List<Dictionary<string, dynamic>> Value { get; set; }\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16841473/" ]
74,574,699
<p>a dataframe as list:</p> <pre><code>dfcheck &lt;- data.frame(status = c(&quot;open/close&quot;, &quot;close&quot;, &quot;open&quot;), stock = c(&quot;company energy&quot;,&quot;goods and books&quot;,&quot;other&quot;), name = c(&quot;amazon1;google1&quot;,&quot;google3;yahoo1&quot;,&quot;yahoo2;amazon2;google2&quot;)) </code></pre> <p>And an input dataframe like this:</p> <pre><code>dfdata &lt;- data.frame(id = c(&quot;id1&quot;, &quot;id2&quot;, &quot;id3&quot;), title1 = c(&quot;amazon1&quot;,&quot;google1&quot;,&quot;yahoo1&quot;), title2 = c(&quot;yahoo2&quot;,NA,&quot;amazon2&quot;)) </code></pre> <p>How is it possible to produce a dataframe with columns based the previous list:</p> <p>Expected output: dfdata &lt;- data.frame(id = c(&quot;id1&quot;, &quot;id2&quot;, &quot;id3&quot;), title1 = c(&quot;amazon1&quot;,&quot;google1&quot;,&quot;yahoo1&quot;), title2 = c(&quot;yahoo2&quot;,NA,&quot;amazon2&quot;), status1 = c(&quot;open/close&quot;,&quot;open/close&quot;,&quot;close&quot;), stock1 = c(&quot;company energy&quot;,&quot;company energy&quot;,&quot;goods and books&quot;), status2 = c(&quot;open&quot;,NA,&quot;open&quot;), stock2 = c(&quot;other&quot;,NA,&quot;other&quot;))</p> <blockquote> <pre><code> id title1 title2 status1 stock1 status2 1 id1 amazon1 yahoo2 open/close company energy open 2 id2 google1 &lt;NA&gt; open/close company energy &lt;NA&gt; 3 id3 yahoo1 amazon2 close goods and books open stock2 1 other 2 &lt;NA&gt; 3 other </code></pre> </blockquote> <p>This dataframe checks in dfdata in every column, expect the first id column, if any of the values in dfcheck dataframe exist and creates two new columns with the status and stock of dfcheck. From the dfcheck the column name has more than one values separated by &quot;;&quot;</p>
[ { "answer_id": 74575047, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(stringr)\nlibrary(tidyr)\n dfcheck dfcheck_tidy <- dfcheck %>%\n mutate(name = str_split(name, \";\")) %>%\n unnest(name)\n tidyr::separate dfdata %>%\n left_join(dfcheck_tidy,\n by = c(\"title1\" = \"name\")) %>%\n left_join(dfcheck_tidy,\n by = c(\"title2\" = \"name\"),\n suffix = c(\"1\", \"2\"))\n# id title1 title2 status1 stock1 status2 stock2\n# 1 id1 amazon1 yahoo2 open/close company energy open other\n# 2 id2 google1 <NA> open/close company energy <NA> <NA>\n# 3 id3 yahoo1 amazon2 close goods and books open other\n" }, { "answer_id": 74575204, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 1, "selected": false, "text": "regex_join() fuzzyjoin library(dplyr)\nlibrary(fuzzyjoin)\nregex_right_join(dfcheck, dfdata, by = c(name = \"title1\")) %>% \n regex_right_join(dfcheck, ., by = c(name = \"title2\")) %>% \n select(!contains(\"name\")) %>% \n relocate(id, title1, title2) \n id title1 title2 status.x stock.x status.y stock.y\n1 id1 amazon1 yahoo2 open other open/close company energy\n2 id2 google1 <NA> <NA> <NA> open/close company energy\n3 id3 yahoo1 amazon2 open other close goods and books\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20224217/" ]
74,574,705
<p>Be the following python pandas DataFrame:</p> <pre><code>| date | column_1 | column_2 | | ---------- | -------- | -------- | | 2022-02-01 | val | val2 | | 2022-02-03 | val1 | val | | 2022-02-01 | val | val3 | | 2022-02-04 | val2 | val | | 2022-02-27 | val2 | val4 | </code></pre> <p>I want to create a new DataFrame, where each row has a value between the minimum and maximum <code>date</code> value from the original DataFrame. The <code>counter column</code> contains a row counter for that date.</p> <pre><code>| date | counter | | ---------- | -------- | | 2022-02-01 | 2 | | 2022-02-02 | 0 | | 2022-02-03 | 1 | | 2022-02-04 | 1 | | 2022-02-05 | 0 | ... | 2022-02-26 | 0 | | 2022-02-27 | 1 | </code></pre>
[ { "answer_id": 74575064, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "df['counts'] = df['date'].map(df['date'].value_counts())\ndf = df.drop_duplicates(subset='date', keep=\"first\")\n\ndf.date = pd.to_datetime(df.date)\ndf = df.set_index('date').asfreq('D').reset_index()\ndf = df.fillna(0)\nprint(df)\n date counts\n0 2022-02-01 2.0\n1 2022-02-02 0.0\n2 2022-02-03 1.0\n3 2022-02-04 1.0\n4 2022-02-05 0.0\n5 2022-02-06 0.0\n6 2022-02-07 0.0\n7 2022-02-08 0.0\n8 2022-02-09 0.0\n9 2022-02-10 0.0\n10 2022-02-11 0.0\n11 2022-02-12 0.0\n12 2022-02-13 0.0\n13 2022-02-14 0.0\n14 2022-02-15 0.0\n15 2022-02-16 0.0\n16 2022-02-17 0.0\n17 2022-02-18 0.0\n18 2022-02-19 0.0\n19 2022-02-20 0.0\n20 2022-02-21 0.0\n21 2022-02-22 0.0\n22 2022-02-23 0.0\n23 2022-02-24 0.0\n24 2022-02-25 0.0\n25 2022-02-26 0.0\n" }, { "answer_id": 74575117, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 2, "selected": true, "text": ".apply import pandas as pd\nimport datetime\n\n# A minimal example (you should provide such an example next time)\ndf=pd.DataFrame({'date':pd.to_datetime(['2022-02-01', '2022-02-03', '2022-02-01', '2022-02-04', '2022-02-27']), 'c1':['val','val1','val','val2','val2'], 'c2':range(5)})\n\n# A delta of 1 day, to create list of date\ndt=datetime.timedelta(days=1)\n\n# Result dataframe, with a count of 0 for now\nres=pd.DataFrame({'date':df.date.min()+dt*np.arange((df.date.max()-df.date.min()).days+1), 'count':0})\n\n# Cound dates\ncountDates=df[['date', 'c1']].groupby('date').agg('count')\n\n# Merge the counted dates with the target array, filling missing values with 0\nres['count']=res.merge(countDates, on='date', how='left').fillna(0)['c1']\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18396935/" ]
74,574,715
<p>I tried with XPath but selenium can't click this image/button.</p> <p><a href="https://i.stack.imgur.com/LBJiu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LBJiu.png" alt="enter image description here" /></a></p> <pre><code>from undetected_chromedriver.v2 import Chrome def test(): driver = Chrome() driver.get('https://bandit.camp') WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,&quot;/html/body/div[1]/div/main/div/div/div/div/div[5]/div/div[2]/div/div[3]/div&quot;))).click() if __name__ == &quot;__main__&quot;: test() </code></pre>
[ { "answer_id": 74575064, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "df['counts'] = df['date'].map(df['date'].value_counts())\ndf = df.drop_duplicates(subset='date', keep=\"first\")\n\ndf.date = pd.to_datetime(df.date)\ndf = df.set_index('date').asfreq('D').reset_index()\ndf = df.fillna(0)\nprint(df)\n date counts\n0 2022-02-01 2.0\n1 2022-02-02 0.0\n2 2022-02-03 1.0\n3 2022-02-04 1.0\n4 2022-02-05 0.0\n5 2022-02-06 0.0\n6 2022-02-07 0.0\n7 2022-02-08 0.0\n8 2022-02-09 0.0\n9 2022-02-10 0.0\n10 2022-02-11 0.0\n11 2022-02-12 0.0\n12 2022-02-13 0.0\n13 2022-02-14 0.0\n14 2022-02-15 0.0\n15 2022-02-16 0.0\n16 2022-02-17 0.0\n17 2022-02-18 0.0\n18 2022-02-19 0.0\n19 2022-02-20 0.0\n20 2022-02-21 0.0\n21 2022-02-22 0.0\n22 2022-02-23 0.0\n23 2022-02-24 0.0\n24 2022-02-25 0.0\n25 2022-02-26 0.0\n" }, { "answer_id": 74575117, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 2, "selected": true, "text": ".apply import pandas as pd\nimport datetime\n\n# A minimal example (you should provide such an example next time)\ndf=pd.DataFrame({'date':pd.to_datetime(['2022-02-01', '2022-02-03', '2022-02-01', '2022-02-04', '2022-02-27']), 'c1':['val','val1','val','val2','val2'], 'c2':range(5)})\n\n# A delta of 1 day, to create list of date\ndt=datetime.timedelta(days=1)\n\n# Result dataframe, with a count of 0 for now\nres=pd.DataFrame({'date':df.date.min()+dt*np.arange((df.date.max()-df.date.min()).days+1), 'count':0})\n\n# Cound dates\ncountDates=df[['date', 'c1']].groupby('date').agg('count')\n\n# Merge the counted dates with the target array, filling missing values with 0\nres['count']=res.merge(countDates, on='date', how='left').fillna(0)['c1']\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16071785/" ]
74,574,723
<p>The objective is simple: I'm building a car rental platform where customers can place an order for a car. The simple 'order' contains the car, start, and end-dates. The form should automatically save the authenticated user as the creator.</p> <p>It uses a CreateView with this code:</p> <pre><code>class BookingCreate(CreateView): model = Booking fields = ['car', 'start_date', 'end_date'] permission_classes = [permissions.IsAuthenticated] def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) </code></pre> <p>The form works fine, but when submitted, it raises this error:</p> <blockquote> <p>ValueError at /rentals/booking/create Cannot assign &quot;&lt;SimpleLazyObject: &lt;CustomUser: Test2 Two&gt;&gt;&quot;: &quot;Booking.user&quot; must be a &quot;Customer&quot; instance.</p> </blockquote> <p>I've looked up previous answers, and the best solution came from <a href="https://stackoverflow.com/questions/62220778/cannot-assign-simplelazyobject-for-customuser-model-in-django">this</a> thread, which recommended using this code instead</p> <pre><code> def form_valid(self, form): form.instance.user = Booking.objects.get(user=self.request.user) return super().form_valid(form) </code></pre> <p>However, this change returns a slightly different error:</p> <blockquote> <p>ValueError at /rentals/booking/create Cannot query &quot;Test2 Two&quot;: Must be &quot;Customer&quot; instance. I have a customUser Model and a &quot;customer&quot; model that inherits from it.</p> </blockquote> <p>For additional context, I am using a customUser model. Because I have multiple user types (in particular (car) Owners and Customers), I use a special table with boolean fields to mark each type as True based on the registration form they use per this <a href="https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html" rel="nofollow noreferrer">this</a> tutorial.</p> <p>Here's the relevant code (there's a lot, so I've only added the relevant parts):</p> <p><strong>models.py</strong></p> <pre><code>from accounts.models import CustomUser class User(CustomUser): is_customer = models.BooleanField(default=False) is_owner = models.BooleanField(default=False) class Owner(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.first_name class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) cars = models.ManyToManyField('Car', blank=True) ... def get_absolute_url(self): return reverse('rental:customer-detail', args=[str(self.id)]) def __str__(self): return f'{ self.user.first_name } { self.user.last_name }' class Booking(models.Model): &quot;&quot;&quot;Stores the bookings, for example when it was made, the booking date, and the car ID.&quot;&quot;&quot; # Unique ID for this booking. id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text=&quot;Automatically generated unique ID. Do not change.&quot;) user = models.ForeignKey('Customer', on_delete=models.SET_NULL, null=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True) start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True) ... </code></pre> <hr /> <p><strong>Solution and extra resources for future explorers</strong></p> <p>Both answers below helped, but the issue kept coming back. The permanent solution was this line of code:</p> <pre><code> def form_valid(self, form): form.instance.created_by = Customer.objects.get(pk=self.request.user.pk) return super().form_valid(form) </code></pre> <p>As alluded to in the question above, this is a common problem. So here are three other threads to look at, each with great answers:</p> <p><a href="https://stackoverflow.com/questions/60780434/valueerror-at-post-new-cannot-assign-simplelazyobjectuser-chetan-pos">ValueError at /post/new/ Cannot assign &quot;&lt;SimpleLazyObject:&lt;User: chetan&gt;&gt;&quot;: &quot;Post.author&quot; must be a &quot;User&quot; instance</a></p> <p><a href="https://stackoverflow.com/questions/35567667/cannot-assign-simplelazyobject-user-xxx-comment-user-must-be-a-mypro">Cannot assign &quot;&lt;SimpleLazyObject: &lt;User: XXX&gt;&gt;&quot;: &quot;Comment.user&quot; must be a &quot;MyProfile&quot; instance</a></p> <p><a href="https://stackoverflow.com/questions/54175494/cannot-assign-simplelazyobject-user-johndoe12-profile-user-must-be-a">Cannot assign &quot;&lt;SimpleLazyObject: &lt;User: JohnDoe12&gt;&gt;&quot;: &quot;Profile.user&quot; must be a &quot;User&quot; instance</a></p>
[ { "answer_id": 74575064, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 2, "selected": false, "text": "df['counts'] = df['date'].map(df['date'].value_counts())\ndf = df.drop_duplicates(subset='date', keep=\"first\")\n\ndf.date = pd.to_datetime(df.date)\ndf = df.set_index('date').asfreq('D').reset_index()\ndf = df.fillna(0)\nprint(df)\n date counts\n0 2022-02-01 2.0\n1 2022-02-02 0.0\n2 2022-02-03 1.0\n3 2022-02-04 1.0\n4 2022-02-05 0.0\n5 2022-02-06 0.0\n6 2022-02-07 0.0\n7 2022-02-08 0.0\n8 2022-02-09 0.0\n9 2022-02-10 0.0\n10 2022-02-11 0.0\n11 2022-02-12 0.0\n12 2022-02-13 0.0\n13 2022-02-14 0.0\n14 2022-02-15 0.0\n15 2022-02-16 0.0\n16 2022-02-17 0.0\n17 2022-02-18 0.0\n18 2022-02-19 0.0\n19 2022-02-20 0.0\n20 2022-02-21 0.0\n21 2022-02-22 0.0\n22 2022-02-23 0.0\n23 2022-02-24 0.0\n24 2022-02-25 0.0\n25 2022-02-26 0.0\n" }, { "answer_id": 74575117, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 2, "selected": true, "text": ".apply import pandas as pd\nimport datetime\n\n# A minimal example (you should provide such an example next time)\ndf=pd.DataFrame({'date':pd.to_datetime(['2022-02-01', '2022-02-03', '2022-02-01', '2022-02-04', '2022-02-27']), 'c1':['val','val1','val','val2','val2'], 'c2':range(5)})\n\n# A delta of 1 day, to create list of date\ndt=datetime.timedelta(days=1)\n\n# Result dataframe, with a count of 0 for now\nres=pd.DataFrame({'date':df.date.min()+dt*np.arange((df.date.max()-df.date.min()).days+1), 'count':0})\n\n# Cound dates\ncountDates=df[['date', 'c1']].groupby('date').agg('count')\n\n# Merge the counted dates with the target array, filling missing values with 0\nres['count']=res.merge(countDates, on='date', how='left').fillna(0)['c1']\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7032374/" ]
74,574,814
<p>I just found that we can use this attribute to specify which case the letters should be entered in, but that doesn't work for me.</p> <p>Example:</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-html lang-html prettyprint-override"><code>&lt;input type="text" autocapitalize="words" name="subject" value="Website Feedback" /&gt;</code></pre> </div> </div> </p> <p>I set this attr to <strong>words</strong> but still type with lover case each new word, so how it should work?</p>
[ { "answer_id": 74621013, "author": "Daniel Cruz", "author_id": 17537072, "author_profile": "https://Stackoverflow.com/users/17537072", "pm_score": 2, "selected": true, "text": "$(\".autocapitalize\").keyup(function () {\n const originalValue = $(this).val();\n const capitalizedValue = originalValue.replace(/(^\\w{1})|(\\s+\\w{1})/g, letter => letter.toUpperCase());\n $(this).val(capitalizedValue).focus()\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<input type=\"text\" class=\"autocapitalize\" autocapitalize=\"words\" name=\"subject\" value=\"\" />" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15464003/" ]
74,574,820
<p>Hello I try to refresh <code>_currentValue</code> when I open a modal bottom sheet and I change the value from state full widget <code>depense()</code>.</p> <p>Here is my code</p> <pre><code>new RaisedButton( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), elevation: 5, highlightElevation: 10, color: Colors.white, splashColor: Colors.white, child : new Text(&quot;${_currentValue}&quot;,textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontWeight: FontWeight.w400, fontSize: SizeConfig.safeBlockHorizontal! * 4)), padding: const EdgeInsets.all (15.0), onPressed: () { setState(() { showMaterialModalBottomSheet(isDismissible: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15)), context: context, builder: (context) =&gt; depense() ); }); }), </code></pre> <hr /> <pre><code>class depense extends StatefulWidget { const depense({Key? key}) : super(key: key); @override State&lt;depense&gt; createState() =&gt; _depenseState(); } class _depenseState extends State&lt;depense&gt; { int _currentValue = 5; @override void initState() { // TODO: implement initState super.initState(); } @override Widget build(BuildContext context) { return Container( width: MediaQuery.of(context).size.width/1, height: MediaQuery.of(context).size.height/1.8, child : Padding( padding: const EdgeInsets.only(left:20,right:20), child: Container( alignment: Alignment.center, child: NumberPicker( axis: Axis.horizontal, itemHeight: 70, itemWidth: 70, step: 1, selectedTextStyle: const TextStyle( fontSize: 30.0, color: Color(0xff61d3cb), fontWeight: FontWeight.w800, ), textStyle: const TextStyle( color: Colors.black, fontSize: 12.0, ), value: _currentValue, minValue: 0, maxValue: 1000, onChanged: (v) { setState(() { _currentValue = v; }); }, ), ), )); } } </code></pre> <p>If I add the widget build from depense state full widget directly on the modalbottomsheet like bellow, <code>Text(&quot;${_currentValue}&quot;</code> is upgrade but NumberPicker return to initial value... But when I create the statefull widget I can use NumberPicker but not refresh data...</p> <pre><code> new RaisedButton( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), elevation: 5, highlightElevation: 10, color: Colors.white, splashColor: Colors.white, child : new Text(&quot;${_currentValue}&quot;,textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontWeight: FontWeight.w400, fontSize: SizeConfig.safeBlockHorizontal! * 4)), padding: const EdgeInsets.all (15.0), onPressed: () { setState(() { showMaterialModalBottomSheet(isDismissible: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15)), context: context, builder: (context) =&gt; Container( width: MediaQuery.of(context).size.width/1, height: MediaQuery.of(context).size.height/1.8, child : Padding( padding: const EdgeInsets.only(left:20,right:20), child: Container( alignment: Alignment.center, child: NumberPicker( axis: Axis.horizontal, itemHeight: 70, itemWidth: 70, step: 1, selectedTextStyle: const TextStyle( fontSize: 30.0, color: Color(0xff61d3cb), fontWeight: FontWeight.w800, ), textStyle: const TextStyle( color: Colors.black, fontSize: 12.0, ), value: _currentValue, minValue: 0, maxValue: 1000, onChanged: (v) { setState(() { _currentValue = v; }); }, ), ), )) ); }); }), </code></pre>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611719/" ]
74,574,827
<p>I have a file that has such a structure:</p> <pre><code>section &quot;first_section&quot; { parameter1 = value1 parameter2 = value2 parameter3 = value3 } section &quot;second_section&quot; { parameter1 = value1 parameter2 = value2 parameter3 = value3 } ... </code></pre> <p>And I have a variable that contains a new section, for example:</p> <pre><code> section &quot;third_section&quot; { parameter1 = value1 parameter2 = value2 parameter3 = value3 } </code></pre> <p>I'd like to check in Bash before adding a new section if that section already exists in the file.</p> <p>I was trying something like</p> <pre><code>if grep -q -z &quot;$section&quot; file.txt then echo &quot;Duplicate found&quot; else echo &quot;$section&quot; &gt;&gt; ./file.txt fi </code></pre> <p>However, I always get a <code>Duplicate found</code> output even if it is not true.</p>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600493/" ]
74,574,860
<p>I made a code for Blackjack in Python and whenever I run blackjack_game(deck) saying no to the 'Play Again' input should quit the game but it doesn't. Funds going zero and below should also trigger the game to quit but it doesn't.</p> <p>This is what it looks like:</p> <pre><code>import random import os # The Card class definition class Card: def __init__(self, suit, value, card_value): # Suit of the Card like Spades and Clubs self.suit = suit # Representing Value of the Card like A for Ace, K for King self.value = value # Score Value for the Card like 10 for King self.card_value = card_value # Clear the terminal def clear(): os.system(&quot;clear&quot;) # Print player stats def print_stats(player_name, funds, wins, losses, ties, blackjacks, busts): print('Player: ', player_name) print('Funds: $', funds) print(f'Wins: {wins} Losses: {losses} Ties: {ties} Blackjacks: {blackjacks} Busts: {busts}') # Function to print the cards def print_cards(cards, hidden): s = &quot;&quot; for card in cards: s = s + &quot;\t ________________&quot; if hidden: s += &quot;\t ________________&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| |&quot; print(s) s = &quot;&quot; for card in cards: if card.value == '10': s = s + &quot;\t| {} |&quot;.format(card.value) else: s = s + &quot;\t| {} |&quot;.format(card.value) if hidden: s += &quot;\t| |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| * * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| * * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| * * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| * * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| {} |&quot;.format(card.suit) if hidden: s += &quot;\t| * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t| |&quot; if hidden: s += &quot;\t| |&quot; print(s) s = &quot;&quot; for card in cards: if card.value == '10': s = s + &quot;\t| {} |&quot;.format(card.value) else: s = s + &quot;\t| {} |&quot;.format(card.value) if hidden: s += &quot;\t| * |&quot; print(s) s = &quot;&quot; for card in cards: s = s + &quot;\t|________________|&quot; if hidden: s += &quot;\t|________________|&quot; print(s) print() # Function for a game of blackjack def blackjack_game(deck): end_game = False play_again = 'Y' # Player name player_name = str(input('Enter player name: ')) # Intro print('Lets have a fun game of Blackjack, ', player_name) # Cards for both dealer and player player_cards = [] dealer_cards = [] # Scores for both dealer and player player_score = 0 dealer_score = 0 # Player stats funds = 100 wins = 0 losses = 0 ties = 0 blackjacks = 0 busts = 0 bet = 0 clear() # Current Stats Display print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) # Bets while play_again == 'Y': while end_game == False: while funds &gt; 0: while bet == 0: bet = int(input('Enter bet amount: ')) if bet &gt; funds: print('Insufficient funds') bet = 0 # Initial dealing for player and dealer while len(player_cards) &lt; 2: # Randomly dealing a card player_card = random.choice(deck) player_cards.append(player_card) deck.remove(player_card) # Updating the player score player_score += player_card.card_value # In case both the cards are Ace, make the first ace value as 1 if len(player_cards) == 2: if player_cards[0].card_value == 11 and player_cards[1].card_value == 11: player_cards[0].card_value = 1 player_score -= 10 # Print player cards and score print(&quot;PLAYER CARDS: &quot;) print_cards(player_cards, False) print(&quot;PLAYER SCORE = &quot;, player_score) input() # Randomly dealing a card dealer_card = random.choice(deck) dealer_cards.append(dealer_card) deck.remove(dealer_card) # Updating the dealer score dealer_score += dealer_card.card_value # Print dealer cards and score, keeping in mind to hide the second card and score print(&quot;DEALER CARDS: &quot;) if len(dealer_cards) == 1: print_cards(dealer_cards, False) print(&quot;DEALER SCORE = &quot;, dealer_score) else: print_cards(dealer_cards[:-1], True) print(&quot;DEALER SCORE = &quot;, dealer_score - dealer_cards[-1].card_value) # In case both the cards are Ace, make the second ace value as 1 if len(dealer_cards) == 2: if dealer_cards[0].card_value == 11 and dealer_cards[1].card_value == 11: dealer_cards[1].card_value = 1 dealer_score -= 10 input() clear() # Print dealer and player cards print(&quot;DEALER CARDS: &quot;) print_cards(dealer_cards[:-1], True) print(&quot;DEALER SCORE = &quot;, dealer_score - dealer_cards[-1].card_value) print() print(&quot;PLAYER CARDS: &quot;) print_cards(player_cards, False) print(&quot;PLAYER SCORE = &quot;, player_score) # Managing the player moves while player_score &lt; 21: choice = input(&quot;Enter H to Hit or S to Stand : &quot;) # Sanity checks for player's choice if len(choice) != 1 or (choice.upper() != 'H' and choice.upper() != 'S'): clear() print(&quot;Wrong choice!! Try Again&quot;) # If player decides to HIT if choice.upper() == 'H': # Dealing a new card player_card = random.choice(deck) player_cards.append(player_card) deck.remove(player_card) # Updating player score player_score += player_card.card_value # Updating player score in case player's card have ace in them c = 0 while player_score &gt; 21 and c &lt; len(player_cards): if player_cards[c].card_value == 11: player_cards[c].card_value = 1 player_score -= 10 c += 1 else: c += 1 clear() # Print player and dealer cards print(&quot;DEALER CARDS: &quot;) print_cards(dealer_cards[:-1], True) print(&quot;DEALER SCORE = &quot;, dealer_score - dealer_cards[-1].card_value) print() print(&quot;PLAYER CARDS: &quot;) print_cards(player_cards, False) print(&quot;PLAYER SCORE = &quot;, player_score) # If player decides to Stand if choice.upper() == 'S': break clear() # Print player and dealer cards print(&quot;PLAYER CARDS: &quot;) print_cards(player_cards, False) print(&quot;PLAYER SCORE = &quot;, player_score) print() print(&quot;DEALER IS REVEALING THE CARDS....&quot;) print(&quot;DEALER CARDS: &quot;) print_cards(dealer_cards, False) print(&quot;DEALER SCORE = &quot;, dealer_score) # Check if player has a Blackjack if player_score == 21: print(&quot;PLAYER HAS A BLACKJACK&quot;) blackjacks += 1 # Check if player busts if player_score &gt; 21: print(&quot;PLAYER BUSTED!!!&quot;) busts += 1 print(&quot;DEALER WINS!!!&quot;) losses += 1 funds -= bet bet = 0 print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() player_cards = [] dealer_cards = [] player_score = 0 dealer_score = 0 end_game = True input() # Managing the dealer moves while dealer_score &lt; 17: clear() print(&quot;DEALER DECIDES TO HIT.....&quot;) # Dealing card for dealer dealer_card = random.choice(deck) dealer_cards.append(dealer_card) deck.remove(dealer_card) # Updating the dealer's score dealer_score += dealer_card.card_value # Updating player score in case player's card have ace in them c = 0 while dealer_score &gt; 21 and c &lt; len(dealer_cards): if dealer_cards[c].card_value == 11: dealer_cards[c].card_value = 1 dealer_score -= 10 c += 1 else: c += 1 # print player and dealer cards print(&quot;PLAYER CARDS: &quot;) print_cards(player_cards, False) print(&quot;PLAYER SCORE = &quot;, player_score) print() print(&quot;DEALER CARDS: &quot;) print_cards(dealer_cards, False) print(&quot;DEALER SCORE = &quot;, dealer_score) input() # TIE Game if dealer_score == player_score: print(&quot;TIE GAME!!!!&quot;) ties += 1 bet = 0 print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() player_cards = [] dealer_cards = [] player_score = 0 dealer_score = 0 end_game = True # Dealer busts elif dealer_score &gt; 21: print(&quot;DEALER BUSTED!!! YOU WIN!!!&quot;) wins += 1 funds += bet bet = 0 print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() player_cards = [] dealer_cards = [] player_score = 0 dealer_score = 0 end_game = True # Dealer gets a blackjack elif dealer_score == 21: print(&quot;DEALER HAS A BLACKJACK!!! PLAYER LOSES&quot;) losses += 1 funds -= bet bet = 0 print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() player_cards = [] dealer_cards = [] player_score = 0 dealer_score = 0 end_game = True # Player Wins elif player_score &lt; 21 and player_score &gt; dealer_score: print(&quot;PLAYER WINS!!!&quot;) wins += 1 funds += bet bet = 0 print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() player_cards = [] dealer_cards = [] player_score = 0 dealer_score = 0 end_game = True # Dealer Wins else: print(&quot;DEALER WINS!!!&quot;) losses += 1 funds -= bet bet = 0 print_stats(player_name, funds, wins, losses, ties, blackjacks, busts) end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() player_cards = [] dealer_cards = [] player_score = 0 dealer_score = 0 end_game = True quit() if __name__ == '__main__': # The type of suit suits = [&quot;Spades&quot;, &quot;Hearts&quot;, &quot;Clubs&quot;, &quot;Diamonds&quot;] # The suit value suits_values = {&quot;Spades&quot;:&quot;\u2664&quot;, &quot;Hearts&quot;:&quot;\u2661&quot;, &quot;Clubs&quot;: &quot;\u2667&quot;, &quot;Diamonds&quot;: &quot;\u2662&quot;} # The type of card cards = [&quot;A&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;, &quot;J&quot;, &quot;Q&quot;, &quot;K&quot;] # The card value cards_values = {&quot;A&quot;: 11, &quot;2&quot;:2, &quot;3&quot;:3, &quot;4&quot;:4, &quot;5&quot;:5, &quot;6&quot;:6, &quot;7&quot;:7, &quot;8&quot;:8, &quot;9&quot;:9, &quot;10&quot;:10, &quot;J&quot;:10, &quot;Q&quot;:10, &quot;K&quot;:10} # The deck of cards deck = [] # Loop for every type of suit for suit in suits: # Loop for every type of card in a suit for card in cards: # Adding card to the deck deck.append(Card(suits_values[suit], card, cards_values[card])) </code></pre> <p>I added a quit() that should trigger should 'while play_again == 'Y':' no longer be true. This should have quit the game and stopped it from running. Instead it prompts the user again for a betting amount, acting as if I chose 'Y' instead.</p> <p>I also tried removing:</p> <pre><code>play_again = 'Y' </code></pre> <p>and replacing this code block:</p> <pre><code>end_choice = input('Play again(Y/N)?: ') play_again = end_choice.upper() </code></pre> <p>with this:</p> <pre><code>end_choice = input('Play again(Y/N)?: ') if end_choice.upper() == 'N': exit() </code></pre> <p>But it still wouldn't quit and stayed as an infinite loop. Help me please, I've been stuck with this issue all day.</p>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20599868/" ]
74,574,866
<p>from snowflake.connector import connect as snowflake_connector</p> <pre class="lang-py prettyprint-override"><code> from snowflake.connector import connect SNOWFLAKE_ACCOUNT = r'my_account' SNOWFLAKE_USERNAME = r'my_username' SNOWFLAKE_PASSWORD = r'my_password' try: conn = connect( user=SNOWFLAKE_USERNAME, password=SNOWFLAKE_PASSWORD, account=SNOWFLAKE_ACCOUNT, warehouse='W1', database='DB1', schema='SC1' ) except Exception as e: raise e </code></pre> <p>This used to work fine, but I must have upgraded something or changed - and now it results in this error (in VS Code's Jupyter Notebooks, and it's also a kernel crash):</p> <pre><code>Canceled future for execute_request message before replies were done The Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click here for more info. View Jupyter log for further details. </code></pre> <p>I don't want to use sqlalchemy or pd.read_sql because I'm using the pyarrow format for data transfer.</p> <p>Any ideas? Using snowflake connector 2.8.2 And pyarrow 8.0.0</p> <p>Here is the Jupyter Log traceback: It seems the issue is with traitlets (I have version 5.4.0)</p> <pre><code> info 15:24:44.741: Started Kernel Python 3.10.7 64-bit (pid: 4548) info 15:24:44.747: UpdateWorkingDirectoryAndPath in Kernel error 15:24:47.233: Disposing session as kernel process died ExitCode: 3221225725, Reason: c:\Users\mkleinbort\AppData\Local\Programs\Python\Python310\lib\site-packages\traitlets\traitlets.py:2412: FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '&quot;hmac-sha256&quot;' if you require traitlets &gt;=5. warn( c:\Users\mkleinbort\AppData\Local\Programs\Python\Python310\lib\site-packages\traitlets\traitlets.py:2366: FutureWarning: Supporting extra quotes around Bytes is deprecated in traitlets 5.0. Use 'cd273979-f6a3-426f-b65e-7098ec266fa7' instead of 'b&quot;cd273979-f6a3-426f-b65e-7098ec266fa7&quot;'. warn( info 15:24:47.233: Dispose Kernel process 4548. error 15:24:47.233: Raw kernel process exited code: 3221225725 error 15:24:47.234: Error in waiting for cell to complete [Error: Canceled future for execute_request message before replies were done at t.KernelShellFutureHandler.dispose (c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:32353) at c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:51405 at Map.forEach (&lt;anonymous&gt;) at y._clearKernelState (c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:51390) at y.dispose (c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:44872) at c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:2218404 at t.swallowExceptions (c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:7:130943) at p.dispose (c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:2218382) at t.RawSession.dispose (c:\Users\mkleinbort\.vscode\extensions\ms-toolsai.jupyter-2022.9.1303220346\out\extension.node.js:2:2223490) at process.processTicksAndRejections (node:internal/process/task_queues:96:5)] warn 15:24:47.235: Cell completed with errors { message: 'Canceled future for execute_request message before replies were done' } info 15:24:47.237: Cancel all remaining cells true || Error || undefined warn 15:24:47.247: 2022-11-25 15:24:47,237 UTC - WARNING - Unknown command: DISPOSE_INTERRUPT_HANDLE:11:2568 </code></pre>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17194313/" ]
74,574,877
<p>I have a list of names in a column e.g.:</p> <p>Bob Adam Smith, Steve Jobs, Stacy Jones</p> <p>I’d like to use these names for a case study presentation, but they have to be anonymized.</p> <p>I imagine something like: B@b A@@m S@@@h, S@@@e J@@s, S@@@y J@@@s</p> <p>(But with asterisks instead of @)</p> <p>The problem is that some people have very long and very short names or some have middle names and others don’t, so I’m not sure if it’s even possible with good old excel formulas.</p> <p>Something like: “=RIGHT(A1,2)&amp;”**** ****”&amp;RIGHT(A3,2)”</p> <p>Gives me: Bo**** ****th</p> <p>Which obviously is no good</p> <p>I’m open to VBA solutions, but I’m a beginner there, so please play nice.</p>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600500/" ]
74,574,894
<h4>Goal:</h4> <p>I have a sneaking suspicion that I'm globbing incorrectly due to not being able to find a satisfactory explanation with multiple clear examples of advanced string-and-var mixing.</p> <p>The operation I am trying to perform is on the last line, and the goal is to output the outputdirectory + filebasename + outputextension. Unfortunately, there are too many variables, and despite reading multiple manuals, I feel certain I am making mistakes.</p> <pre><code>#!/bin/bash echo Input directory name like ./path/to: read -r varin echo Input directory name like ./path/to: read -r varout if [ ! -d &quot;${varout}&quot; ]; then mkdir -p &quot;${varout}&quot;; fi for file in ${varin}; do pconvert -i &quot;${file}&quot; -o &quot;${varout}&quot;/&quot;${file%%.*}&quot;.txt; done </code></pre> <p>error: <code>File './inputs/outputs/*/.txt' already exists. Overwrite ? [y/N] ^C</code></p> <h4>Unexpected behavior:</h4> <ol> <li>I have to write <code>./inputs/*</code> instead of <code>./inputs</code>, and this is unexpected. I expected bash to look for a directory then loop through the files in that directory: this is fine, but it shows that I am not comprehending the code.</li> <li>Presuming I type <code>./inputs/outputs/*</code>, this script tries to create <code>./inputs/outputs/*.txt</code> on each iteration rather than <code>./inputs/outputs/inputname.txt</code>. The goal in the last operation on line 15 is to scrub the directory, scrub the extension, and use the new path + basename + newextension. Kind of the blind leading the blind, but I feel like this can only have something to do with my use of quotation marks?</li> </ol> <h4>Resources I've used:</h4> <p>According to <a href="https://mywiki.wooledge.org/Quotes" rel="nofollow noreferrer">this link</a>, I should probably do something like this:</p> <pre><code>convertdoc -i &quot;$'{file}'&quot; --pdfconvert -o &quot;$'{outputDir}'/$'{file%%.*}'.odf </code></pre> <p>But I am getting mixed opinions from friends. So far, I've been told to use no trailing quote, to only use semiquotes, to use quotes both prior to and after the dollar sign, and to be pipe down, to mention a few.</p> <p>Sample inputs:</p> <pre><code>$HOME/pdfdl/ardvarks.pdf $HOME/pdfdl/ants.pdf $HOME/pdfdl/canines.pdf $HOME/pdfdl/cats.tmp.pdf </code></pre>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445651/" ]
74,574,895
<p>I'm trying to build an estimator to compare the asymptotics of the GLS and OLS estimators. My idea is to try and see what happens at large samples, and with many of them.</p> <p>Ideally, I would like to create a loop that would generate 6000 different random samples, of sizes 50 and 100 each, for different parameter values.</p> <pre><code>N=1000 n=c(50, 100) #parameters alpha0=1 beta0=1 gamma0=c(0, 0.1, 0.5) alpha1=matrix(NA,N,6) beta1=matrix(NA,N,6) alpha2=matrix(NA,N,6) beta2=matrix(NA,N,6) alphaOLS=matrix(NA,N,6) betaOLS=matrix(NA,N,6) </code></pre> <p>the different samples come from the combinations of gamma0 and n, which would equal 6 (times N) to get 6000. My first idea was to build a loop for the generation of the random samples the model I'm trying to work with is the following y_i=alpha+beta*x_i+u_i</p> <p>u_i=e_i*h(x_i)^(1/2) and h(x)=exp(gamma0)</p> <pre><code>u &lt;- list() for (i in n) { for (k in gamma0) { x=rnorm(i,0,1) h=exp(gamma0[k]*x) e=rnorm(i,0,1) u[[i]] &lt;- e*h^(1/2) } } </code></pre> <p>The issue with this loop is that I'm only getting one random sample in x and e, and h is coming out as an empty matrix, and hence, u is also coming out empty. h here should be a matrix where the columns correspond to x* the different values of gamma0. e is supposed to be N(0,1) and u is meant to be the residual of the model</p> <p>My ideal output should be get this loop to work, because from there on, I can sort my way around building an OLS and GLS estimator manually.</p> <p>Thanks a lot!</p>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18029734/" ]
74,574,913
<p><a href="https://i.stack.imgur.com/k8IBX.png" rel="nofollow noreferrer">Design preview Not visible in Android Studio</a></p> <p>The design preview for all other activities are visible, but for this specific activity(quiz_page.xml) the design preview is not visible.</p> <p>I have tried all the things on the Internet including</p> <ol> <li>Invalid caches</li> <li>Force Refresh layout</li> <li>Disabled and enabled Android support plugins</li> </ol>
[ { "answer_id": 74575115, "author": "Sanketh B. K", "author_id": 10553747, "author_profile": "https://Stackoverflow.com/users/10553747", "pm_score": 0, "selected": false, "text": "class depense extends StatefulWidget {\n Function changeCurrentValue(int val);\n\n const depense({Key? key}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n ...\n\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width/1,\n height: MediaQuery.of(context).size.height/1.8,\n child :\n ...\n onChanged: (v) {\n widget.changeCurrentValue(v);\n }\n int _currentValue = 5;\n\nvoid changeCurrentValue(int v){\n setState(() {\n _currentValue = v;\n })\n}\n\nnew RaisedButton(\n ...\n showMaterialModalBottomSheet(isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius:\n BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(changeCurrentValue: changeCurrentValue)\n ....\n\n \n\n\n \n" }, { "answer_id": 74575176, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "currentValue depense class depense extends StatefulWidget {\n final Function(int) onChange; //<-- add this\n const depense({Key? key, required this.onChange}) : super(key: key);\n\n @override\n State<depense> createState() => _depenseState();\n}\n\nclass _depenseState extends State<depense> {\n int _currentValue = 5;\n @override\n Widget build(BuildContext context) {\n return Container(\n width: MediaQuery.of(context).size.width / 1,\n height: MediaQuery.of(context).size.height / 1.8,\n child: Padding(\n padding: const EdgeInsets.only(left: 20, right: 20),\n child: Container(\n alignment: Alignment.center,\n child: NumberPicker(\n axis: Axis.horizontal,\n itemHeight: 70,\n itemWidth: 70,\n step: 1,\n selectedTextStyle: const TextStyle(\n fontSize: 30.0,\n color: Color(0xff61d3cb),\n fontWeight: FontWeight.w800,\n ),\n textStyle: const TextStyle(\n color: Colors.black,\n fontSize: 12.0,\n ),\n value: _currentValue,\n minValue: 0,\n maxValue: 1000,\n onChanged: (v) {\n widget.onChange(v);\n setState(() {\n _currentValue = v;\n });\n },\n ),\n ),\n ));\n }\n}\n RaisedButton(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10)),\n elevation: 5,\n highlightElevation: 10,\n color: Colors.white,\n splashColor: Colors.white,\n child: new Text(\"${_currentValue}\",\n textAlign: TextAlign.center,\n style: TextStyle(\n color: Colors.black,\n fontWeight: FontWeight.w400,\n fontSize: SizeConfig.safeBlockHorizontal! * 4)),\n padding: const EdgeInsets.all(15.0),\n onPressed: () {\n setState(() {\n showMaterialModalBottomSheet(\n isDismissible: true,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15)),\n context: context,\n builder: (context) => depense(onChange:(value){\n setState(() {\n _currentValue = value;\n });\n }));\n });\n })\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600451/" ]
74,574,914
<p>I have an SVG image that uses masking to cut out a hole in another shape. I've simplified the complex shapes involved down to this representative example:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot; ?&gt; &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; version=&quot;1.1&quot; width=&quot;256&quot; height=&quot;256&quot; viewBox=&quot;0 0 256 256&quot; xml:space=&quot;preserve&quot;&gt; &lt;defs&gt; &lt;mask id=&quot;mask&quot;&gt; &lt;rect x=&quot;0&quot; y=&quot;0&quot; width=&quot;256&quot; height=&quot;256&quot; fill=&quot;#ffffff&quot; /&gt; &lt;circle cx=&quot;128&quot; cy=&quot;128&quot; r=&quot;32&quot; fill=&quot;#000000&quot; /&gt; &lt;/mask&gt; &lt;/defs&gt; &lt;circle mask=&quot;url(#mask)&quot; cx=&quot;128&quot; cy=&quot;128&quot; r=&quot;64&quot; fill=&quot;#ff0000&quot; /&gt; &lt;/svg&gt; </code></pre> <p>This works as expected, i.e., draws the following donut shape, in pretty much every context:</p> <p><a href="https://i.stack.imgur.com/kLD6m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kLD6m.png" alt="enter image description here" /></a></p> <p>However, if I inline the SVG in an email and view it in macOS Mail (16.0, comes with Monterey 12.3.1) or iOS Mail while dark mode is enabled, I get this peculiar version:</p> <p><a href="https://i.stack.imgur.com/Yv5zi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yv5zi.png" alt="enter image description here" /></a></p> <p>What appears to be happening is that these two apps are trying to guess at a dark-mode interpretation of the SVG, and have erroneously changed the mask's <code>#ffffff</code> to a very dark grey (<code>#232323</code>, if I had to guess, which is the background color of the application itself in dark mode) and <code>#000000</code> to <code>#ffffff</code>, thereby mostly but not entirely inverting the masking behavior.</p> <p>This seems like a bug in Mail. Is there a way to tell Mail to not mess with the colors defined in the mask? I tried a couple workarounds, but they were insufficient:</p> <ul> <li>using <code>prefers-color-scheme</code> to define the mask's colors so I can &quot;pre-invert&quot; it for dark mode, which works here but breaks the image in every <em>other</em> context</li> <li>obscuring the mask coloration enough that it won't try to invert it (e.g. by using <code>linear-gradient(#ffffff,#ffffff)</code> instead of just <code>#ffffff</code>), which just breaks the images everywhere</li> </ul>
[ { "answer_id": 74584915, "author": "skelley", "author_id": 3736239, "author_profile": "https://Stackoverflow.com/users/3736239", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" width=\"256\" height=\"256\" viewBox=\"0 0 256 256\" xml:space=\"preserve\">\n <defs>\n <mask id=\"mask\" mask-type=\"alpha\">\n <path\n d=\"\n M 0 0\n L 256 0\n L 256 256\n L 0 256\n L 0 0\n M 128 96\n a 32 32 180 1 1 0 64\n a 32 32 180 1 1 0 -64\n z\n \"\n fill-rule=\"evenodd\"\n />\n </mask>\n </defs>\n <circle mask=\"url(#mask)\" cx=\"128\" cy=\"128\" r=\"64\" fill=\"#ff0000\" />\n</svg>\n mask-type fill-rule=\"evenodd\" circle rect" }, { "answer_id": 74590774, "author": "herrstrietzel", "author_id": 15015675, "author_profile": "https://Stackoverflow.com/users/15015675", "pm_score": 1, "selected": false, "text": "// outer circle - clockwise\nM 128 64\na 64 64 0 0 1 0 128\na 64 64 0 0 1 0 -128\nz\n\n// innercircle - counter clockwise\nM 128 96\na 32 32 180 1 0 0 64\na 32 32 180 1 0 0 -64\nz \n body{\nbackground:#222\n} <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" width=\"256\" height=\"256\" viewBox=\"0 0 256 256\" xml:space=\"preserve\">\n <path\nd=\"\nM 128 64\na 64 64 0 0 1 0 128\na 64 64 0 0 1 0 -128\nz\nM 128 96\na 32 32 180 1 0 0 64\na 32 32 180 1 0 0 -64\nz\"\nfill=\"#ff0000\" />\n</svg> fill-rule" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3736239/" ]
74,574,921
<p>I am trying to import many excel files (around 400) into one dataframe from a folder but I seem to be running into an error.</p> <p>The files I want from my folder are names filename followed by a date - &quot;filename_yyyy_mm_dd.xlsx&quot;.</p> <p>I want to keep the header as the files have all same columns for different dates.</p> <p>My current code is:</p> <pre><code>import glob import pandas as pd import os path = r&quot;C:\Users\...&quot; my_files = glob.glob(os.path.join(path, &quot;filename*.xlsx&quot;)) file_li = [] for filename in my_files: df = pd.read_excel(filename, index_col=None, header=1) file_li.append(df) frame = pd.concat(file_li, axis=0, ignore_index=True) </code></pre> <p>When I call my frame I dont get any response? Am I doing something wrong in the way I am calling the file name?</p> <p>Update:</p> <p>My excel files look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Column 1</th> <th style="text-align: center;">Column 2</th> <th style="text-align: center;">Column 3</th> <th style="text-align: center;">Column 4</th> <th style="text-align: center;">Column 5</th> <th style="text-align: center;">Column 6</th> <th style="text-align: center;">Column 7</th> <th style="text-align: center;">Column 8</th> <th style="text-align: center;">Column 9</th> <th style="text-align: center;">Column 10</th> <th style="text-align: center;">Column 11</th> <th style="text-align: center;">Column 12</th> <th style="text-align: center;">Column 13</th> <th style="text-align: center;">Column 14</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Date</td> <td style="text-align: center;">SREC-MD</td> <td style="text-align: center;">SREC</td> <td style="text-align: center;">Feb-25</td> <td style="text-align: center;">MDX</td> <td style="text-align: center;">F</td> <td style="text-align: center;"></td> <td style="text-align: center;">85</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> <td style="text-align: center;">8086</td> <td style="text-align: center;">02/25/2025</td> <td style="text-align: center;">20107</td> <td style="text-align: center;"></td> </tr> </tbody> </table> </div> <p>with around 300-400 rows.</p> <p>My output has captured the 14 columns but it has added a lot more as doing frame.info() shows I have 922 columns.</p> <p>Update 2:</p> <p><a href="https://i.stack.imgur.com/lzmoO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lzmoO.png" alt="Screenshot of output" /></a></p>
[ { "answer_id": 74584915, "author": "skelley", "author_id": 3736239, "author_profile": "https://Stackoverflow.com/users/3736239", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" width=\"256\" height=\"256\" viewBox=\"0 0 256 256\" xml:space=\"preserve\">\n <defs>\n <mask id=\"mask\" mask-type=\"alpha\">\n <path\n d=\"\n M 0 0\n L 256 0\n L 256 256\n L 0 256\n L 0 0\n M 128 96\n a 32 32 180 1 1 0 64\n a 32 32 180 1 1 0 -64\n z\n \"\n fill-rule=\"evenodd\"\n />\n </mask>\n </defs>\n <circle mask=\"url(#mask)\" cx=\"128\" cy=\"128\" r=\"64\" fill=\"#ff0000\" />\n</svg>\n mask-type fill-rule=\"evenodd\" circle rect" }, { "answer_id": 74590774, "author": "herrstrietzel", "author_id": 15015675, "author_profile": "https://Stackoverflow.com/users/15015675", "pm_score": 1, "selected": false, "text": "// outer circle - clockwise\nM 128 64\na 64 64 0 0 1 0 128\na 64 64 0 0 1 0 -128\nz\n\n// innercircle - counter clockwise\nM 128 96\na 32 32 180 1 0 0 64\na 32 32 180 1 0 0 -64\nz \n body{\nbackground:#222\n} <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" width=\"256\" height=\"256\" viewBox=\"0 0 256 256\" xml:space=\"preserve\">\n <path\nd=\"\nM 128 64\na 64 64 0 0 1 0 128\na 64 64 0 0 1 0 -128\nz\nM 128 96\na 32 32 180 1 0 0 64\na 32 32 180 1 0 0 -64\nz\"\nfill=\"#ff0000\" />\n</svg> fill-rule" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19631653/" ]
74,574,928
<p>I've made a function to create a figure with N subplots in Plotly. To hide the x-axis labels of these subplots I want to execute, inside this function, for example for N=5</p> <pre><code>relayout!(p, xaxis_showticklabels=false) relayout!(p, xaxis2_showticklabels=false) relayout!(p, xaxis3_showticklabels=false) relayout!(p, xaxis4_showticklabels=false) </code></pre> <p>Since I don't know that number N of subplots a priori, I'd like to do this in a loop, employing the for-loop counter <strong>n</strong> in the command ...xaxis<strong>n</strong>_...</p> <p>I've tried to construct the string and then parse it using eval(Meta.parse(expr)) but that doesn't work since eval only works in global scope.</p> <p>Any suggestions on how to do this would be greatly appreciated.</p>
[ { "answer_id": 74594855, "author": "Przemyslaw Szufel", "author_id": 9957710, "author_profile": "https://Stackoverflow.com/users/9957710", "pm_score": 1, "selected": false, "text": "f(a; a1=0,a2=0,a3=0) = a+a1+2a2+3a3\n f(100, a1=1) f(100, a2=2) f(100, a3=3) julia> [f(100; Symbol(\"a$i\")=>i) for i in 1:3]\n3-element Vector{Int64}:\n 101\n 104\n 109\n" }, { "answer_id": 74598239, "author": "wrsc", "author_id": 20600602, "author_profile": "https://Stackoverflow.com/users/20600602", "pm_score": 0, "selected": false, "text": "relayout!(p; xaxis_showticklabels=false)=>false)\nfor i = 2:N\n relayout!(p; Symbol(\"xaxis$i\"*\"_showticklabels\")=>false)\nend\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600602/" ]
74,574,946
<p>I have a diagram like below picture and I use entity framework. <a href="https://i.stack.imgur.com/QqJpn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QqJpn.png" alt="enter image description here" /></a> I want to retrieve OutOfServices items based on the Id of Calenders table. I used this syntax like below which leads to the error &quot;System.ArgumentNullException:</p> <blockquote> <p>'Value cannot be null. (Parameter 'source')'&quot;</p> </blockquote> <pre><code> public IList&lt;OutOfService&gt; GetRoomOutOfServiceDatesByCalendarId(int calendarId) { IList&lt;OutOfService&gt; outOfServices = _myDbContext.Calenders.Find(calendarId).OutOfServices.ToList(); return outOfServices; } </code></pre>
[ { "answer_id": 74575021, "author": "Jegan Maria", "author_id": 20600273, "author_profile": "https://Stackoverflow.com/users/20600273", "pm_score": -1, "selected": false, "text": " public IList<OutOfService> GetRoomOutOfServiceDatesByCalendarId(int calendarId)\n{\n var outOfService=_myDbContext.Calenders.Find(calendarId);\n IList<OutOfService> outOfServices = outOfService!=null && outOfService.OutOfServices!=null?outOfService.OutOfServices.ToList():null;\n\n return outOfServices;\n}\n" }, { "answer_id": 74575447, "author": "amir kian", "author_id": 10997800, "author_profile": "https://Stackoverflow.com/users/10997800", "pm_score": 0, "selected": false, "text": " IList<OutOfService> outOfServices = _myDbContext.OutOfServices.Where(x=>x.Calender.Calender_id== calendarId).ToList();\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10997800/" ]
74,574,952
<p>I am trying to connect web api made in asp.net to sql server database provided by aws rds. I have never used aws before so I am not really sure if I am missing something there. I have tried to do it but i get following message when I added migration and trying to update database (using EF core):</p> <blockquote> <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)</p> </blockquote> <p>I have following code in my API:</p> <p>Context class:</p> <pre><code> public class TestContext : DbContext { public virtual DbSet&lt;Fruit&gt; Fruits { get; set; } public TestContext(DbContextOptions&lt;TestContext&gt; options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(&quot;server=&lt;nameofserver&gt;;user=&lt;username&gt;;password=&lt;password&gt;;database=&lt;nameofdatabase&gt;;&quot;); // there i put data from my database hosted on aws } } </code></pre> <p>and in Program.cs:</p> <pre><code>builder.Services.AddDbContext&lt;TestContext&gt;(options =&gt; options.UseSqlServer(&quot;server=&lt;nameofserver&gt;;user=&lt;username&gt;;password=&lt;password&gt;;database=&lt;nameofdatabase&gt;;&quot;))// there i put data from my database hosted on aws1; </code></pre> <p>I know I should put connection string in appsettings.json but I believe that is not the case now. Why isn't the table being created in the database? Should i enable/do sth on aws website? Or maybe the problem is in the code? How can I solve it?</p>
[ { "answer_id": 74575136, "author": "smac2020", "author_id": 1435543, "author_profile": "https://Stackoverflow.com/users/1435543", "pm_score": 1, "selected": false, "text": "static void Main(string[] args)\n {\n try \n { \n SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();\n\n builder.DataSource = \"<your_server.database.windows.net>\"; \n builder.UserID = \"<your_username>\"; \n builder.Password = \"<your_password>\"; \n builder.InitialCatalog = \"<your_database>\";\n \n using (SqlConnection connection = new SqlConnection(builder.ConnectionString))\n {\n Console.WriteLine(\"\\nQuery data example:\");\n Console.WriteLine(\"=========================================\\n\");\n \n connection.Open(); \n\n String sql = \"SELECT name, collation_name FROM sys.databases\";\n\n using (SqlCommand command = new SqlCommand(sql, connection))\n {\n using (SqlDataReader reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n Console.WriteLine(\"{0} {1}\", reader.GetString(0), reader.GetString(1));\n }\n }\n } \n }\n }\n catch (SqlException e)\n {\n Console.WriteLine(e.ToString());\n }\n Console.WriteLine(\"\\nDone. Press enter.\");\n Console.ReadLine(); \n }\n }\n" } ]
2022/11/25
[ "https://Stackoverflow.com/questions/74574952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20600638/" ]