qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,558,031
<pre><code>import re phonenumregex=re.compile(r'ddd-ddd-dddd') mo=phonenumregex.search(&quot;My number is 415-555-4242&quot;) print(&quot;Phone Number found: &quot; + mo.group()) #it gives me this error. AttributeError: 'NoneType' object has no attribute 'group' </code></pre> <p>I gave the format as ddd-ddd-dddd in raw string. and was expecting to get the number 415-555-4242 in return</p>
[ { "answer_id": 74558465, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "ROWID ROW_NUMBER DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT ROW_NUMBER() OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ORDER BY ROWID\n ) AS rn\n FROM table_name\n )\n WHERE rn > 1\n);\n DELETE FROM table_name\nWHERE ROWID IN (\n SELECT ROWID\n FROM (\n SELECT COUNT(*) OVER (\n PARTITION BY col1, col2, col3, /*...,*/ colN -- List all the columns\n ) AS cnt\n FROM table_name\n )\n WHERE cnt > 1\n);\n" }, { "answer_id": 74575222, "author": "psaraj12", "author_id": 1297792, "author_profile": "https://Stackoverflow.com/users/1297792", "pm_score": 0, "selected": false, "text": " declare\n l_column_list varchar2(32767);\n l_table_name varchar2(4000) := 'AAAA_DATES';\n begin\n for rec in (select column_name, column_id\n from dba_tab_cols\n where table_name = l_table_name\n order by column_id) loop\n if (rec.column_id = 1) then\n l_column_list := rec.column_name;\n else\n l_column_list := l_column_list || ',' || rec.column_name;\n end if;\n end loop;\n\n execute immediate 'DELETE FROM ' || l_table_name ||\n ' WHERE ROWID IN (\n SELECT ROW_id\n FROM (\n SELECT rowid row_id, ROW_NUMBER() OVER (\n PARTITION BY ' || l_column_list ||\n ' ORDER BY ROWNUM\n ) AS rn\n FROM ' || l_table_name || '\n )\n WHERE rn > 1\n )';\n dbms_output.put_line(sql%rowcount);\n commit;\n end;\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589075/" ]
74,558,042
<p>I'm trying to automate some tedious code-writing. I have something like the following:</p> <pre><code>Codes&lt;-c(&quot;code1&quot;,&quot;code2&quot;,&quot;code3&quot;,&quot;code4&quot;) other_Codes&lt;-c(&quot;code5&quot;,&quot;code6&quot;,&quot;code7&quot;,&quot;code8&quot;) </code></pre> <p>What I want to create is something like the following:</p> <pre><code>repetetivetext Code1 repetetivetext Code5 repetetivetext Code2 repetetivetext Code6 repetetivetext Code3 repetetivetext Code7 repetetivetext Code4 repetetivetext Code8 </code></pre> <p>....So that the first argument in the first vector is paired with the first argument in the second vector and so on. This can be done with something like:</p> <pre><code>paste0(&quot;repetetivetext &quot;,Codes, &quot;repetitive text &quot;, other_Codes) </code></pre> <p>But for different reason (the actual code is more complex than this) this isn't a workable solution right now. I would much rather use a variation of a for loop or nested for-loop, one which would let me combine the elements from the two vectors, but give me 4 combinations instead of 16.</p> <p>Is there such a variation? Or is there a different way of doing this which I haven't thought of?</p>
[ { "answer_id": 74558335, "author": "islem", "author_id": 11952767, "author_profile": "https://Stackoverflow.com/users/11952767", "pm_score": 1, "selected": false, "text": "Codes <- c(\"code1\", \"code2\", \"code3\", \"code4\")\nother_Codes <- c(\"code5\", \"code6\", \"code7\", \"code8\")\noutput = c()\ntext = \"repetetivetext \"\nfor (j in 1:length(Codes)) { \n element = paste0(text, Codes[j], text,other_Codes[j])\n output = c(output, element)\n}\noutput\n" }, { "answer_id": 74558390, "author": "Carlos Luis Rivera", "author_id": 10215301, "author_profile": "https://Stackoverflow.com/users/10215301", "pm_score": 0, "selected": false, "text": "purrr::map2 purrr::map2_chr library(purrr)\n\nCodes <- c(\"code1\", \"code2\", \"code3\", \"code4\")\nother_Codes <- c(\"code5\", \"code6\", \"code7\", \"code8\")\n\nmap2_chr(\n .x = rep(Codes, each = length(other_Codes)),\n .y = rep(other_Codes, times = length(Codes)),\n ~ paste0(\"repetetive text \", .x, \" repetitive text \", .y)\n)\n\n# [1] \"repetetive text code1 repetitive text code5\"\n# [2] \"repetetive text code1 repetitive text code6\"\n# [3] \"repetetive text code1 repetitive text code7\"\n# [4] \"repetetive text code1 repetitive text code8\"\n# [5] \"repetetive text code2 repetitive text code5\"\n# [6] \"repetetive text code2 repetitive text code6\"\n# [7] \"repetetive text code2 repetitive text code7\"\n# [8] \"repetetive text code2 repetitive text code8\"\n# [9] \"repetetive text code3 repetitive text code5\"\n# [10] \"repetetive text code3 repetitive text code6\"\n# [11] \"repetetive text code3 repetitive text code7\"\n# [12] \"repetetive text code3 repetitive text code8\"\n# [13] \"repetetive text code4 repetitive text code5\"\n# [14] \"repetetive text code4 repetitive text code6\"\n# [15] \"repetetive text code4 repetitive text code7\"\n# [16] \"repetetive text code4 repetitive text code8\"\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5428469/" ]
74,558,052
<p>Assume I have a JSON-file that looks like this one:</p> <pre><code>{ &quot;data&quot;: [ { &quot;question&quot;: &quot;What's 1+1&quot;, &quot;answers&quot;: [ { &quot;text&quot;: &quot;3&quot;, &quot;correct&quot;: false }, { &quot;text&quot;: &quot;2&quot;, &quot;correct&quot;: true } ] } ] } </code></pre> <p>In my code I am iterating over these answers and rendering a button for each. Each button also receives a click-handler like beneath. What I'd like to happen when you click a button, is that if it's the correct one, I should assign it a <em>(correct)</em> class. But if it's the wrong one, I will assign it another <em>(wrong)</em> class, but <strong>still</strong> show which was the correct one.</p> <pre><code>const handleClick = answer =&gt; { // How would I implement this logic? } const App = ({ data }) =&gt; { return ( &lt;div&gt; {data.answers.map(answer =&gt; ( &lt;button onClick={() =&gt; handleClick(answer)}&gt;{answer.text}&lt;/button&gt; ))} &lt;/div&gt; ) } </code></pre> <p>I tried to create a state variable to the button that was clicked. Then compare it against the parameter that was passed through the onclick handler.</p>
[ { "answer_id": 74558114, "author": "Priyen Mehta", "author_id": 19431815, "author_profile": "https://Stackoverflow.com/users/19431815", "pm_score": 1, "selected": false, "text": "const App = ({ data }) => {\n\nreturn (\n <div>\n {data.answers.map(answer => (\n <button classname={answer.correct ? 'correct-class' : 'wrong-class'`} onClick={() => handleClick(answer)}>{answer.text}</button>\n ))}\n </div>\n)}\n" }, { "answer_id": 74558433, "author": "Nick Parsons", "author_id": 5648954, "author_profile": "https://Stackoverflow.com/users/5648954", "pm_score": 3, "selected": true, "text": "selectedAnswer correct .correct true incorrect false classType selectedAnnswer const {useState} = React;\nconst App = ({ data }) => {\n const [selectedAnswer, setSelectedAnswer] = useState();\n const handleClick = answer => {\n setSelectedAnswer(answer);\n }\n\n return (\n <div>\n {data.answers.map(answer => {\n const classType = answer.correct ? \"correct\" : \"incorrect\";\n const showClass = selectedAnswer && (answer.correct || selectedAnswer === answer);\n return <button\n key={answer.text}\n className={showClass && classType}\n onClick={() => handleClick(answer)}>{answer.text}</button>\n })}\n </div>\n );\n}\n\n\nconst obj = { \"data\": [ { \"question\": \"What's 1+1\", \"answers\": [ { \"text\": \"3\", \"correct\": false }, { \"text\": \"2\", \"correct\": true }, { \"text\": \"1\", \"correct\": false } ] } ] }\nReactDOM.createRoot(document.body).render(<App data={obj.data[0]} />); .correct {background: lime;}\n.incorrect {background: red;} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74558767, "author": "Hakim Allem", "author_id": 18236008, "author_profile": "https://Stackoverflow.com/users/18236008", "pm_score": -1, "selected": false, "text": " const App = ({ data }) => {\n\n return (\n <div>\n {data.answers.map(answer => (\n <button \n className={`${answer.correct ? \"correct\" : \"wrong\"} other \n classes `} \n onClick={() => handleClick(answer)}>{answer.text}\n </button>\n ))}\n </div>\n )\n }" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20131031/" ]
74,558,064
<p>I'm trying to implement a PckPlace ros service, but I get the this error:</p> <pre><code>/opt/ros/noetic/share/genmsg/cmake/pkg-genmsg.cmake.em:56: error: &lt;class 'genmsg.base.InvalidMsgSpec'&gt;: std_msgs/UInt16.msg is not a legal message field type </code></pre> <h3>PickPlace.srv</h3> <pre><code>std_msgs/UInt16.msg speed --- bool success </code></pre> <h3>Package.xml</h3> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot;?&gt; &lt;package format=&quot;2&quot;&gt; &lt;name&gt;pick_place&lt;/name&gt; &lt;version&gt;0.0.0&lt;/version&gt; &lt;description&gt;The package&lt;/description&gt; &lt;maintainer email=&quot;s@s.com&quot;&gt;s&lt;/maintainer&gt; &lt;license&gt;LGPLv2.1&lt;/license&gt; &lt;buildtool_depend&gt;catkin&lt;/buildtool_depend&gt; &lt;build_depend&gt;rospy&lt;/build_depend&gt; &lt;build_export_depend&gt;rospy&lt;/build_export_depend&gt; &lt;exec_depend&gt;rospy&lt;/exec_depend&gt; &lt;depend&gt;rospy_message_converter&lt;/depend&gt; &lt;depend&gt;message_generation&lt;/depend&gt; &lt;depend&gt;message_runtime&lt;/depend&gt; &lt;depend&gt;std_msgs&lt;/depend&gt; &lt;/package&gt; </code></pre> <h3>CMakeLists.txt</h3> <pre><code>cmake_minimum_required(VERSION 3.0.2) project(pick_place) find_package(catkin REQUIRED COMPONENTS rospy std_msgs rospy_message_converter message_generation ) catkin_python_setup() # Generate services in the 'srv' folder add_service_files( FILES PickPlace.srv ) ## Generate added messages and services with any dependencies listed here generate_messages( DEPENDENCIES std_msgs ) # Declare catkin package catkin_package( CATKIN_DEPENDS rospy rospy_message_converter std_msgs message_runtime # LIBRARIES ${PROJECT_NAME} ) catkin_install_python(PROGRAMS # nodes/pp_client.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) </code></pre> <p>Can you please tell me how can I resolve this error? thanks in advance.</p>
[ { "answer_id": 74558273, "author": "Bilal", "author_id": 8618242, "author_profile": "https://Stackoverflow.com/users/8618242", "pm_score": 0, "selected": false, "text": ".msg" }, { "answer_id": 74566458, "author": "Fruchtzwerg", "author_id": 5235574, "author_profile": "https://Stackoverflow.com/users/5235574", "pm_score": 2, "selected": true, "text": "string int64 geometry_msgs/PoseWithCovariance uint16 speed\n---\nbool success\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8618242/" ]
74,558,068
<p>I would like to change import from <code>../../../db/index.js</code> to <code>db/index.js</code></p> <p><a href="https://i.stack.imgur.com/NBGaO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NBGaO.png" alt="enter image description here" /></a></p> <p>I have already added this setting in my jsconfig.json but I still got this error.</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;module&quot;: &quot;commonjs&quot;, &quot;baseUrl&quot;: &quot;src&quot; }, &quot;include&quot;: [ &quot;src/**/*&quot; ], &quot;exclude&quot;: [ &quot;node_modules&quot; ] } </code></pre>
[ { "answer_id": 74558371, "author": "AbsoluteZero", "author_id": 20539156, "author_profile": "https://Stackoverflow.com/users/20539156", "pm_score": 0, "selected": false, "text": "import { something } from '../../something' import { something } from 'something' yarn add something import { something } from '@components/something' babel-plugin-root-import" }, { "answer_id": 74566399, "author": "Pusoy", "author_id": 11194137, "author_profile": "https://Stackoverflow.com/users/11194137", "pm_score": 2, "selected": true, "text": "\"imports\": {\n \"#root/*\": {\n \"default\": \"./src/*\"\n }\n},\n {\n \"compilerOptions\": {\n \"target\": \"esnext\",\n \"module\": \"commonjs\",\n \"baseUrl\": \"./src\",\n \"paths\": {\n \"#root/*\": [\"./*\"]\n }\n },\n \"include\": [\n \"src/**/*\"\n ],\n \"exclude\": [\n \"node_modules\"\n ]\n}\n import level1 from '#root/level1/index.js';\n import level1 from './level1/index.js';\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11194137/" ]
74,558,078
<p>I have this function</p> <pre><code>export const handleSortableColumns = (headerKeys: string[], sortKeys: object): string[] =&gt; { if (!headerKeys) return []; return headerKeys.map((key: string): any =&gt; sortKeys[key] || null); }; </code></pre> <p>so <strong>headerKeys</strong> parameter takes <code>list of string</code> <strong>sortKeys</strong> parameter should take an <code>object</code> but I think it's wrong to put object type and I can't define type or interface because each time it will be different properties. should I specify generic type ? how I can do that ? also the return type will be a list of strings that contains null values as well so what should be return type + using any type is forbidden</p>
[ { "answer_id": 74558277, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 1, "selected": false, "text": "sortKeys interface ISortKeys {\n [key: string]: string\n}\n (string|null)[]\n" }, { "answer_id": 74558949, "author": "Schmid", "author_id": 5790966, "author_profile": "https://Stackoverflow.com/users/5790966", "pm_score": 0, "selected": false, "text": "sortKeys headerKeys const handleSortableColumns = <T>(sortKeys: T, ...headerKeys: (keyof T & string)[]): (string | null)[] => {\n if (!headerKeys) return [];\n const result = headerKeys.map(key => sortKeys[key] || null);\n return result as (string | null)[];\n}\n handleSortableColumns({ a: '1', b: 2 }, 'a', 'X');\n handleSortableColumns({ a: '1', b: 2 }, 'a', 'b');\n filter throw" }, { "answer_id": 74559624, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 0, "selected": false, "text": "function handleSortableColumns <\n Keys extends readonly string[],\n ValueMap extends Record<string, unknown>,\n>(headerKeys: Keys, valueMap: ValueMap): (ValueMap[Extract<keyof ValueMap, Keys[number]>] | null)[] {\n return headerKeys.map(\n key => (valueMap[key] ?? null) as ValueMap[Extract<keyof ValueMap, Keys[number]>] | null\n );\n}\n\nconst keys = ['a', 'b', 'c'] as const;\n\nconst map = {\n a: 1,\n c: false,\n d: 'hello world',\n};\n\nconst result = handleSortableColumns(keys, map);\n //^? const result: (number | boolean | null)[]\n\nconsole.log(result); // [1, null, false]\n\n \"use strict\";\nfunction handleSortableColumns(headerKeys, valueMap) {\n return headerKeys.map(key => (valueMap[key] ?? null));\n}\nconst keys = ['a', 'b', 'c'];\nconst map = {\n a: 1,\n c: false,\n d: 'hello world',\n};\nconst result = handleSortableColumns(keys, map);\n//^?\nconsole.log(result); // [1, null, false]" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10692884/" ]
74,558,080
<p>This is a true story of evolving code. We began with many classes based on this structure:</p> <pre><code>class Base { public: virtual void doSomething() {} }; class Derived : public Base { public: void doSomething() override { Base::doSomething(); // Do the basics // Do other derived things } }; </code></pre> <p>At one point, we needed a class in between Base and Derived:</p> <pre><code>class Base; class Between : public Base; class Derived : public Between; </code></pre> <p>To keep the structure, <code>Between::doSomething()</code> first calls Base. However now <code>Derived::doSomething()</code> must be changed to call <code>Between::doSomething()</code>...</p> <p>And this goes for all methods of Derived, requiring search &amp; replace to many many calls.</p> <p>A best solution would be to have some this-&gt;std::direct_parent mechanism to avoid all the replacements and to allow easy managing of class topology.</p> <p>Of course, this should compile only when there's a single immediate parent.</p> <p>Is there any way to accomplish this? If not, could this be a feature request for the C++ committee?</p>
[ { "answer_id": 74558156, "author": "Tomek", "author_id": 25406, "author_profile": "https://Stackoverflow.com/users/25406", "pm_score": 4, "selected": true, "text": "parent Derived class Base\n{\npublic:\n virtual void doSomething() {}\n};\n\nclass Derived : public Base\n{\nprivate:\n typedef Base parent;\npublic:\n void doSomething() override \n {\n parent::doSomething(); // Do the basics\n\n // Do other derived things\n }\n};\n Between Derived parent class Derived : public Between\n{\nprivate:\n typedef Between parent;\npublic:\n void doSomething() override \n {\n parent::doSomething(); // Do the basics\n\n // Do other derived things\n }\n};\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2181250/" ]
74,558,102
<p>How do I split the zipcode and state in this table? I had no trouble separating the street and city, but I struggled with the ZIP code and State part</p> <p>944 Walnut Street, Boston, MA 02215 This should be the output:</p> <pre><code>| Street | City | State | ZipCode :------------------:------:-------:-------: | 944 Walnut Street|Boston| MA | 02215 </code></pre> <p>I tried doing this but this is the result</p> <pre><code>SELECT split_part(purchaseaddress::TEXT, ',', 1) Street, split_part(purchaseaddress::TEXT, ',', 2) City, split_part(purchaseaddress::TEXT, ',', 3) State, split_part(purchaseaddress::TEXT, ' ' , 4)ZIPCode FROM sales_2019; </code></pre> <pre><code>| Street | City | State | ZipCode :------------------:------:------------:-------: | 944 Walnut Street|Boston| MA 02215 | Boston, </code></pre>
[ { "answer_id": 74558201, "author": "DEEPAK TOMAR", "author_id": 9974900, "author_profile": "https://Stackoverflow.com/users/9974900", "pm_score": 1, "selected": true, "text": "SELECT\ntrim(split_part(purchaseaddress::TEXT, ',', 1)) Street,\ntrim(split_part(purchaseaddress::TEXT, ',', 2)) City,\ntrim(split_part(trim(split_part(purchaseaddress::TEXT, ',', 3))::TEXT, ' ', 1)) State,\ntrim(split_part(trim(split_part(purchaseaddress::TEXT, ',' , 3))::TEXT, ' ', 2)) ZIPCode\nFROM\nsales_2019;\n street | city | state | zipcode\n ------------------+--------+-------+---------\n 944 Walnut Street | Boston | MA | 02215\n" }, { "answer_id": 74558263, "author": "Zegarek", "author_id": 5298879, "author_profile": "https://Stackoverflow.com/users/5298879", "pm_score": 2, "selected": false, "text": "string_to_array() trim() create table sales_2019 (purchaseaddress text);\ninsert into sales_2019 values ('944 Walnut Street, Boston, MA 02215');\n\nwith \n address_split_by_commas as \n ( select string_to_array(purchaseaddress::TEXT, ',') arr \n from sales_2019 )\n,address_split_by_commas_trimmed as \n ( select array_agg( trim(element) ) arr \n from ( select unnest(arr) element \n from address_split_by_commas) a )\nSELECT\n arr[1] Street,\n arr[2] City,\n split_part(arr[3], ' ', 1) State,\n split_part(arr[3], ' ', 2) ZIPCode\nFROM\n address_split_by_commas_trimmed;\n \n\n-- street | city | state | zipcode\n---------------------+--------+-------+---------\n-- 944 Walnut Street | Boston | MA | 02215\n--(1 row)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14610361/" ]
74,558,107
<p>Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner:</p> <pre><code>tail file.txt -n `python 123*456` </code></pre> <p>instead of having to calculate 123*456 in a separate step.</p>
[ { "answer_id": 74558479, "author": "beat_it_987", "author_id": 6800343, "author_profile": "https://Stackoverflow.com/users/6800343", "pm_score": 1, "selected": false, "text": "-c tail test_log.txt -n `python -c \"print(1 + 2)\"` " }, { "answer_id": 74558697, "author": "Dominique", "author_id": 4279155, "author_profile": "https://Stackoverflow.com/users/4279155", "pm_score": 3, "selected": true, "text": "tail -f file.txt -n $((123*456))\n $((...))" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4746861/" ]
74,558,117
<p><strong>Background:</strong></p> <p>I have several ASP.NET projects under one solution file. I have a build pipeline for ASP.NET projects and building it with .sln. Now, we have added a new project to the same .sln which is in .NET CORE.</p> <p><strong>Problem statement:</strong></p> <p>In my build pipeline, when I try to build the whole solution, it throws an exception to the newly added project. (.NET CORE)</p> <blockquote> <p>&quot;The type or namespace name 'Entity' does not exist in the namespace 'System.Data' (are you missing an assembly reference?)&quot;</p> </blockquote> <p>I believe this is due to framework versions.</p> <p><strong>Question</strong>:</p> <p>Is it possible to have both projects under one build pipeline, if yes, how can I achieve it? if not, what would be the ideal solution?</p> <p>Additional information: From the visual studio, everything is building and working fine, but I build the project pipeline it's throwing this error.</p>
[ { "answer_id": 74558479, "author": "beat_it_987", "author_id": 6800343, "author_profile": "https://Stackoverflow.com/users/6800343", "pm_score": 1, "selected": false, "text": "-c tail test_log.txt -n `python -c \"print(1 + 2)\"` " }, { "answer_id": 74558697, "author": "Dominique", "author_id": 4279155, "author_profile": "https://Stackoverflow.com/users/4279155", "pm_score": 3, "selected": true, "text": "tail -f file.txt -n $((123*456))\n $((...))" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10950108/" ]
74,558,151
<p>how to convert <code>{ startItem: 2 }</code> string to an object <code>{ &quot;startItem&quot;: 2 }</code> without using eval() function ?</p>
[ { "answer_id": 74559119, "author": "Ji aSH", "author_id": 6108947, "author_profile": "https://Stackoverflow.com/users/6108947", "pm_score": -1, "selected": false, "text": "> JSON.stringify({ startItem: 2 })\n '{\"startItem\":2}'\n > JSON.parse('{\"startItem\":2}')\n {startItem: 2}\n > const transform = (value) => Function(`return ${value}`)()\n> transform('{ startItem: 2}')\n {startItem: 2}\n" }, { "answer_id": 74559326, "author": "Divyesh", "author_id": 6146508, "author_profile": "https://Stackoverflow.com/users/6146508", "pm_score": 0, "selected": false, "text": "var aux = { startItem: 2 }\nvar jsonStr = aux.replace(/(\\w+:)|(\\w+ :)/g, function(matchedStr) {\n return '\"' + matchedStr.substring(0, matchedStr.length - 1) + '\":';\n});\nvar obj = JSON.parse(jsonStr);\nconsole.log(obj);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6146508/" ]
74,558,153
<p>Here is the type of the variable</p> <pre><code>type imageTags: string | number | { tag_type: string; tag_name: string; tag_id: number; photo_id: number; confidence: number; }[] </code></pre> <p>This is how i try to access its properties.</p> <pre><code> if (imageTags.length &gt; 0) { return imageTags[0].tag_name === image_type; } </code></pre> <p>The variable can be a <strong>string , number or array</strong> then why am I getting the error <strong>Property 'length' does not exist on type 'string | number | { tag_type: string; tag_name: string; tag_id: number; photo_id: number; confidence: number; }[]'. Property 'length' does not exist on type 'number'.ts(2339)</strong></p>
[ { "answer_id": 74559119, "author": "Ji aSH", "author_id": 6108947, "author_profile": "https://Stackoverflow.com/users/6108947", "pm_score": -1, "selected": false, "text": "> JSON.stringify({ startItem: 2 })\n '{\"startItem\":2}'\n > JSON.parse('{\"startItem\":2}')\n {startItem: 2}\n > const transform = (value) => Function(`return ${value}`)()\n> transform('{ startItem: 2}')\n {startItem: 2}\n" }, { "answer_id": 74559326, "author": "Divyesh", "author_id": 6146508, "author_profile": "https://Stackoverflow.com/users/6146508", "pm_score": 0, "selected": false, "text": "var aux = { startItem: 2 }\nvar jsonStr = aux.replace(/(\\w+:)|(\\w+ :)/g, function(matchedStr) {\n return '\"' + matchedStr.substring(0, matchedStr.length - 1) + '\":';\n});\nvar obj = JSON.parse(jsonStr);\nconsole.log(obj);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16018684/" ]
74,558,182
<p>Similar to an Angular 14 generated project I want to have separate development and production environments but when creating a project using <code>ng new</code>:</p> <pre><code>ng new my-app </code></pre> <p>this does not create the environments folder or set this up.</p> <p><a href="https://i.stack.imgur.com/Nol70.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nol70.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74558330, "author": "Daniel T", "author_id": 10477326, "author_profile": "https://Stackoverflow.com/users/10477326", "pm_score": 2, "selected": false, "text": "environments npm install -g @angular/cli@14.2.10 ng new" }, { "answer_id": 74558518, "author": "Andrew Allen", "author_id": 4711754, "author_profile": "https://Stackoverflow.com/users/4711754", "pm_score": 3, "selected": true, "text": "ng new environments environment.ts environment.prod.ts environment.staging.ts angular.json project.json fileReplacements replace with \"configurations\": {\n \"production\": {\n ...\n \"fileReplacements\": [\n {\n \"replace\": \"apps/some-app/src/environments/environment.ts\",\n \"with\": \"apps/some-app/src/environments/environment.prod.ts\"\n }\n ],\n },\n \"development\": {\n ...\n }\n },\n \"defaultConfiguration\": \"production\"\n },\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19270476/" ]
74,558,185
<p>In my Vue application I have a list of objects looking like this:</p> <pre class="lang-js prettyprint-override"><code>const arr = [ { id: 1, name: 'Max', grade: 3 }, { id: 2, name: 'Lisa', grade: 2 } ]; </code></pre> <p>Now I want every object in this array to be a single string for itself. I know there is <code>JSON.stringifty</code> but this makes my whole array to a string and not every single object.</p> <p>So the result should be something like:</p> <pre class="lang-js prettyprint-override"><code>const arr = [ &quot;{id:1,name:'Max',grade:3}&quot;, &quot;{id:2,name:'Max',grade:3}&quot; ]; </code></pre>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19432419/" ]
74,558,190
<p>I can't fetch the next address</p> <p>but I can fetch sequence shipto 0</p> <p>RangeError (index): Invalid value: Only valid value is 0: 1</p> <p>after some fixes type 'sting' is not a subtype of type 'int' of 'index'</p> <p>The data in the address will be included in the same set of items.</p> <p>Please help me I am practicing fetch api</p> <pre><code>List&lt;dynamic&gt; pos = &lt;dynamic&gt;[]; bool isLoading = false; @override void initState() { super.initState(); this.fetchMos(); } Future fetchMos() async { var client = http.Client(); String mosUrl = ','; var url = Uri.parse(mosUrl); var headers = {'Client-Token': ''}; var response = await client.get(url, headers: headers); if (response.statusCode == 200) { var items = jsonDecode((utf8.decode(response.bodyBytes)))['items']; setState(() { pos = items; isLoading = false; }); } else { setState(() { pos = []; isLoading = false; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0.0, ), body: ListView.builder( itemBuilder: (context, index) { if (pos.length &gt; 0) { return _listItem(index); } else { return Center(child: CircularProgressIndicator()); } }, itemCount: pos.length + 1, ), ); } _listItem(index) { return Card( child: ListTile( leading: const CircleAvatar( child: Icon(Icons.emoji_emotions), ), title: Text( pos[index]['addr1'], style: const TextStyle( fontSize: 17, fontWeight: FontWeight.bold, ), ), subtitle: Text( pos[index]['shipto'], ), ), ); } { &quot;items&quot;: [ { &quot;custnum&quot;: &quot;&quot;, &quot;name&quot;: &quot;&quot;, &quot;address&quot;: [ { &quot;shipto&quot;: 0, &quot;addr1&quot;: &quot;&quot;, &quot;thanon&quot;: &quot;&quot;, &quot;tambon&quot;: &quot;&quot;, &quot;amphur&quot;: &quot;&quot;, &quot;prov_code&quot;: &quot;&quot;, &quot;province&quot;: &quot;&quot;, &quot;zipcode&quot;: &quot;&quot;, &quot;country&quot;: &quot;&quot;, &quot;contact&quot;: &quot;&quot;, &quot;postcode&quot;: &quot;&quot; }, { &quot;shipto&quot;: 1, &quot;addr1&quot;: &quot;&quot;, &quot;thanon&quot;: &quot;&quot;, &quot;tambon&quot;: &quot;&quot;, &quot;amphur&quot;: &quot;&quot;, &quot;prov_code&quot;: &quot;&quot;, &quot;province&quot;: &quot;&quot;, &quot;zipcode&quot;: &quot;&quot;, &quot;country&quot;: &quot;&quot;, &quot;contact&quot;: &quot;&quot;, &quot;postcode&quot;: &quot;&quot; }, { &quot;shipto&quot;: 2, &quot;addr1&quot;: &quot;&quot;, &quot;thanon&quot;: &quot;&quot;, &quot;tambon&quot;: &quot;&quot;, &quot;amphur&quot;: &quot;&quot;, &quot;prov_code&quot;: &quot;&quot;, &quot;province&quot;: &quot;&quot;, &quot;zipcode&quot;: &quot;&quot;, &quot;country&quot;: &quot;&quot;, &quot;contact&quot;: &quot;&quot;, &quot;postcode&quot;: &quot;&quot; }, { &quot;shipto&quot;: 3, &quot;addr1&quot;: &quot;&quot;, &quot;thanon&quot;: &quot;&quot;, &quot;tambon&quot;: &quot;&quot;, &quot;amphur&quot;: &quot;&quot;, &quot;prov_code&quot;: &quot;&quot;, &quot;province&quot;: &quot;&quot;, &quot;zipcode&quot;: &quot;&quot;, &quot;country&quot;: &quot;&quot;, &quot;contact&quot;: &quot;&quot;, &quot;postcode&quot;: &quot;&quot; } ] } ], &quot;total_records&quot;: 1, &quot;total_pages&quot;: 1, &quot;current_page&quot;: 1 </code></pre>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19085153/" ]
74,558,252
<p>I have a project management app where the details of the project are displayed after pressing the 'more' icon button on a card. The details to be displayed include the project name and due date that are fetched from the database and then stored locally using shared preferences. Both the 'setString' and 'getString are working well but upon loading the project details page, the details do not appear at first. They only display after hot reloading the app while that page is active. Below is the code of the project details app:</p> <pre><code>import 'package:flutter/material.dart'; import 'package:mne/Actual%20Tasks/activity_widget.dart'; import 'package:mne/UserTasks/task_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; class ProjectTask extends StatefulWidget { const ProjectTask({Key key}) : super(key: key); @override State&lt;ProjectTask&gt; createState() =&gt; _ProjectTaskState(); } class _ProjectTaskState extends State&lt;ProjectTask&gt; { String pname; String pdesc; String pdue; @override void initState() { super.initState(); _fetchData(); } Future&lt;Null&gt; _fetchData() async { WidgetsFlutterBinding.ensureInitialized(); SharedPreferences localStorage = await SharedPreferences.getInstance(); pname = localStorage.getString('project_name'); pdesc = localStorage.getString('project_desc'); pdue = localStorage.getString('project_due'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( iconTheme: const IconThemeData(color: Colors.black), backgroundColor: Colors.white, automaticallyImplyLeading: true, centerTitle: true, title: const Text('Project Details', style: TextStyle(color: Colors.black))), body: SingleChildScrollView( child: Column(children: [ Container(height: 10, color: Colors.transparent), // for image Container( width: 330, child: Image.asset('assets/images/projectbanner.png'), ), //for project name Container( padding: const EdgeInsets.only(bottom: 25, top: 15), child: Row(children: [ Container( padding: const EdgeInsets.only(left: 20, right: 145), child: Text(pname ?? '', style: const TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 16)), ), Container( padding: const EdgeInsets.only(right: 10, top: 8), child: const Icon(Icons.calendar_month_outlined)), RichText( text: TextSpan(children: [ const TextSpan( text: 'Due: ', style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, color: Colors.black)), TextSpan( text: pdue ?? '', style: const TextStyle(fontSize: 12, color: Colors.black)) ])), ])), // for description title Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(left: 20, bottom: 20), child: const Text('Description', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16))), // for actual desc Container( padding: const EdgeInsets.only(left: 20), alignment: Alignment.centerLeft, child: Text( pdesc ?? '', style: const TextStyle(color: Colors.grey), )), // for task title Container( padding: const EdgeInsets.only(left: 20, top: 20, bottom: 20), alignment: Alignment.centerLeft, child: const Text('Tasks', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16))), // for task widget Container(height: 630, child: const ActivityWidget()), ]), ), ); } } </code></pre> <p>This image shows what it looks like when it first loads: <a href="https://i.stack.imgur.com/pg5O6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pg5O6.jpg" alt="on first loading this is what it looks like" /></a></p> <p>This is what it is supposed to look like after hot reloading: <a href="https://i.stack.imgur.com/LT0dy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LT0dy.jpg" alt="This is what it looks like after hot reloading" /></a></p> <p>How can I make it so that it displays the information right away? Any help is appreciated.</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16712104/" ]
74,558,256
<p>I have a table which is updated at irregular intervals; I need to always retrieve the newest data set from the table.</p> <p>I will know the data is the newest if the column PERIODAG_D (timestamp vraiable) is close to the current date.</p> <p>My current solution is to set <code>outobs=1</code> to only get one observation and order by <code>PER_DAG_I</code> (numeric date variable) decending:</p> <pre><code>PROC SQL OUTOBS=1; CREATE TABLE DESC_SORT AS SELECT DISTINCT t3.PER_DAG_I, t3.PERIODAG_D FROM COREPLNZ.KXYZ1000FCT t1 LEFT JOIN COREPLNZ.KXYZ0090_SKEMA_JUNK t2 ON (t1.SKEMA_XYZ_JUNK_I = t2.SKEMA_XYZ_JUNK_I) LEFT JOIN COREPLNZ.TXYZ0200_KILDEFACT_DIM t4 ON (t1.KILDEFACT_I = t4.KILDEFACT_I) LEFT JOIN COREPLNZ.TKON0010PER_DAG_DIM t3 ON (t1.OPGOR_DAG_I = t3.PER_DAG_I) WHERE t4.KILDEFACT_NAVN = 'TLIK6000_RESTLOEBETID_FCT' AND t2.SKEMA_KODE = 'C 73.00' ORDER BY t3.PER_DAG_I DESC; QUIT; </code></pre> <p>This gives me the following output:</p> <p><a href="https://i.stack.imgur.com/SLJkS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SLJkS.png" alt="enter image description here" /></a></p> <p>I then add PERIODAG_D and PER_DAG_I to macro variables I can use in my WHERE statement to get the newest data in the table.</p> <p>My issue is this feels like a very inefficient workaround to only get a date variable.</p> <p>I hope you can point me in the right direction.</p> <p>EDIT to show the creation of the macro variable and how it is used:</p> <p>This is how I create the macro variable:</p> <pre><code>PROC SQL; CREATE TABLE DESC_SORT_FORMAT AS SELECT t1.PERIODAG_D as str_perdag_Desc_sort, t1.PERIODAG_D AS str_timestamp_Desc_sort, (&quot;'&quot;!!put(t1.PERIODAG_D,datetime22.3)!!&quot;'dt&quot;) as str_SAStimestamp_Desc_sort FROM DESC_SORT t1; QUIT; PROC SQL NOPRINT; SELECT DISTINCT str_perdag_Desc_sort, str_timestamp_Desc_sort, str_SAStimestamp_Desc_sort INTO :str_perdag_Desc_sort, :str_timestamp_Desc_sort, :str_SAStimestamp_Desc_sort FROM DESC_SORT_FORMAT; </code></pre> <p>This is the code Insert my macro variable &amp;str_SAStimestamp_Desc_sort into:</p> <pre><code>PROC SQL; CREATE TABLE WORK.QUERY_FOR_TXYZ1000FCT_000F(label=&quot;WORK.QUERY_FOR_TXYZ1000FCT_000F&quot;) AS SELECT t2.PERIODAG_D AS OpgoerelseDato, t6.PERIODAG_D AS AfviklingDato, t1.KILDEFACT_Key_I, t3.X_ORDINATE, t3.Y_ORDINATE, t3.Z_ORDINATE, t4.SKEMA_KODE, t4.SKEMA_NAVN, t5.KILDEFACT_NAVN, t7.KUNDE_SCD_I, t7.KONTO_SCD_I, t2.PER_DAG_I FROM COREPLNZ.KXYZ1000FCT t1 LEFT JOIN COREPLNZ.TKON0010PER_DAG_DIM t2 ON (t1.OPGOR_DAG_I = t2.PER_DAG_I) LEFT JOIN COREPLNZ.TKON0010PER_DAG_DIM t6 ON (t1.AFVIKL_DAG_I = t6.PER_DAG_I) LEFT JOIN COREPLNZ.KXYZ0090_SKEMA_JUNK t3 ON (t1.SKEMA_XYZ_JUNK_I = t3.SKEMA_XYZ_JUNK_I) LEFT JOIN COREPLNZ.TXYZ0100_SKEMA_DIM t4 ON (t1.SKEMA_I = t4.SKEMA_I) LEFT JOIN COREPLNZ.TXYZ0200_KILDEFACT_DIM t5 ON (t1.KILDEFACT_I = t5.KILDEFACT_I) LEFT JOIN COREPLNZ.KLIK6000_RESTLOEBETID_FCT t7 ON (t1.KILDEFACT_Key_I = t7.RESTLOEBETID_FCT_I) WHERE t5.KILDEFACT_NAVN = 'TLIK6000_RESTLOEBETID_FCT' AND t4.SKEMA_KODE = 'C 73.00' AND t2.PERIODAG_D = &amp;str_SAStimestamp_Desc_sort ORDER BY t2.PER_DAG_I DESC; QUIT; </code></pre>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13340047/" ]
74,558,345
<p>I wrote a function which allows me to draw circles on a canvas. Everything works fine, but the start position of my canvas is not the same position as my mouse position.</p> <pre class="lang-js prettyprint-override"><code>const stopDrawingCircle = () =&gt; { setIsDrawing(false); console.log(currentImage); } //Setting start position const startDrawingCircle = (event:any) =&gt; { currentImage.circle.x = event.clientX; currentImage.circle.y = event.clientY; currentImage.circle.radius = 0; setIsDrawing(true); }; const drawCircle = function(event:any){ if(!isDrawing) return; let canvas = canvasRef.current as HTMLCanvasElement | null; let ctx = canvas?.getContext('2d') //seems to be the problem console log at start says the result of this is zero var currentX = currentImage.circle.x - event.clientX; var currentY = currentImage.circle.y - event.clientY; currentImage.circle.radius = Math.sqrt(currentX * currentX + currentY * currentY) if(canvas != null &amp;&amp; ctx != null){ ctx.beginPath(); ctx.arc(currentImage.circle.x, currentImage.circle.y, currentImage.circle.radius, 0, Math.PI*2); ctx.fill(); } } return( &lt;div className=&quot;main&quot;&gt; &lt;div id=&quot;imageSection&quot;&gt; &lt;canvas id=&quot;canvas&quot; onMouseDown={startDrawingCircle} onMouseUp={stopDrawingCircle} onMouseMove={drawCircle} ref={canvasRef}&gt; &lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; ) </code></pre> <p>The result of drawing a circle is like this:</p> <p><a href="https://i.stack.imgur.com/M1rhX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M1rhX.png" alt="example of fail" /></a></p> <p>I started with my mouse in the center of the image and he draws it in the &quot;lower right corner&quot;</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20136915/" ]
74,558,378
<p>I have this schema</p> <pre><code> _id: 637c96369088ef201f1a0924, timestamp: 1669109220, date: '2022-11-19', rates: { ALU: 13.467843419485, IRD: 0.00025380710659898, IRON: 351.21258466244, LCO: 0.62255678407529, LEAD: 15.222537878788, NI: 1.3163568621028, RUTH: 0.1, TIN: 1.5148619686393, USD: 1, XAG: 0.047328809297387, XAU: 0.00057311770347523, XCU: 4.4456793553765, XPD: 0.00055066079295154, XPT: 0.001010101010101, XRH: 0.000074626865671642, ZNC: 10.092283737024 }, __v: 0 } </code></pre> <p>and I need to create an API that gets one of the rate's key and return the value. I'm trying to create a dynamic query on mongoose, but I keep getting a null object.</p> <p>if I write the query like this:</p> <pre><code>await Metals.findOne({ 'rates.RUTH' : { $ne: null }} ).sort({ date: -1 }).exec </code></pre> <p>I get the right obj. but how to I change RUTH to be the dynamic key I got from the client?</p> <p>I tried to do:</p> <p><code>rates.${metalType}</code> but it returned null as well</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589274/" ]
74,558,382
<p>I am trying to build a database on US universities. I have been using Beautiful Soup and Pandas to do so, but have encounter difficulties as there were several tables to scrap per page. In order to reunite the data extracted from two tables, I tried to use .merge(), but haven't succeeded at all.</p> <p>My code is as follows:</p> <pre><code># Connecticut url='https://en.wikipedia.org/wiki/List_of_colleges_and_universities_in_Connecticut' soup=bs(requests.get(url).text) table = soup.find_all('table') #Extracting a df for each table df1 = pd.read_html(str(table))[0] df1.rename(columns = {'Enrollment(2020)[4]': 'Enrollment', 'Founded[5]':'Founded'}, inplace = True) df2 = pd.read_html(str(table))[1] df2=df2.drop(['Type','Ref.'], axis=1) df_Connecticut=df1.merge(df2, on=['School','Location','Control','Founded']) df_Connecticut </code></pre> <p>I have tried to do it with other states, but still encounter the same problem:</p> <pre><code> Maine url='https://en.wikipedia.org/wiki/List_of_colleges_and_universities_in_Maine' soup=bs(requests.get(url).text) table = soup.find_all('table') #Extracting a df for each table df1 = pd.read_html(str(table))[0] df1=df1.drop(['Type[a]'], axis=1) df1.rename(columns = {'Location(s)': 'Location', 'Enrollment (2019)[b]':'Enrollment'}, inplace = True) df1 = df1.astype({'School':'string','Location':'string','Control':'string','Enrollment':'string','Founded':'string'}) df2 = pd.read_html(str(table))[1] df2=df2.drop(['Cite'], axis=1) df2.rename(columns = {'Location(s)': 'Location'}, inplace = True) df2 = df2.astype({'School':'string','Location':'string','Founded':'string','Closed':'string'}) df_Maine=df1.merge(df2, on=['School','Location','Founded']) df_Maine``` </code></pre> <p>I am complete beginner in Python.</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589231/" ]
74,558,385
<p>By using the Godot engine and writing in the GDScript language, let's say I have an enum declared as:</p> <pre><code>enum eTextMode {CHAR, NUMBER, SYMBOLS_TEXT, SYMBOLS_ALL} </code></pre> <p>And an export variable as:</p> <pre><code>export(eTextMode, FLAGS) var _id: int = 0 </code></pre> <p>In the inspector panel I can see which flag is selected or not, but <strong>how can I know in code which specifically flag is selected?</strong></p> <p>By selecting in the inspector, for example: the <em>NUMBER</em> and <em>SYMBOLS_TEXT</em> flags, the <em>_id</em> variable will be set as 5</p> <p>My approach is the following hard-coded dictionary:</p> <pre><code>var _selected_flags: Dictionary = { CHAR = _id in [1, 3, 5, 7, 9, 11, 13, 15], NUMBER = _id in [2, 3, 6, 7, 10, 11, 14, 15], SYMBOLS_TEXT = _id in [4, 5, 6, 7, 12, 13, 14, 15], SYMBOLS_ALL = _id in [8, 9, 10, 11, 12, 13, 14, 15] } </code></pre> <p>Resulting in:</p> <pre><code>{CHAR:True, NUMBER:False, SYMBOLS_ALL:False, SYMBOLS_TEXT:True} </code></pre> <p>The above result is exactly what I'm expecting (a dictionary with string keys as they are defined in the <em>enum</em> with a <em>boolean</em> value representing the selection state).</p> <p><strong>How could I manage to do this dynamically for any <em>enum</em> regardless of size?</strong></p> <p>Thank you very much,</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15692942/" ]
74,558,414
<p>I am trying to add styles to my dialog header of my ui5 application, but the effect is not applied.</p> <p>Here is the code: `</p> <pre><code>onValueHelpRequest : function(oEvent) { var sInputValue = oEvent.getSource().getValue(), oView = this.getView(); if (!this._pValueHelpDialog) { this._pValueHelpDialog = sap.ui.xmlfragment( &quot;zpractice.fragment.ValueHelp&quot;, this); this._pValueHelpDialog.addEventDelegate({ onAfterRendering : function(oEvent) { $(&quot;#selectDialog-dialog-header-BarPH&quot;).css({ &quot;background-color&quot; : &quot;white&quot; }); } }) var oDialog = this._pValueHelpDialog; this.oView.addDependent(oDialog); oDialog.getBinding(&quot;items&quot;).filter( [ new Filter(&quot;name&quot;, FilterOperator.Contains, sInputValue) ]); } this._pValueHelpDialog.open(sInputValue); }, </code></pre> <p>`</p> <p>Could anyone help me with this?</p> <p>Thanks in advance!</p> <p>I tried to change the background of the header of the dialog box into white using jQuery.</p> <p>The effect is nit getting apllied!</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589291/" ]
74,558,443
<p>I have 4 lists and I want to print them, but it returns name of list.</p> <pre><code>list1 = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;] list2 = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] list3 = [&quot;a&quot;, &quot;b&quot;] list4 = [&quot;a&quot;] for i in range(1,5): print(list[i]) </code></pre> <p>It shows:</p> <pre class="lang-none prettyprint-override"><code>list[1] list[2] list[3] list[4] </code></pre> <p>I need, for example <code>[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]</code> for list1.</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589176/" ]
74,558,444
<p>I want to create a project in nuxt js in version 2.15.8. I researched, tried to do some ways that I know but it does not work. Does anyone know if this is possible and how to do it?</p>
[ { "answer_id": 74558229, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": true, "text": "const myJsonArr = arr.map((v) => JSON.stringify(v))\n" }, { "answer_id": 74558281, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": "let array = arr.map(item=>JSON.stringify(item))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15139592/" ]
74,558,457
<p>I am trying to compare the username and password for may auth. then i think everything is good at my code but it throws me an error if the username and password is incorrect and the nodejs is stopping this error give me [Here is my error] (<a href="https://i.stack.imgur.com/OSxpK.png" rel="nofollow noreferrer">https://i.stack.imgur.com/OSxpK.png</a>)</p> <p>and this is my code what I did in this code Im trying to compare the username and password</p> <pre><code></code></pre> <pre><code>router.post(&quot;/login&quot;, async (req, res) =&gt; { const {username, password} = req.body; const user = await Admin.findOne({where: {username: username}}); if (!user) res.json({error: &quot;Admin User doesn't exist&quot;}); bcrypt.compare(password, user.password).then((match) =&gt; { if(!match) res.json({error: &quot;Username and password is incorrect&quot;}); res.json(&quot;Login Success&quot;); }); }); </code></pre> <pre><code></code></pre> <p><strong>your text</strong></p>
[ { "answer_id": 74558714, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 1, "selected": true, "text": "router.post(\"/login\", async (req, res) => {\n try {\n const {username, password} = req.body;\n\n const user = await Admin.findOne({where: {username: username}});\n\n // make sure the user password was hashed befor saving\n // const hashPassword = await hash(password, await genSalt());\n\n if (!user) res.json({error: \"Admin User doesn't exist\"});\n\n const match = await bcrypt.compare(password, user.password)\n if(!match) {\n res.json({error: \"Username and password is incorrect\"});\n else {\n res.json(\"Login Success\");\n }\n }\n } catch(error) {\n // App logger log\n //check console in node terminal\n console.error('error authenticating', error)\n // return 500 http status code or may be a code \n // depending on how you are handling it in the client\n } \n\n});\n" }, { "answer_id": 74558716, "author": "Ramel Jay Cuña", "author_id": 20553470, "author_profile": "https://Stackoverflow.com/users/20553470", "pm_score": 1, "selected": false, "text": "const user = await Admin.findOne({where: {username: username}});\n\nif (!user) return res.status(400).json({error: \"Admin User doesn't exist\"});\n\nbcrypt.compare(password, user.password).then((match) => {\n if(!match) return res.status(400).json({error: \"Username and password is incorrect\"});\n res.json(\"Login Success\");\n});\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20553470/" ]
74,558,476
<p>I tried this on regex but the quote</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> let stringdata = "01110010100111101000111"; let output= stringdata .match(/(10)1?|(01)+0?/g); console.log(output);</code></pre> </div> </div> </p> <p>currently output, the code above is like this , I have missing <strong>single quotes</strong> <a href="https://i.stack.imgur.com/ywlVD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ywlVD.png" alt="enter image description here" /></a></p> <p><strong>but I want the output like this</strong> , did I miss something?</p> <pre><code>'01','','10','0101','','01','','','01010','','01','','','' </code></pre>
[ { "answer_id": 74559165, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 0, "selected": false, "text": "'01010' stringdata '1010', '', '01', '', '' 01 (?:01)+ 10 (?:10)+ 1 0 /(?:01)+|(?:10)+|1|0/g match const stringdata = '01110010100111101000111';\n\n// see ... [https://regex101.com/r/eqG6Xp/1]\nconst regXSequences = /(?:01)+|(?:10)+|1|0/g;\n\nconsole.log(\n stringdata\n .match(regXSequences)\n);\nconsole.log(\n stringdata\n .match(regXSequences)\n .map(value => value.length >= 2 && value || '')\n); .as-console-wrapper { min-height: 100%!important; top: 0; }" }, { "answer_id": 74559212, "author": "BootCamp", "author_id": 14385814, "author_profile": "https://Stackoverflow.com/users/14385814", "pm_score": -1, "selected": false, "text": "let result = text.match(/(0101)|(01)|(10)*/g) let result = text.match(/^.{0,20}/g);" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14385814/" ]
74,558,481
<p>is it possible to use react component in vue 2.4 app in way that react package is not installed in vue app an I will be able to pass props from vue to react component or run methods in react component or emit events from it?</p>
[ { "answer_id": 74559165, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 0, "selected": false, "text": "'01010' stringdata '1010', '', '01', '', '' 01 (?:01)+ 10 (?:10)+ 1 0 /(?:01)+|(?:10)+|1|0/g match const stringdata = '01110010100111101000111';\n\n// see ... [https://regex101.com/r/eqG6Xp/1]\nconst regXSequences = /(?:01)+|(?:10)+|1|0/g;\n\nconsole.log(\n stringdata\n .match(regXSequences)\n);\nconsole.log(\n stringdata\n .match(regXSequences)\n .map(value => value.length >= 2 && value || '')\n); .as-console-wrapper { min-height: 100%!important; top: 0; }" }, { "answer_id": 74559212, "author": "BootCamp", "author_id": 14385814, "author_profile": "https://Stackoverflow.com/users/14385814", "pm_score": -1, "selected": false, "text": "let result = text.match(/(0101)|(01)|(10)*/g) let result = text.match(/^.{0,20}/g);" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5499573/" ]
74,558,488
<p>I try to explain my problem in the simplest way.</p> <p>I have a table, let's call it <strong>Table_A</strong>, structured like this:</p> <p><code>ID | Name | Code | Status | Counter_A | Counter_B | Counter_C</code></p> <p>This Table_A is filled with data once a day.</p> <p>A second table, named <strong>Table_B</strong>, structurally identical to the previous one, takes the data in real-time (it is refreshed over and over again a day).</p> <p>I have to find a way to highlight daily if and which counter (Counter_A, Counter_B, Counter_C) is different between Table_A and Table_B.</p> <p>A numerical example:</p> <p><strong>Table_A</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Code</th> <th>Status</th> <th>Counter_A</th> <th>Counter_B</th> <th>Counter_C</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>aaa</td> <td>971283</td> <td>online</td> <td>0</td> <td>3</td> <td>0</td> </tr> <tr> <td>02</td> <td>bbb</td> <td>287301</td> <td>online</td> <td>4</td> <td>2</td> <td>2</td> </tr> <tr> <td>03</td> <td>ccc</td> <td>718923</td> <td>online</td> <td>5</td> <td>5</td> <td>5</td> </tr> <tr> <td>04</td> <td>ddd</td> <td>789021</td> <td>online</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>05</td> <td>eee</td> <td>890123</td> <td>online</td> <td>1</td> <td>1</td> <td>4</td> </tr> </tbody> </table> </div> <p><strong>Table_B</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Code</th> <th>Status</th> <th>Counter_A</th> <th>Counter_B</th> <th>Counter_C</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>aaa</td> <td>971283</td> <td>online</td> <td>0</td> <td>3</td> <td><strong>1</strong></td> </tr> <tr> <td>02</td> <td>bbb</td> <td>287301</td> <td>online</td> <td><strong>0</strong></td> <td>2</td> <td>2</td> </tr> <tr> <td>03</td> <td>ccc</td> <td>718923</td> <td>online</td> <td>5</td> <td>5</td> <td>5</td> </tr> <tr> <td>04</td> <td>ddd</td> <td>789021</td> <td>online</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>05</td> <td>eee</td> <td>890123</td> <td>online</td> <td><strong>0</strong></td> <td><strong>0</strong></td> <td><strong>2</strong></td> </tr> </tbody> </table> </div> <p>My idea would be to run a script daily and check if the counters are the same, adding incremental columns to a view_B, so that view_B would be:</p> <p><strong>View_B</strong> ( What I want )</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Code</th> <th>Status</th> <th>Counter_A</th> <th>Counter_B</th> <th>Counter_C</th> <th>Counter_A_check</th> <th>Counter_B_check</th> <th>Counter_C_check</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>aaa</td> <td>971283</td> <td>online</td> <td>0</td> <td>3</td> <td>1</td> <td>0</td> <td>0</td> <td><strong>1</strong></td> </tr> <tr> <td>02</td> <td>bbb</td> <td>287301</td> <td>online</td> <td>0</td> <td>2</td> <td>2</td> <td><strong>1</strong></td> <td>0</td> <td>0</td> </tr> <tr> <td>03</td> <td>ccc</td> <td>718923</td> <td>online</td> <td>5</td> <td>5</td> <td>5</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>04</td> <td>ddd</td> <td>789021</td> <td>online</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>05</td> <td>eee</td> <td>890123</td> <td>online</td> <td>0</td> <td>0</td> <td>2</td> <td><strong>1</strong></td> <td><strong>1</strong></td> <td><strong>1</strong></td> </tr> </tbody> </table> </div> <p>If the data is not the same, then I increase the value by one. In this way I would know in addition to the discrepancy, also for how many days the values have been misaligned. In the example, 1 = one-day misaligned.</p> <p>it seems to work but I don't know how to implement it in SQL</p> <p>Currently I have set up the two tables. The View_B and the script are missing.</p>
[ { "answer_id": 74559165, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 0, "selected": false, "text": "'01010' stringdata '1010', '', '01', '', '' 01 (?:01)+ 10 (?:10)+ 1 0 /(?:01)+|(?:10)+|1|0/g match const stringdata = '01110010100111101000111';\n\n// see ... [https://regex101.com/r/eqG6Xp/1]\nconst regXSequences = /(?:01)+|(?:10)+|1|0/g;\n\nconsole.log(\n stringdata\n .match(regXSequences)\n);\nconsole.log(\n stringdata\n .match(regXSequences)\n .map(value => value.length >= 2 && value || '')\n); .as-console-wrapper { min-height: 100%!important; top: 0; }" }, { "answer_id": 74559212, "author": "BootCamp", "author_id": 14385814, "author_profile": "https://Stackoverflow.com/users/14385814", "pm_score": -1, "selected": false, "text": "let result = text.match(/(0101)|(01)|(10)*/g) let result = text.match(/^.{0,20}/g);" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10886833/" ]
74,558,524
<p>I try to added data in to <code>dayResult</code> key using date-wise like in shortlisted <code>[]</code> add all array data in to shortlisted <code>[ ]</code> also sum of <code>slotAvailable</code> my JSON format is below mention kindly help me for to added data.</p> <p>This is my Input JSON data.</p> <pre><code> { &quot;date&quot;: &quot;2022-08-01&quot;, &quot;dayResult&quot;: [ { &quot;date&quot;: &quot;2022-08-01T18:29:59.999Z&quot;, &quot;day&quot;: 1, &quot;shortlisted&quot;: [ &quot;62e76c83b61203589ed06682&quot; ], &quot;slotAvailable&quot;: 0 }, { &quot;date&quot;: &quot;2022-08-01T18:29:59.999Z&quot;, &quot;day&quot;: 1, &quot;shortlisted&quot;: [ &quot;62e76c83b61203589ed06682&quot;, &quot;62e7644f4c8f8d7b2a2d661c&quot; ], &quot;slotAvailable&quot;: 2 }, { &quot;date&quot;: &quot;2022-08-01T18:29:59.999Z&quot;, &quot;day&quot;: 1, &quot;shortlisted&quot;: [], &quot;slotAvailable&quot;: 1 } ] }, { &quot;date&quot;: &quot;2022-08-02&quot;, &quot;dayResult&quot;: [ { &quot;date&quot;: &quot;2022-08-02T18:29:59.999Z&quot;, &quot;day&quot;: 2, &quot;shortlisted&quot;: [ &quot;62e76c83b61203589ed06687&quot;, &quot;62e7644f4c8f8d7b2a2d661a&quot; ], &quot;slotAvailable&quot;: 0 }, { &quot;date&quot;: &quot;2022-08-02T18:29:59.999Z&quot;, &quot;day&quot;: 2, &quot;shortlisted&quot;: [ &quot;62e76c83b61203589ed06682&quot;, &quot;62e7644f4c8f8d7b2a2d661c&quot; ], &quot;slotAvailable&quot;: 1 }, { &quot;date&quot;: &quot;2022-08-02T18:29:59.999Z&quot;, &quot;day&quot;: 2, &quot;shortlisted&quot;: [], &quot;slotAvailable&quot;: 6 } ] } ] </code></pre> <p>This is my wanted out put</p> <pre><code>[ { &quot;date&quot;: &quot;2022-08-01&quot;, &quot;dayResult&quot;: [ { &quot;date&quot;: &quot;2022-08-01T18:29:59.999Z&quot;, &quot;day&quot;: 1, &quot;shortlisted&quot;: [ &quot;62e76c83b61203589ed06682&quot;, &quot;62e7644f4c8f8d7b2a2d661c&quot; ], &quot;slotAvailable&quot;: 3 } ] }, { &quot;date&quot;: &quot;2022-08-02&quot;, &quot;dayResult&quot;: [ { &quot;date&quot;: &quot;2022-08-02T18:29:59.999Z&quot;, &quot;day&quot;: 2, &quot;shortlisted&quot;: [ &quot;62e76c83b61203589ed06687&quot;, &quot;62e7644f4c8f8d7b2a2d661a&quot;, &quot;62e76c83b61203589ed06682&quot;, &quot;62e7644f4c8f8d7b2a2d661c&quot; ], &quot;slotAvailable&quot;: 7 } ] } ] </code></pre> <p>So for that I try this kind of code but its not works as accepted.</p> <pre><code>let dateArr = {}; for (let i = 0; i &lt; groupArrays.length; i++) { const item = groupArrays[i]; item.dayResult.map((data) =&gt;{ dateArr.date = data.date; dateArr.day = data.day; dateArr.interviewScheduled = [...data.interviewScheduled] }) } </code></pre> <p>Please help me for this kind of out put using javascript.</p>
[ { "answer_id": 74558779, "author": "jsN00b", "author_id": 13658816, "author_profile": "https://Stackoverflow.com/users/13658816", "pm_score": 2, "selected": false, "text": "// method to transform array to desired structure\nconst myTransform = arr => (arr.map( // map each array elt\n ({date: myDt, dayResult: dr}) => ({\n date: myDt,\n dayResult: dr.reduce( // iterate over inner \"dayResult\" array\n (acc, { // destructure & rename date, day, shortlisted, slotAvailable props\n date: myDt2, day: myDy, shortlisted: sh, slotAvailable: sa\n }) => {\n acc ??= {}; // nullish coalesce assignment for accumulator \"acc\" to empty object\n acc[\"date\"] ??= myDt2; // assign date, if not already present\n acc[\"day\"] ??= myDy; // assign day, if not already present\n acc[\"shortlisted\"] ??= []; // set-up shortlisted as empty array, if not already\n sh.forEach(sItm => { // add each shortlisted item if it is not already present\n if (!(acc[\"shortlisted\"].includes(sItm))) {\n acc[\"shortlisted\"].push(sItm);\n }\n });\n acc[\"slotAvailable\"] ??= 0; // set-up slotAvailable as zero, if not already present\n acc[\"slotAvailable\"] += sa; // increment slotAvailable based on current elt\n return acc; // always return the accumulator \"acc\"\n },\n {} // initialize the \"acc\" as an empty object\n )}) // implicit return\n));\n\n\nconst rawJsonData = [{\n \"date\": \"2022-08-01\",\n \"dayResult\": [{\n \"date\": \"2022-08-01T18:29:59.999Z\",\n \"day\": 1,\n \"shortlisted\": [\n \"62e76c83b61203589ed06682\"\n ],\n \"slotAvailable\": 0\n\n },\n {\n \"date\": \"2022-08-01T18:29:59.999Z\",\n \"day\": 1,\n \"shortlisted\": [\n \"62e76c83b61203589ed06682\",\n \"62e7644f4c8f8d7b2a2d661c\"\n ],\n \"slotAvailable\": 2\n\n },\n {\n \"date\": \"2022-08-01T18:29:59.999Z\",\n \"day\": 1,\n \"shortlisted\": [],\n \"slotAvailable\": 1\n\n }\n ]\n}, {\n \"date\": \"2022-08-02\",\n \"dayResult\": [{\n \"date\": \"2022-08-02T18:29:59.999Z\",\n \"day\": 2,\n \"shortlisted\": [\n \"62e76c83b61203589ed06687\",\n \"62e7644f4c8f8d7b2a2d661a\"\n ],\n \"slotAvailable\": 0\n\n },\n {\n \"date\": \"2022-08-02T18:29:59.999Z\",\n \"day\": 2,\n \"shortlisted\": [\n \"62e76c83b61203589ed06682\",\n \"62e7644f4c8f8d7b2a2d661c\"\n ],\n \"slotAvailable\": 1\n\n },\n {\n \"date\": \"2022-08-02T18:29:59.999Z\",\n \"day\": 2,\n \"shortlisted\": [],\n \"slotAvailable\": 6\n\n }\n ]\n}];\n\nconsole.log('Transformed data:\\n', myTransform(rawJsonData)); .as-console-wrapper { max-height: 100% !important; top: 0 }" }, { "answer_id": 74558808, "author": "AbsoluteZero", "author_id": 20539156, "author_profile": "https://Stackoverflow.com/users/20539156", "pm_score": 2, "selected": false, "text": "Array.prototype.map Array.prototype.reduce [...new Set(Array)] const mappedData = data.map((v) => {\n const { date, dayResult } = v;\n \n const mergedDayResults = dayResult.reduce((prev, curr) => ({\n ...prev,\n shortlisted: [\n ...prev.shortlisted,\n ...curr.shortlisted,\n ],\n slotAvailable: prev.slotAvailable + curr.slotAvailable,\n }), dayResult[0])\n \n return {\n date,\n dayResults: {\n ...mergedDayResults,\n shortlisted: Array.from(new Set(mergedDayResults.shortlisted)),\n }\n }\n});\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7260158/" ]
74,558,578
<p>Let it be the following python pandas DataFrame where each row represents a person's stay in a hotel.</p> <pre><code>| entry_date | exit_date | days | other_columns | | ---------- | ---------- | ------ | ------------- | | 2022-02-01 | 2022-02-05 | 5 | ... | | 2022-02-02 | 2022-02-03 | 2 | ... | | 2022-04-10 | 2022-04-13 | 4 | ... | | 2022-04-11 | 2022-04-12 | 2 | ... | | 2022-04-12 | 2022-04-13 | 2 | ... | | 2022-11-10 | 2022-11-15 | 6 | ... | </code></pre> <p>I want to make a DataFrame from the previous one, where it represents for each day, the occupancy of the hotel at that moment. I am not taking into account the nights, just the days variable.</p> <pre><code>| date | ocupation | | ---------- | ---------- | | 2022-02-01 | 1 | | 2022-02-02 | 2 | | 2022-02-03 | 2 | | 2022-02-04 | 1 | | 2022-02-05 | 1 | | 2022-04-10 | 1 | | 2022-04-11 | 2 | | 2022-04-12 | 3 | | 2022-04-13 | 2 | | 2022-11-10 | 1 | | 2022-11-11 | 1 | | 2022-11-12 | 1 | | 2022-11-13 | 1 | | 2022-11-14 | 1 | | 2022-11-15 | 1 | </code></pre>
[ { "answer_id": 74558705, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "#convert column to datetimes\ndf['entry_date'] = pd.to_datetime(df['entry_date'])\n\n#repeat rows by days column\ndf = df.loc[df.index.repeat(df['days'])]\n\n#create days timedeltas\ntd = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')\n\n#add timedeltas by datetiems and count to 2 columns DataFrame\ndf1 = (df['entry_date'].add(td)\n .value_counts()\n .sort_index()\n .rename_axis('date')\n .reset_index(name='ocupation'))\nprint (df1)\n\n date ocupation\n0 2022-02-01 1\n1 2022-02-02 2\n2 2022-02-03 2\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-04-10 1\n6 2022-04-11 2\n7 2022-04-12 3\n8 2022-04-13 2\n9 2022-11-10 1\n10 2022-11-11 1\n11 2022-11-12 1\n12 2022-11-13 1\n13 2022-11-14 1\n14 2022-11-15 1\n df = pd.concat([df] * 1000, ignore_index=True)\n\ndef jez(df):\n #convert column to datetimes\n df['entry_date'] = pd.to_datetime(df['entry_date'], dayfirst=True)\n \n #repeat rows by days column\n df = df.loc[df.index.repeat(df['days'])]\n \n #create days timedeltas\n td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')\n \n #add timedeltas by datetiems and count to 2 columns DataFrame\n return (df['entry_date'].add(td)\n .value_counts()\n .sort_index()\n .rename_axis('date')\n .reset_index(name='ocupation'))\n \n\n\ndef moz(df):\n return (pd.Series([d for start, end in zip(df['entry_date'], df['exit_date'])\n for d in pd.date_range(start, end, freq='D')], name='date')\n .value_counts(sort=False)\n .reset_index(name='ocupation')\n )\n In [122]: %timeit jez(df)\n15.3 ms ± 470 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [123]: %timeit moz(df)\n2.31 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" }, { "answer_id": 74558775, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "date_range value_counts # ensure datetime\n# for year-day-month\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=True)\n# for year-month-day\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=False)\n\n\n(pd.Series([d for start, end in zip(df['entry_date'], df['exit_date'])\n for d in pd.date_range(start, end, freq='D')], name='date')\n .value_counts(sort=False)\n .reset_index(name='ocupation')\n)\n index ocupation\n0 2022-02-01 1\n1 2022-02-02 2\n2 2022-02-03 2\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-04-10 1\n6 2022-04-11 2\n7 2022-04-12 3\n8 2022-04-13 2\n9 2022-11-10 1\n10 2022-11-11 1\n11 2022-11-12 1\n12 2022-11-13 1\n13 2022-11-14 1\n14 2022-11-15 1\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18396935/" ]
74,558,590
<p>I need to check if a file exists in a gitlab deployment pipeline. How to do it efficiently and reliably?</p>
[ { "answer_id": 74558705, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "#convert column to datetimes\ndf['entry_date'] = pd.to_datetime(df['entry_date'])\n\n#repeat rows by days column\ndf = df.loc[df.index.repeat(df['days'])]\n\n#create days timedeltas\ntd = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')\n\n#add timedeltas by datetiems and count to 2 columns DataFrame\ndf1 = (df['entry_date'].add(td)\n .value_counts()\n .sort_index()\n .rename_axis('date')\n .reset_index(name='ocupation'))\nprint (df1)\n\n date ocupation\n0 2022-02-01 1\n1 2022-02-02 2\n2 2022-02-03 2\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-04-10 1\n6 2022-04-11 2\n7 2022-04-12 3\n8 2022-04-13 2\n9 2022-11-10 1\n10 2022-11-11 1\n11 2022-11-12 1\n12 2022-11-13 1\n13 2022-11-14 1\n14 2022-11-15 1\n df = pd.concat([df] * 1000, ignore_index=True)\n\ndef jez(df):\n #convert column to datetimes\n df['entry_date'] = pd.to_datetime(df['entry_date'], dayfirst=True)\n \n #repeat rows by days column\n df = df.loc[df.index.repeat(df['days'])]\n \n #create days timedeltas\n td = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='d')\n \n #add timedeltas by datetiems and count to 2 columns DataFrame\n return (df['entry_date'].add(td)\n .value_counts()\n .sort_index()\n .rename_axis('date')\n .reset_index(name='ocupation'))\n \n\n\ndef moz(df):\n return (pd.Series([d for start, end in zip(df['entry_date'], df['exit_date'])\n for d in pd.date_range(start, end, freq='D')], name='date')\n .value_counts(sort=False)\n .reset_index(name='ocupation')\n )\n In [122]: %timeit jez(df)\n15.3 ms ± 470 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [123]: %timeit moz(df)\n2.31 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" }, { "answer_id": 74558775, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "date_range value_counts # ensure datetime\n# for year-day-month\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=True)\n# for year-month-day\ndf[['entry_date', 'exit_date']] = df[['entry_date', 'exit_date']].apply(pd.to_datetime, dayfirst=False)\n\n\n(pd.Series([d for start, end in zip(df['entry_date'], df['exit_date'])\n for d in pd.date_range(start, end, freq='D')], name='date')\n .value_counts(sort=False)\n .reset_index(name='ocupation')\n)\n index ocupation\n0 2022-02-01 1\n1 2022-02-02 2\n2 2022-02-03 2\n3 2022-02-04 1\n4 2022-02-05 1\n5 2022-04-10 1\n6 2022-04-11 2\n7 2022-04-12 3\n8 2022-04-13 2\n9 2022-11-10 1\n10 2022-11-11 1\n11 2022-11-12 1\n12 2022-11-13 1\n13 2022-11-14 1\n14 2022-11-15 1\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16986712/" ]
74,558,591
<p>I have a file <strong>in1.txt</strong></p> <pre><code>info=&quot;0x0000b573&quot; data=&quot;0x7&quot; id=&quot;sp. PCU(Si)&quot; info=&quot;0x0000b573&quot; data=&quot;0x00000007&quot; id=&quot;HI all. SHa&quot; info=&quot;0x00010AC3&quot; data=&quot;0x00000003&quot; id=&quot;abc_16. PS&quot; info=&quot;0x00010ac3&quot; data=&quot;0x00000045&quot; id=&quot;hB2_RC/BS (Spr)&quot; info=&quot;0x205&quot; data=&quot;0x00000010&quot; id=&quot;cgc_15. PK&quot; info=&quot;0x205&quot; data=&quot;0x10&quot; id=&quot;cgsd_GH/BS (Scd)&quot; </code></pre> <p>Expected output: <strong>out.txt</strong></p> <pre><code>info=&quot;0x00010AC3&quot; data=&quot;0x00000003&quot; id=&quot;abc_16. PS&quot; info=&quot;0x00010ac3&quot; data=&quot;0x00000045&quot; id=&quot;hB2_RC/BS (Spr)&quot; </code></pre> <p>I need only lines that have same <strong>info</strong> values and different <strong>data</strong> values to be written to out.txt.</p> <p>but the current code removes all the line that have string data in it.</p> <pre><code>with open(&quot;in.txt&quot;, &quot;r&quot;) as fin,open(&quot;out.txt&quot;, &quot;w&quot;) as fout: for line in fin: if 'data' not in line: fout.write(line.strip()+'\n') </code></pre> <p>what i need is for eg: line 1 and line 2 is having same <code>info=&quot;0x0000b573&quot;</code> and data is <code>&quot;0x7&quot; &amp; &quot;0x00000007</code>&quot; which is same then remove that line.</p>
[ { "answer_id": 74558958, "author": "Epsi95", "author_id": 6660638, "author_profile": "https://Stackoverflow.com/users/6660638", "pm_score": 1, "selected": false, "text": "regex import re\n\ns = '''info=\"0x0000b573\" data=\"0x7\" id=\"sp. PCU(Si)\"\ninfo=\"0x0000b573\" data=\"0x00000007\" id=\"HI all. SHa\"\ninfo=\"0x00010AC3\" data=\"0x00000003\" id=\"abc_16. PS\"\ninfo=\"0x00010ac3\" data=\"0x00000045\" id=\"hB2_RC/BS (Spr)\"\ninfo=\"0x205\" data=\"0x00000010\" id=\"cgc_15. PK\"\ninfo=\"0x205\" data=\"0x10\" id=\"cgsd_GH/BS (Scd)\"'''\n\nparsed_data = re.findall(r'info=\"([^\"]+)\" data=\"([^\"]+)\" id=\"[^\"]+\"', s, re.MULTILINE)\nparsed_data = sorted([list(map(lambda x: int(x, 16), i)) + [index] for index,i in enumerate(parsed_data)])\n\nrow_numbers = [j for i in [[parsed_data[i][-1], parsed_data[i+1][-1]] for i in range(0,len(parsed_data),2) if parsed_data[i][1] != parsed_data[i+1][1]] for j in i]\n\n\nfinal_output = []\n\nfor index,line in enumerate(s.split('\\n')):\n if index in row_numbers:\n final_output.append(line)\n \n \nfinal_out_text = '\\n'.join(final_output)\nprint(final_out_text)\n\n# info=\"0x00010AC3\" data=\"0x00000003\" id=\"abc_16. PS\"\n# info=\"0x00010ac3\" data=\"0x00000045\" id=\"hB2_RC/BS (Spr)\"\n" }, { "answer_id": 74558969, "author": "TorNato", "author_id": 13102310, "author_profile": "https://Stackoverflow.com/users/13102310", "pm_score": 0, "selected": false, "text": "found_info_values = []\n\nwith open(\"in.txt\", \"r\") as fin,open(\"out.txt\", \"w\") as fout:\n for line in fin:\n info = line.split('\"')[1]\n if info not in found_info_values:\n fout.write(line.strip()+'\\n')\n found_info_values += info\n" }, { "answer_id": 74564289, "author": "Ulisse Rubizzo", "author_id": 4412510, "author_profile": "https://Stackoverflow.com/users/4412510", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python3\n\nrecords = {}\nitems = []\ninfo = []\ndata = []\n\nwith open(\"in.dat\", \"r\") as fin:\n for line in fin:\n items=line.split(' ')\n info = items[0].split('=')\n data = items[1].split('=')\n try:\n key = info[1].strip('\"').lower()\n value = str(int(data[1].strip('\"'), 16))\n records[key][value] += 1\n except KeyError:\n try:\n records[key][value] = 1\n except KeyError:\n records[key] = {value: 1}\n\n\nout = dict()\nfor key in records:\n for value in records[key]:\n if records[key][value] == 1:\n try:\n out[key].append(value)\n except KeyError:\n out[key] = [value]\n \n\nwith open(\"out.dat\", \"w\") as fout:\n for key in out:\n for value in out[key]:\n fout.write(f\"{key}={value}\\n\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273554/" ]
74,558,762
<p>I am trying to convert the following string '1.12.22 14:16UTC+01:00' in Pandas to December 1st 2022</p> <pre><code>my_date = '1.12.22 14:16UTC+01:00' new_date = pd.to_datetime(my_date) </code></pre> <p>Timestamp('2022-01-12 14:16:00-0100', tz='pytz.FixedOffset(-60)')</p> <p>It inverts month with day only in specific cases. I am trying to use format=&quot;%d.%m.%Y %H:%M%z&quot; but it says that the string is not matching the format.</p> <p><code>time data '1.12.22 14:16UTC+01:00' does not match format '%d.%m.%Y %H:%M%z' (match)</code></p> <p>Thanks for your help.</p>
[ { "answer_id": 74558817, "author": "Oleg", "author_id": 13165337, "author_profile": "https://Stackoverflow.com/users/13165337", "pm_score": 1, "selected": false, "text": "my_date = '01.12.22 14:16UTC+01:00'" }, { "answer_id": 74558877, "author": "tangolin", "author_id": 14641214, "author_profile": "https://Stackoverflow.com/users/14641214", "pm_score": 3, "selected": true, "text": ">>> pd.to_datetime('01.12.22 14:16UTC', format='%d.%m.%y %H:%M%Z')\nTimestamp('2022-12-01 14:16:00+0000', tz='UTC')\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13643243/" ]
74,558,778
<p>Is there a way to get the N iteration of an SQL query ?</p> <p>For example, if I want the second iteration :</p> <p><strong>Backup</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>id_device</th> <th>nb_cut</th> </tr> </thead> <tbody> <tr> <td>11</td> <td>222</td> <td>853</td> </tr> <tr> <td>10</td> <td>5</td> <td>698</td> </tr> <tr> <td>9</td> <td>222</td> <td>589</td> </tr> <tr> <td>8</td> <td>5</td> <td>123</td> </tr> <tr> <td>7</td> <td>222</td> <td>456</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> </tr> </tbody> </table> </div> <pre><code>SELECT nb_cut FROM Backup WHERE id_device = 5 ORDER BY id DESC; </code></pre> <p>This query return <strong>698</strong>. But I want the seconde iteration whose result would be <strong>123</strong>.</p>
[ { "answer_id": 74558817, "author": "Oleg", "author_id": 13165337, "author_profile": "https://Stackoverflow.com/users/13165337", "pm_score": 1, "selected": false, "text": "my_date = '01.12.22 14:16UTC+01:00'" }, { "answer_id": 74558877, "author": "tangolin", "author_id": 14641214, "author_profile": "https://Stackoverflow.com/users/14641214", "pm_score": 3, "selected": true, "text": ">>> pd.to_datetime('01.12.22 14:16UTC', format='%d.%m.%y %H:%M%Z')\nTimestamp('2022-12-01 14:16:00+0000', tz='UTC')\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7316992/" ]
74,558,800
<p>I have a data set formatted as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>sha</th> <th>0_x</th> <th>1_x</th> <th>N_x</th> </tr> </thead> <tbody> <tr> <td>Sha1</td> <td>rm</td> <td></td> <td>rm</td> </tr> <tr> <td>Sha2</td> <td>rw</td> <td></td> <td>rw</td> </tr> <tr> <td>Sha3</td> <td></td> <td></td> <td>rw</td> </tr> <tr> <td>Sha4</td> <td></td> <td>tr</td> <td></td> </tr> </tbody> </table> </div> <p>In particular, the dataset currently contains about 2000 columns.</p> <p>I want to reduce the number of columns removing as many as possible the empty rows, as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>sha</th> <th>0_x</th> <th>1_x</th> </tr> </thead> <tbody> <tr> <td>Sha1</td> <td>rm</td> <td>rm</td> </tr> <tr> <td>Sha2</td> <td>rw</td> <td>rw</td> </tr> <tr> <td>Sha3</td> <td>rw</td> <td></td> </tr> <tr> <td>Sha4</td> <td>tr</td> <td></td> </tr> </tbody> </table> </div> <p>I don't care about the names of the columns.</p>
[ { "answer_id": 74558881, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "NaN replace('', np.nan) stack pivot cols = df.columns[1:]\n# ['0_x', '1_x', 'N_x']\n\n(df.set_index('sha')\n .stack()\n .reset_index()\n .assign(cols=lambda d: d.groupby('sha')\n .cumcount()\n .map(dict(enumerate(cols)))\n )\n .pivot(index='sha', columns='cols', values=0)\n .reset_index()\n)\n apply cols = list(df.columns[1:])\n# ['0_x', '1_x', 'N_x']\n\n(df.set_index('sha')\n .apply(lambda s: s.dropna().reset_index(drop=True), axis=1)\n .pipe(lambda d: d.set_axis(cols[:len(d.columns)], axis=1))\n .reset_index()\n)\n cols sha 0_x 1_x\n0 Sha1 rm rm\n1 Sha2 rw rw\n2 Sha3 rw NaN\n3 Sha4 tr NaN\n" }, { "answer_id": 74559537, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 0, "selected": false, "text": "(df.set_index('sha')\n .replace(r'$', '_', regex=True)\n .replace(np.nan, '')\n .sum(numeric_only=False, axis=1)\n .str.split('_+', regex=True, expand=True)\n .replace('', np.nan)\n .dropna(how='all', axis=1)\n .pipe(lambda d: d.set_axis(d.columns.astype('str') + '_x', axis=1))\n .reset_index())\n sha 0_x 1_x\n0 Sha1 rm rm\n1 Sha2 rw rw\n2 Sha3 rw NaN\n3 Sha4 tr NaN\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19505786/" ]
74,558,839
<p>How can I enforce the &quot;object&quot; property only to allow the listed properties be part of it and not something else, especially an empty key &quot;&quot;?</p> <pre><code>{ &quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: { &quot;object&quot;: { &quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: { &quot;property1&quot;: { &quot;type&quot;: &quot;string&quot; }, &quot;property2&quot;: { &quot;type&quot;: &quot;string&quot; }, &quot;property3&quot;: { &quot;type&quot;: &quot;string&quot; } }, &quot;uniqueItems&quot;: true } } } </code></pre>
[ { "answer_id": 74560069, "author": "Daniel Schneider", "author_id": 8821969, "author_profile": "https://Stackoverflow.com/users/8821969", "pm_score": 2, "selected": true, "text": "\"additionalProperties\": false additionalProperties \"object\" {\n \"type\": \"object\",\n \"properties\": {\n \"property1\": {\n \"type\": \"string\"\n },\n \"property2\": {\n \"type\": \"string\"\n },\n \"property3\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n}\n" }, { "answer_id": 74561174, "author": "Jordan Jordanovski", "author_id": 5971094, "author_profile": "https://Stackoverflow.com/users/5971094", "pm_score": 0, "selected": false, "text": "\"additionalProperties\": false {\n \"type\": \"object\",\n \"properties\": {\n \"object\": {\n \"type\": \"object\",\n \"properties\": {\n \"property1\": {\n \"type\": \"string\"\n },\n \"property2\": {\n \"type\": \"string\"\n },\n \"property3\": {\n \"type\": \"string\"\n }\n },\n \"uniqueItems\": true,\n \"additionalProperties\": false // will not allow any other property other than 'property1', 'property2' or 'property3' as part of the nested object \"object\".\n }\n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5971094/" ]
74,558,880
<p>I've trying to connect to amazon api for a week now. I've got stuck in this error and after readig the doc several times I can't realize which is the problem.</p> <p>Here is my code:</p> <pre><code># Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 &quot;&quot;&quot; Important The AWS SDKs sign API requests for you using the access key that you specify when you configure the SDK. When you use an SDK, you don’t need to learn how to sign API requests. We recommend that you use the AWS SDKs to send API requests, instead of writing your own code. The following example is a reference to help you get started if you have a need to write your own code to send and sign requests. The example is for reference only and is not maintained as functional code. &quot;&quot;&quot; # AWS Version 4 signing example # EC2 API (DescribeRegions) # See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html # This version makes a GET request and passes the signature # in the Authorization header. import sys, os, base64, datetime, hashlib, hmac import requests # pip install requests # ************* REQUEST VALUES ************* method = 'GET' service = 'execute-api' host = 'sellingpartnerapi-na.amazon.com' region = 'us-east-1' endpoint = 'https://sellingpartnerapi-na.amazon.com' request_parameters = 'Action=ListOrders&amp;MarketplaceId=ATVPDKIKX0DER&amp;Version=0' #service = 'ec2' #host = 'ec2.amazonaws.com' #region = 'us-east-1' #endpoint = 'https://ec2.amazonaws.com' #request_parameters = 'Action=DescribeRegions&amp;Version=2013-10-15' # Key derivation functions. See: # http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python def sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() def getSignatureKey(key, dateStamp, regionName, serviceName): kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, 'aws4_request') return kSigning # Read AWS access key from env. variables or configuration file. Best practice is NOT # to embed credentials in code. access_key = 'AKIEXAMPLE' secret_key = 'SECRETEXAMPLE' if access_key is None or secret_key is None: print('No access key is available.') sys.exit() # Create a date for headers and the credential string t = datetime.datetime.utcnow() amzdate = t.strftime('%Y%m%dT%H%M%SZ') datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope # ************* TASK 1: CREATE A CANONICAL REQUEST ************* # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html # Step 1 is to define the verb (GET, POST, etc.)--already done. # Step 2: Create canonical URI--the part of the URI from domain to query # string (use '/' if no path) canonical_uri = '/orders/v0/orders' # Step 3: Create the canonical query string. In this example (a GET request), # request parameters are in the query string. Query string values must # be URL-encoded (space=%20). The parameters must be sorted by name. # For this example, the query string is pre-formatted in the request_parameters variable. canonical_querystring = request_parameters # Step 4: Create the canonical headers and signed headers. Header names # must be trimmed and lowercase, and sorted in code point order from # low to high. Note that there is a trailing \n. canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n' # Step 5: Create the list of signed headers. This lists the headers # in the canonical_headers list, delimited with &quot;;&quot; and in alpha order. # Note: The request can include any headers; canonical_headers and # signed_headers lists those that you want to be included in the # hash of the request. &quot;Host&quot; and &quot;x-amz-date&quot; are always required. signed_headers = 'host;x-amz-date' # Step 6: Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (&quot;&quot;). payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest() # Step 7: Combine elements to create canonical request canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash # ************* TASK 2: CREATE THE STRING TO SIGN************* # Match the algorithm to the hashing algorithm you use, either SHA-1 or # SHA-256 (recommended) algorithm = 'AWS4-HMAC-SHA256' credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request' string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest() # ************* TASK 3: CALCULATE THE SIGNATURE ************* # Create the signing key using the function defined above. signing_key = getSignatureKey(secret_key, datestamp, region, service) # Sign the string_to_sign using the signing_key signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest() # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST ************* # The signing information can be either in a query string value or in # a header named Authorization. This code shows how to use a header. # Create authorization header and add to request headers authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature # The request can include any headers, but MUST include &quot;host&quot;, &quot;x-amz-date&quot;, # and (for this scenario) &quot;Authorization&quot;. &quot;host&quot; and &quot;x-amz-date&quot; must # be included in the canonical_headers and signed_headers, as noted # earlier. Order here is not significant. # Python note: The 'host' header is added automatically by the Python 'requests' library. headers = {'x-amz-date':amzdate, 'Authorization':authorization_header} # ************* SEND THE REQUEST ************* request_url = endpoint + '?' + canonical_querystring print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++') print('Request URL = ' + request_url) r = requests.get(request_url, headers=headers) print('\nRESPONSE++++++++++++++++++++++++++++++++++++') print('Response code: %d\n' % r.status_code) print(r.text) </code></pre> <p>My application is originally built in Java, but since I've got the same error in the Python code sample from amazon, I'm tring to make it work first in Python.</p> <p>It's also interesting that if I uncomment the code:</p> <pre><code>#service = 'ec2' #host = 'ec2.amazonaws.com' #region = 'us-east-1' #endpoint = 'https://ec2.amazonaws.com' #request_parameters = 'Action=DescribeRegions&amp;Version=2013-10-15' </code></pre> <p>It works, but if I use my own endpoints it doesn't. I've checked everything and tried a lot of things, any idea of why this is happening? Thanks in advance for your time.</p> <pre><code>The full error msg { &quot;errors&quot;: [ { &quot;message&quot;: &quot;The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. &quot;code&quot;: &quot;InvalidSignature&quot; } ] } </code></pre>
[ { "answer_id": 74626058, "author": "ChalsBP", "author_id": 14839276, "author_profile": "https://Stackoverflow.com/users/14839276", "pm_score": 1, "selected": true, "text": "\n# AWS Version 4 signing example\n\n# EC2 API (DescribeRegions)\n\n# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n# This version makes a GET request and passes the signature\n# in the Authorization header.\nimport sys, os, base64, datetime, hashlib, hmac \nimport requests # pip install requests\nimport boto3\n\ncredentials = {\n \n 'lwa_refresh_token': 'whatever',\n 'lwa_client_secret': 'whatever',\n 'lwa_client_id': 'whatever',\n 'aws_secret_access_key': 'whatever',\n 'aws_access_key': 'whatever',\n 'role_arn': 'whatever:role/whatever'\n}\n\n\n# get Access Token and assign to 'x-amz-access-token'\nresponse = requests.post('https://api.amazon.com/auth/o2/token',\n headers={'Content-Type': 'application/x-www-form-urlencoded'},\n data={\n 'grant_type': 'refresh_token',\n 'refresh_token': credentials['lwa_refresh_token'],\n 'client_id': credentials['lwa_client_id'],\n 'client_secret': credentials['lwa_client_secret']\n }\n)\ncredentials['x-amz-access-token'] = response.json()['access_token']\n\n# get AWS STS Session Token and assign to 'x-amz-security-token'\nsts_client = boto3.client(\n 'sts',\n aws_access_key_id=credentials['aws_access_key'],\n aws_secret_access_key=credentials['aws_secret_access_key']\n)\n\nassumed_role_object=sts_client.assume_role(\n RoleArn=credentials['role_arn'],\n RoleSessionName=\"whatever role sesion name you got\"\n)\ncredentials['x-amz-security-token'] = assumed_role_object['Credentials']['SessionToken']\ncredentials['aws_access_key'] = assumed_role_object['Credentials']['AccessKeyId']\ncredentials['aws_secret_access_key'] = assumed_role_object['Credentials']['SecretAccessKey']\n\n# ************* REQUEST VALUES *************\nmethod = 'GET'\nservice = 'execute-api'\nhost = 'sandbox.sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sandbox.sellingpartnerapi-na.amazon.com/orders/v0/orders'\nrequest_parameters = 'CreatedAfter=TEST_CASE_200&MarketplaceIds=ATVPDKIKX0DER'\n\n# Key derivation functions. See:\n# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n# Read AWS access key from env. variables or configuration file. Best practice is NOT\n# to embed credentials in code.\naccess_key = credentials['aws_access_key']\n# No deberia de ser security-token, si no secret_access_key?¿\nsecret_key = credentials['aws_secret_access_key']\nif access_key is None or secret_key is None:\n print('No access key is available.')\n sys.exit()\n\n# Create a date for headers and the credential string\nt = datetime.datetime.utcnow()\namzdate = t.strftime('%Y%m%dT%H%M%SZ')\ndatestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n\n# ************* TASK 1: CREATE A CANONICAL REQUEST *************\n# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n# Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n# Step 2: Create canonical URI--the part of the URI from domain to query \n# string (use '/' if no path)\ncanonical_uri = '/orders/v0/orders' \n\n# Step 3: Create the canonical query string. In this example (a GET request),\n# request parameters are in the query string. Query string values must\n# be URL-encoded (space=%20). The parameters must be sorted by name.\n# For this example, the query string is pre-formatted in the request_parameters variable.\ncanonical_querystring = request_parameters\n\n# Step 4: Create the canonical headers and signed headers. Header names\n# must be trimmed and lowercase, and sorted in code point order from\n# low to high. Note that there is a trailing \\n.\ncanonical_headers = 'host:' + host + '\\n' + 'user-agent:' + 'Ladder data ingestion' + '\\n' + 'x-amz-access-token:' + credentials['x-amz-access-token'] + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + credentials['x-amz-security-token'] + '\\n'\n \n# Step 5: Create the list of signed headers. This lists the headers\n# in the canonical_headers list, delimited with \";\" and in alpha order.\n# Note: The request can include any headers; canonical_headers and\n# signed_headers lists those that you want to be included in the \n# hash of the request. \"Host\" and \"x-amz-date\" are always required.\nsigned_headers = 'host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token'\n\n# Step 6: Create payload hash (hash of the request body content). For GET\n# requests, the payload is an empty string (\"\").\npayload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n# Step 7: Combine elements to create canonical request\ncanonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\nprint(\"My Canonical String:\")\nprint(canonical_request+'\\n')\n\n# ************* TASK 2: CREATE THE STRING TO SIGN*************\n# Match the algorithm to the hashing algorithm you use, either SHA-1 or\n# SHA-256 (recommended)\nalgorithm = 'AWS4-HMAC-SHA256'\ncredential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\nstring_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\nprint(\"My String to Sign\")\nprint(string_to_sign+'\\n')\n\n# ************* TASK 3: CALCULATE THE SIGNATURE *************\n# Create the signing key using the function defined above.\nsigning_key = getSignatureKey(secret_key, datestamp, region, service)\n\n# Sign the string_to_sign using the signing_key\nsignature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n\n\n# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n# The signing information can be either in a query string value or in \n# a header named Authorization. This code shows how to use a header.\n# Create authorization header and add to request headers\nauthorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n\n# The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n# and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n# be included in the canonical_headers and signed_headers, as noted\n# earlier. Order here is not significant.\n# Python note: The 'host' header is added automatically by the Python 'requests' library.\nheaders = {\n 'authorization': authorization_header,\n 'host': host,\n 'user-agent': 'Ladder data ingestion',\n 'x-amz-access-token': credentials['x-amz-access-token'],\n 'x-amz-date': amzdate, \n 'x-amz-security-token': credentials['x-amz-security-token']\n}\n\n\n# ************* SEND THE REQUEST *************\nrequest_url = endpoint + '?' + canonical_querystring\n\nprint('\\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')\nprint('Request URL = ' + request_url)\nr = requests.get(request_url, headers=headers)\n\nprint('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\nprint('Response code: %d\\n' % r.status_code)\nprint(r.text)\n\n" }, { "answer_id": 74636735, "author": "Otro Fulano", "author_id": 6494882, "author_profile": "https://Stackoverflow.com/users/6494882", "pm_score": 1, "selected": false, "text": "import hashlib\nimport hmac\nimport logging\nfrom collections import OrderedDict\nfrom urllib.parse import urlencode\nimport defusedxml.ElementTree as ET\nfrom sdc_etl_libs.api_helpers.API import API\nimport sys, datetime, hashlib, hmac \nimport requests\nimport json\nfrom bs4 import BeautifulSoup\ndef get_session_token_from_xml(content):\n soup = BeautifulSoup(content, \"xml\")\n return soup.find('SessionToken').text, soup.find('AccessKeyId').text, soup.find('SecretAccessKey').text\n\ndef set_params(action_):\n\n logging.info(f\"Setting params according to action {action_}\")\n params = dict()\n if action_ == 'AssumeRole':\n params['Version'] = '2011-06-15'\n params['Action'] = action_\n params['RoleSessionName'] = <<ROLE NAME>>\n params['RoleArn'] = <<ROLE ARN>>\n params['DurationSeconds']='3600'\n elif action_ == 'orders':\n params['MarketplaceIds'] = <<MARKET PLACE>>\n params['LastUpdatedAfter'] = '2022-11-27T14:00:00Z'\n params['LastUpdatedBefore'] = '2022-11-27T16:00:00Z'\n else:\n raise Exception(\"Action is not implemented.\")\n return params\ndef _get_access_token(lwa_app_id, lwa_client_secret, refresh_token):\n url = \"https://api.amazon.com/auth/O2/token\"\n\n payload=f'client_id={lwa_app_id}&client_secret={lwa_client_secret}&refresh_token={refresh_token}&grant_type=refresh_token'\n headers = {\n 'Host': 'api.amazon.com',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n return response\ndef format_params_to_create_signature(params_to_format_):\n \"\"\"\n URL encodes the parameter name and values\n https://docs.developer.amazonservices.com/en_US/dev_guide/DG_QueryString.html\n :param params_to_format_: dict. Parameters that should be ordered in natural byte order\n and url encoded.\n :return: str.\n \"\"\"\n logging.info(\"Format params.\")\n params_in_order = OrderedDict(sorted(params_to_format_.items()))\n params_formatted = urlencode(params_in_order, doseq=True)\n return params_formatted\n\ndef sign(key, msg):\n \n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\ndef _get_signature_request(action, access_key, secret_key, service, host, region, endpoint, \nmethod: str = 'GET', access_token: str = None, security_token: str = None):\n \n # ************* REQUEST VALUES *************\n params = set_params(action)\n fparams = format_params_to_create_signature(params)\n request_parameters = fparams\n\n # Read AWS access key from env. variables or configuration file. Best practice is NOT\n # to embed credentials in code.\n if access_key is None or secret_key is None:\n raise Exception(\"Access key or secret key are not implemented.\")\n\n # Create a date for headers and the credential string\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ')\n datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n # ************* TASK 1: CREATE A CANONICAL REQUEST *************\n # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n # Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n # Step 2: Create canonical URI--the part of the URI from domain to query \n # string (use '/' if no path)\n if action == 'AssumeRole':\n canonical_uri = '/' \n else:\n canonical_uri = '/orders/v0/orders' \n\n # Step 3: Create the canonical query string. In this example (a GET request),\n # request parameters are in the query string. Query string values must\n # be URL-encoded (space=%20). The parameters must be sorted by name.\n # For this example, the query string is pre-formatted in the request_parameters variable.\n canonical_querystring = request_parameters\n\n # Step 4: Create the canonical headers and signed headers. Header names\n # must be trimmed and lowercase, and sorted in code point order from\n # low to high. Note that there is a trailing \\n.\n\n # Step 5: Create the list of signed headers. This lists the headers\n # in the canonical_headers list, delimited with \";\" and in alpha order.\n # Note: The request can include any headers; canonical_headers and\n # signed_headers lists those that you want to be included in the \n # hash of the request. \"Host\" and \"x-amz-date\" are always required.\n if action == 'AssumeRole':\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'\n\n signed_headers = 'host;x-amz-date'\n else:\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-access-token:' + \\\n access_token + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + \\\n security_token + '\\n'\n\n signed_headers = 'host;x-amz-access-token;x-amz-date;x-amz-security-token'\n \n\n # Step 6: Create payload hash (hash of the request body content). For GET\n # requests, the payload is an empty string (\"\").\n payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n # Step 7: Combine elements to create canonical request\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + \\\n signed_headers + '\\n' + payload_hash\n\n # ************* TASK 2: CREATE THE STRING TO SIGN*************\n # Match the algorithm to the hashing algorithm you use, either SHA-1 or\n # SHA-256 (recommended)\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + \\\n hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\n\n # ************* TASK 3: CALCULATE THE SIGNATURE *************\n # Create the signing key using the function defined above.\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n \n # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n # The signing information can be either in a query string value or in \n # a header named Authorization. This code shows how to use a header.\n # Create authorization header and add to request headers\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + \\\n 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n # The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n # and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n # be included in the canonical_headers and signed_headers, as noted\n # earlier. Order here is not significant.\n # Python note: The 'host' header is added automatically by the Python 'requests' library.\n if action == 'AssumeRole':\n headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}\n else:\n headers = {\n 'authorization': authorization_header,\n 'host': host,\n 'x-amz-access-token': access_token,\n 'x-amz-date': amzdate, \n 'x-amz-security-token': security_token\n }\n\n # ************* SEND THE REQUEST *************\n request_url = endpoint + '?' + canonical_querystring\n logging.info(f\"BEGIN REQUEST++++++++++++++++++++++++++++++++++++'\")\n logging.info(f\"Request URL = {request_url}\")\n r = requests.get(request_url, headers=headers)\n\n logging.info('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\n logging.info('Response code: %d\\n' % r.status_code)\n\n return r\n service = 'sts'\nhost = 'sts.amazonaws.com'\nregion = 'us-east-1'\nendpoint = 'https://sts.amazonaws.com'\nresponse = _get_signature_session('AssumeRole', access_key, secret_key, service, host, region, endpoint)\naccess_token = json.loads(_get_access_token(lwa_app_id, lwa_client_secret, refresh_token).content)['access_token']\ntmp_session_token_, tmp_access_key, tmp_secret_access_key = get_session_token_from_xml(response.content.decode('utf-8'))\n service = 'execute-api'\nhost = 'sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sellingpartnerapi-na.amazon.com/orders/v0/orders'\nresponse = _get_signature_session('orders', tmp_access_key, tmp_secret_access_key, service, host, region, endpoint,\n access_token = access_token, security_token = tmp_session_token_)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14839276/" ]
74,558,882
<p>I'm trying to run a php website with nginx using php8.1 and php8.1-fpm, in a Ubuntu 20.04 vps.</p> <p>phpinfo reports that the config file in use is: /etc/php/8.1/fpm/php.ini</p> <p>It also reports that allow_url_fopen is Off (both Local Value and Master Value). Examining /etc/php/8.1/fpm/php.ini shows:</p> <p><code>allow_url_fopen = On</code></p> <p>I suppose that's the default setting. But I need this value to reflect in phpinfo and I can't get that to work.</p> <p>I've tried changing the value, restarting nginx and fpm, changing it back and restarting again, but nothing works. Feels like phpinfo is getting its values elsewhere. I've checked all files in /etc/php/8.1/fpm/conf.d (the config folder reported by phpinfo) and there is no allow_url_fopen in any of those.</p> <p>How do I get allow_url_fopen to be On?</p>
[ { "answer_id": 74626058, "author": "ChalsBP", "author_id": 14839276, "author_profile": "https://Stackoverflow.com/users/14839276", "pm_score": 1, "selected": true, "text": "\n# AWS Version 4 signing example\n\n# EC2 API (DescribeRegions)\n\n# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n# This version makes a GET request and passes the signature\n# in the Authorization header.\nimport sys, os, base64, datetime, hashlib, hmac \nimport requests # pip install requests\nimport boto3\n\ncredentials = {\n \n 'lwa_refresh_token': 'whatever',\n 'lwa_client_secret': 'whatever',\n 'lwa_client_id': 'whatever',\n 'aws_secret_access_key': 'whatever',\n 'aws_access_key': 'whatever',\n 'role_arn': 'whatever:role/whatever'\n}\n\n\n# get Access Token and assign to 'x-amz-access-token'\nresponse = requests.post('https://api.amazon.com/auth/o2/token',\n headers={'Content-Type': 'application/x-www-form-urlencoded'},\n data={\n 'grant_type': 'refresh_token',\n 'refresh_token': credentials['lwa_refresh_token'],\n 'client_id': credentials['lwa_client_id'],\n 'client_secret': credentials['lwa_client_secret']\n }\n)\ncredentials['x-amz-access-token'] = response.json()['access_token']\n\n# get AWS STS Session Token and assign to 'x-amz-security-token'\nsts_client = boto3.client(\n 'sts',\n aws_access_key_id=credentials['aws_access_key'],\n aws_secret_access_key=credentials['aws_secret_access_key']\n)\n\nassumed_role_object=sts_client.assume_role(\n RoleArn=credentials['role_arn'],\n RoleSessionName=\"whatever role sesion name you got\"\n)\ncredentials['x-amz-security-token'] = assumed_role_object['Credentials']['SessionToken']\ncredentials['aws_access_key'] = assumed_role_object['Credentials']['AccessKeyId']\ncredentials['aws_secret_access_key'] = assumed_role_object['Credentials']['SecretAccessKey']\n\n# ************* REQUEST VALUES *************\nmethod = 'GET'\nservice = 'execute-api'\nhost = 'sandbox.sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sandbox.sellingpartnerapi-na.amazon.com/orders/v0/orders'\nrequest_parameters = 'CreatedAfter=TEST_CASE_200&MarketplaceIds=ATVPDKIKX0DER'\n\n# Key derivation functions. See:\n# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n# Read AWS access key from env. variables or configuration file. Best practice is NOT\n# to embed credentials in code.\naccess_key = credentials['aws_access_key']\n# No deberia de ser security-token, si no secret_access_key?¿\nsecret_key = credentials['aws_secret_access_key']\nif access_key is None or secret_key is None:\n print('No access key is available.')\n sys.exit()\n\n# Create a date for headers and the credential string\nt = datetime.datetime.utcnow()\namzdate = t.strftime('%Y%m%dT%H%M%SZ')\ndatestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n\n# ************* TASK 1: CREATE A CANONICAL REQUEST *************\n# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n# Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n# Step 2: Create canonical URI--the part of the URI from domain to query \n# string (use '/' if no path)\ncanonical_uri = '/orders/v0/orders' \n\n# Step 3: Create the canonical query string. In this example (a GET request),\n# request parameters are in the query string. Query string values must\n# be URL-encoded (space=%20). The parameters must be sorted by name.\n# For this example, the query string is pre-formatted in the request_parameters variable.\ncanonical_querystring = request_parameters\n\n# Step 4: Create the canonical headers and signed headers. Header names\n# must be trimmed and lowercase, and sorted in code point order from\n# low to high. Note that there is a trailing \\n.\ncanonical_headers = 'host:' + host + '\\n' + 'user-agent:' + 'Ladder data ingestion' + '\\n' + 'x-amz-access-token:' + credentials['x-amz-access-token'] + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + credentials['x-amz-security-token'] + '\\n'\n \n# Step 5: Create the list of signed headers. This lists the headers\n# in the canonical_headers list, delimited with \";\" and in alpha order.\n# Note: The request can include any headers; canonical_headers and\n# signed_headers lists those that you want to be included in the \n# hash of the request. \"Host\" and \"x-amz-date\" are always required.\nsigned_headers = 'host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token'\n\n# Step 6: Create payload hash (hash of the request body content). For GET\n# requests, the payload is an empty string (\"\").\npayload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n# Step 7: Combine elements to create canonical request\ncanonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\nprint(\"My Canonical String:\")\nprint(canonical_request+'\\n')\n\n# ************* TASK 2: CREATE THE STRING TO SIGN*************\n# Match the algorithm to the hashing algorithm you use, either SHA-1 or\n# SHA-256 (recommended)\nalgorithm = 'AWS4-HMAC-SHA256'\ncredential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\nstring_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\nprint(\"My String to Sign\")\nprint(string_to_sign+'\\n')\n\n# ************* TASK 3: CALCULATE THE SIGNATURE *************\n# Create the signing key using the function defined above.\nsigning_key = getSignatureKey(secret_key, datestamp, region, service)\n\n# Sign the string_to_sign using the signing_key\nsignature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n\n\n# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n# The signing information can be either in a query string value or in \n# a header named Authorization. This code shows how to use a header.\n# Create authorization header and add to request headers\nauthorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n\n# The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n# and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n# be included in the canonical_headers and signed_headers, as noted\n# earlier. Order here is not significant.\n# Python note: The 'host' header is added automatically by the Python 'requests' library.\nheaders = {\n 'authorization': authorization_header,\n 'host': host,\n 'user-agent': 'Ladder data ingestion',\n 'x-amz-access-token': credentials['x-amz-access-token'],\n 'x-amz-date': amzdate, \n 'x-amz-security-token': credentials['x-amz-security-token']\n}\n\n\n# ************* SEND THE REQUEST *************\nrequest_url = endpoint + '?' + canonical_querystring\n\nprint('\\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')\nprint('Request URL = ' + request_url)\nr = requests.get(request_url, headers=headers)\n\nprint('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\nprint('Response code: %d\\n' % r.status_code)\nprint(r.text)\n\n" }, { "answer_id": 74636735, "author": "Otro Fulano", "author_id": 6494882, "author_profile": "https://Stackoverflow.com/users/6494882", "pm_score": 1, "selected": false, "text": "import hashlib\nimport hmac\nimport logging\nfrom collections import OrderedDict\nfrom urllib.parse import urlencode\nimport defusedxml.ElementTree as ET\nfrom sdc_etl_libs.api_helpers.API import API\nimport sys, datetime, hashlib, hmac \nimport requests\nimport json\nfrom bs4 import BeautifulSoup\ndef get_session_token_from_xml(content):\n soup = BeautifulSoup(content, \"xml\")\n return soup.find('SessionToken').text, soup.find('AccessKeyId').text, soup.find('SecretAccessKey').text\n\ndef set_params(action_):\n\n logging.info(f\"Setting params according to action {action_}\")\n params = dict()\n if action_ == 'AssumeRole':\n params['Version'] = '2011-06-15'\n params['Action'] = action_\n params['RoleSessionName'] = <<ROLE NAME>>\n params['RoleArn'] = <<ROLE ARN>>\n params['DurationSeconds']='3600'\n elif action_ == 'orders':\n params['MarketplaceIds'] = <<MARKET PLACE>>\n params['LastUpdatedAfter'] = '2022-11-27T14:00:00Z'\n params['LastUpdatedBefore'] = '2022-11-27T16:00:00Z'\n else:\n raise Exception(\"Action is not implemented.\")\n return params\ndef _get_access_token(lwa_app_id, lwa_client_secret, refresh_token):\n url = \"https://api.amazon.com/auth/O2/token\"\n\n payload=f'client_id={lwa_app_id}&client_secret={lwa_client_secret}&refresh_token={refresh_token}&grant_type=refresh_token'\n headers = {\n 'Host': 'api.amazon.com',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n return response\ndef format_params_to_create_signature(params_to_format_):\n \"\"\"\n URL encodes the parameter name and values\n https://docs.developer.amazonservices.com/en_US/dev_guide/DG_QueryString.html\n :param params_to_format_: dict. Parameters that should be ordered in natural byte order\n and url encoded.\n :return: str.\n \"\"\"\n logging.info(\"Format params.\")\n params_in_order = OrderedDict(sorted(params_to_format_.items()))\n params_formatted = urlencode(params_in_order, doseq=True)\n return params_formatted\n\ndef sign(key, msg):\n \n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\ndef _get_signature_request(action, access_key, secret_key, service, host, region, endpoint, \nmethod: str = 'GET', access_token: str = None, security_token: str = None):\n \n # ************* REQUEST VALUES *************\n params = set_params(action)\n fparams = format_params_to_create_signature(params)\n request_parameters = fparams\n\n # Read AWS access key from env. variables or configuration file. Best practice is NOT\n # to embed credentials in code.\n if access_key is None or secret_key is None:\n raise Exception(\"Access key or secret key are not implemented.\")\n\n # Create a date for headers and the credential string\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ')\n datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n # ************* TASK 1: CREATE A CANONICAL REQUEST *************\n # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n # Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n # Step 2: Create canonical URI--the part of the URI from domain to query \n # string (use '/' if no path)\n if action == 'AssumeRole':\n canonical_uri = '/' \n else:\n canonical_uri = '/orders/v0/orders' \n\n # Step 3: Create the canonical query string. In this example (a GET request),\n # request parameters are in the query string. Query string values must\n # be URL-encoded (space=%20). The parameters must be sorted by name.\n # For this example, the query string is pre-formatted in the request_parameters variable.\n canonical_querystring = request_parameters\n\n # Step 4: Create the canonical headers and signed headers. Header names\n # must be trimmed and lowercase, and sorted in code point order from\n # low to high. Note that there is a trailing \\n.\n\n # Step 5: Create the list of signed headers. This lists the headers\n # in the canonical_headers list, delimited with \";\" and in alpha order.\n # Note: The request can include any headers; canonical_headers and\n # signed_headers lists those that you want to be included in the \n # hash of the request. \"Host\" and \"x-amz-date\" are always required.\n if action == 'AssumeRole':\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'\n\n signed_headers = 'host;x-amz-date'\n else:\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-access-token:' + \\\n access_token + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + \\\n security_token + '\\n'\n\n signed_headers = 'host;x-amz-access-token;x-amz-date;x-amz-security-token'\n \n\n # Step 6: Create payload hash (hash of the request body content). For GET\n # requests, the payload is an empty string (\"\").\n payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n # Step 7: Combine elements to create canonical request\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + \\\n signed_headers + '\\n' + payload_hash\n\n # ************* TASK 2: CREATE THE STRING TO SIGN*************\n # Match the algorithm to the hashing algorithm you use, either SHA-1 or\n # SHA-256 (recommended)\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + \\\n hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\n\n # ************* TASK 3: CALCULATE THE SIGNATURE *************\n # Create the signing key using the function defined above.\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n \n # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n # The signing information can be either in a query string value or in \n # a header named Authorization. This code shows how to use a header.\n # Create authorization header and add to request headers\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + \\\n 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n # The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n # and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n # be included in the canonical_headers and signed_headers, as noted\n # earlier. Order here is not significant.\n # Python note: The 'host' header is added automatically by the Python 'requests' library.\n if action == 'AssumeRole':\n headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}\n else:\n headers = {\n 'authorization': authorization_header,\n 'host': host,\n 'x-amz-access-token': access_token,\n 'x-amz-date': amzdate, \n 'x-amz-security-token': security_token\n }\n\n # ************* SEND THE REQUEST *************\n request_url = endpoint + '?' + canonical_querystring\n logging.info(f\"BEGIN REQUEST++++++++++++++++++++++++++++++++++++'\")\n logging.info(f\"Request URL = {request_url}\")\n r = requests.get(request_url, headers=headers)\n\n logging.info('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\n logging.info('Response code: %d\\n' % r.status_code)\n\n return r\n service = 'sts'\nhost = 'sts.amazonaws.com'\nregion = 'us-east-1'\nendpoint = 'https://sts.amazonaws.com'\nresponse = _get_signature_session('AssumeRole', access_key, secret_key, service, host, region, endpoint)\naccess_token = json.loads(_get_access_token(lwa_app_id, lwa_client_secret, refresh_token).content)['access_token']\ntmp_session_token_, tmp_access_key, tmp_secret_access_key = get_session_token_from_xml(response.content.decode('utf-8'))\n service = 'execute-api'\nhost = 'sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sellingpartnerapi-na.amazon.com/orders/v0/orders'\nresponse = _get_signature_session('orders', tmp_access_key, tmp_secret_access_key, service, host, region, endpoint,\n access_token = access_token, security_token = tmp_session_token_)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744811/" ]
74,558,916
<p>I have run my Collection. I have Exported results &quot;***API.postman_test_run.json&quot; file using Export Results option into my local folder:</p> <p><a href="https://i.stack.imgur.com/2w9fG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2w9fG.png" alt="enter image description here" /></a></p> <p>I closed the Runner tab (Run Summary) on Postman. And then I tried to open (to Import) this json file somewhere in Postman in order to view these results again and I do not see how I can do that. My question is - how I can view exported results in Postman? Is it possible at all or I need to open results in some other application like Visual Studio Code?</p> <p>Here is an update: I have found the icon Runner in the right bottom part of my Postman desktop.</p> <p><a href="https://i.stack.imgur.com/uyFzI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uyFzI.png" alt="enter image description here" /></a></p> <p>I clicked on it and got an interface to import the previous collection runs: <a href="https://i.stack.imgur.com/KHjHA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KHjHA.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/ORwbx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ORwbx.png" alt="enter image description here" /></a></p> <p>However, when I click on button Import I am getting an error: Failed to import collection run.</p> <p><a href="https://i.stack.imgur.com/ACvZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ACvZq.png" alt="enter image description here" /></a></p> <p>What could be the reason of it?</p>
[ { "answer_id": 74626058, "author": "ChalsBP", "author_id": 14839276, "author_profile": "https://Stackoverflow.com/users/14839276", "pm_score": 1, "selected": true, "text": "\n# AWS Version 4 signing example\n\n# EC2 API (DescribeRegions)\n\n# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n# This version makes a GET request and passes the signature\n# in the Authorization header.\nimport sys, os, base64, datetime, hashlib, hmac \nimport requests # pip install requests\nimport boto3\n\ncredentials = {\n \n 'lwa_refresh_token': 'whatever',\n 'lwa_client_secret': 'whatever',\n 'lwa_client_id': 'whatever',\n 'aws_secret_access_key': 'whatever',\n 'aws_access_key': 'whatever',\n 'role_arn': 'whatever:role/whatever'\n}\n\n\n# get Access Token and assign to 'x-amz-access-token'\nresponse = requests.post('https://api.amazon.com/auth/o2/token',\n headers={'Content-Type': 'application/x-www-form-urlencoded'},\n data={\n 'grant_type': 'refresh_token',\n 'refresh_token': credentials['lwa_refresh_token'],\n 'client_id': credentials['lwa_client_id'],\n 'client_secret': credentials['lwa_client_secret']\n }\n)\ncredentials['x-amz-access-token'] = response.json()['access_token']\n\n# get AWS STS Session Token and assign to 'x-amz-security-token'\nsts_client = boto3.client(\n 'sts',\n aws_access_key_id=credentials['aws_access_key'],\n aws_secret_access_key=credentials['aws_secret_access_key']\n)\n\nassumed_role_object=sts_client.assume_role(\n RoleArn=credentials['role_arn'],\n RoleSessionName=\"whatever role sesion name you got\"\n)\ncredentials['x-amz-security-token'] = assumed_role_object['Credentials']['SessionToken']\ncredentials['aws_access_key'] = assumed_role_object['Credentials']['AccessKeyId']\ncredentials['aws_secret_access_key'] = assumed_role_object['Credentials']['SecretAccessKey']\n\n# ************* REQUEST VALUES *************\nmethod = 'GET'\nservice = 'execute-api'\nhost = 'sandbox.sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sandbox.sellingpartnerapi-na.amazon.com/orders/v0/orders'\nrequest_parameters = 'CreatedAfter=TEST_CASE_200&MarketplaceIds=ATVPDKIKX0DER'\n\n# Key derivation functions. See:\n# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n# Read AWS access key from env. variables or configuration file. Best practice is NOT\n# to embed credentials in code.\naccess_key = credentials['aws_access_key']\n# No deberia de ser security-token, si no secret_access_key?¿\nsecret_key = credentials['aws_secret_access_key']\nif access_key is None or secret_key is None:\n print('No access key is available.')\n sys.exit()\n\n# Create a date for headers and the credential string\nt = datetime.datetime.utcnow()\namzdate = t.strftime('%Y%m%dT%H%M%SZ')\ndatestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n\n# ************* TASK 1: CREATE A CANONICAL REQUEST *************\n# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n# Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n# Step 2: Create canonical URI--the part of the URI from domain to query \n# string (use '/' if no path)\ncanonical_uri = '/orders/v0/orders' \n\n# Step 3: Create the canonical query string. In this example (a GET request),\n# request parameters are in the query string. Query string values must\n# be URL-encoded (space=%20). The parameters must be sorted by name.\n# For this example, the query string is pre-formatted in the request_parameters variable.\ncanonical_querystring = request_parameters\n\n# Step 4: Create the canonical headers and signed headers. Header names\n# must be trimmed and lowercase, and sorted in code point order from\n# low to high. Note that there is a trailing \\n.\ncanonical_headers = 'host:' + host + '\\n' + 'user-agent:' + 'Ladder data ingestion' + '\\n' + 'x-amz-access-token:' + credentials['x-amz-access-token'] + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + credentials['x-amz-security-token'] + '\\n'\n \n# Step 5: Create the list of signed headers. This lists the headers\n# in the canonical_headers list, delimited with \";\" and in alpha order.\n# Note: The request can include any headers; canonical_headers and\n# signed_headers lists those that you want to be included in the \n# hash of the request. \"Host\" and \"x-amz-date\" are always required.\nsigned_headers = 'host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token'\n\n# Step 6: Create payload hash (hash of the request body content). For GET\n# requests, the payload is an empty string (\"\").\npayload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n# Step 7: Combine elements to create canonical request\ncanonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\nprint(\"My Canonical String:\")\nprint(canonical_request+'\\n')\n\n# ************* TASK 2: CREATE THE STRING TO SIGN*************\n# Match the algorithm to the hashing algorithm you use, either SHA-1 or\n# SHA-256 (recommended)\nalgorithm = 'AWS4-HMAC-SHA256'\ncredential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\nstring_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\nprint(\"My String to Sign\")\nprint(string_to_sign+'\\n')\n\n# ************* TASK 3: CALCULATE THE SIGNATURE *************\n# Create the signing key using the function defined above.\nsigning_key = getSignatureKey(secret_key, datestamp, region, service)\n\n# Sign the string_to_sign using the signing_key\nsignature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n\n\n# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n# The signing information can be either in a query string value or in \n# a header named Authorization. This code shows how to use a header.\n# Create authorization header and add to request headers\nauthorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n\n# The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n# and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n# be included in the canonical_headers and signed_headers, as noted\n# earlier. Order here is not significant.\n# Python note: The 'host' header is added automatically by the Python 'requests' library.\nheaders = {\n 'authorization': authorization_header,\n 'host': host,\n 'user-agent': 'Ladder data ingestion',\n 'x-amz-access-token': credentials['x-amz-access-token'],\n 'x-amz-date': amzdate, \n 'x-amz-security-token': credentials['x-amz-security-token']\n}\n\n\n# ************* SEND THE REQUEST *************\nrequest_url = endpoint + '?' + canonical_querystring\n\nprint('\\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')\nprint('Request URL = ' + request_url)\nr = requests.get(request_url, headers=headers)\n\nprint('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\nprint('Response code: %d\\n' % r.status_code)\nprint(r.text)\n\n" }, { "answer_id": 74636735, "author": "Otro Fulano", "author_id": 6494882, "author_profile": "https://Stackoverflow.com/users/6494882", "pm_score": 1, "selected": false, "text": "import hashlib\nimport hmac\nimport logging\nfrom collections import OrderedDict\nfrom urllib.parse import urlencode\nimport defusedxml.ElementTree as ET\nfrom sdc_etl_libs.api_helpers.API import API\nimport sys, datetime, hashlib, hmac \nimport requests\nimport json\nfrom bs4 import BeautifulSoup\ndef get_session_token_from_xml(content):\n soup = BeautifulSoup(content, \"xml\")\n return soup.find('SessionToken').text, soup.find('AccessKeyId').text, soup.find('SecretAccessKey').text\n\ndef set_params(action_):\n\n logging.info(f\"Setting params according to action {action_}\")\n params = dict()\n if action_ == 'AssumeRole':\n params['Version'] = '2011-06-15'\n params['Action'] = action_\n params['RoleSessionName'] = <<ROLE NAME>>\n params['RoleArn'] = <<ROLE ARN>>\n params['DurationSeconds']='3600'\n elif action_ == 'orders':\n params['MarketplaceIds'] = <<MARKET PLACE>>\n params['LastUpdatedAfter'] = '2022-11-27T14:00:00Z'\n params['LastUpdatedBefore'] = '2022-11-27T16:00:00Z'\n else:\n raise Exception(\"Action is not implemented.\")\n return params\ndef _get_access_token(lwa_app_id, lwa_client_secret, refresh_token):\n url = \"https://api.amazon.com/auth/O2/token\"\n\n payload=f'client_id={lwa_app_id}&client_secret={lwa_client_secret}&refresh_token={refresh_token}&grant_type=refresh_token'\n headers = {\n 'Host': 'api.amazon.com',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n return response\ndef format_params_to_create_signature(params_to_format_):\n \"\"\"\n URL encodes the parameter name and values\n https://docs.developer.amazonservices.com/en_US/dev_guide/DG_QueryString.html\n :param params_to_format_: dict. Parameters that should be ordered in natural byte order\n and url encoded.\n :return: str.\n \"\"\"\n logging.info(\"Format params.\")\n params_in_order = OrderedDict(sorted(params_to_format_.items()))\n params_formatted = urlencode(params_in_order, doseq=True)\n return params_formatted\n\ndef sign(key, msg):\n \n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\ndef _get_signature_request(action, access_key, secret_key, service, host, region, endpoint, \nmethod: str = 'GET', access_token: str = None, security_token: str = None):\n \n # ************* REQUEST VALUES *************\n params = set_params(action)\n fparams = format_params_to_create_signature(params)\n request_parameters = fparams\n\n # Read AWS access key from env. variables or configuration file. Best practice is NOT\n # to embed credentials in code.\n if access_key is None or secret_key is None:\n raise Exception(\"Access key or secret key are not implemented.\")\n\n # Create a date for headers and the credential string\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ')\n datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n # ************* TASK 1: CREATE A CANONICAL REQUEST *************\n # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n # Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n # Step 2: Create canonical URI--the part of the URI from domain to query \n # string (use '/' if no path)\n if action == 'AssumeRole':\n canonical_uri = '/' \n else:\n canonical_uri = '/orders/v0/orders' \n\n # Step 3: Create the canonical query string. In this example (a GET request),\n # request parameters are in the query string. Query string values must\n # be URL-encoded (space=%20). The parameters must be sorted by name.\n # For this example, the query string is pre-formatted in the request_parameters variable.\n canonical_querystring = request_parameters\n\n # Step 4: Create the canonical headers and signed headers. Header names\n # must be trimmed and lowercase, and sorted in code point order from\n # low to high. Note that there is a trailing \\n.\n\n # Step 5: Create the list of signed headers. This lists the headers\n # in the canonical_headers list, delimited with \";\" and in alpha order.\n # Note: The request can include any headers; canonical_headers and\n # signed_headers lists those that you want to be included in the \n # hash of the request. \"Host\" and \"x-amz-date\" are always required.\n if action == 'AssumeRole':\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'\n\n signed_headers = 'host;x-amz-date'\n else:\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-access-token:' + \\\n access_token + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + \\\n security_token + '\\n'\n\n signed_headers = 'host;x-amz-access-token;x-amz-date;x-amz-security-token'\n \n\n # Step 6: Create payload hash (hash of the request body content). For GET\n # requests, the payload is an empty string (\"\").\n payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n # Step 7: Combine elements to create canonical request\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + \\\n signed_headers + '\\n' + payload_hash\n\n # ************* TASK 2: CREATE THE STRING TO SIGN*************\n # Match the algorithm to the hashing algorithm you use, either SHA-1 or\n # SHA-256 (recommended)\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + \\\n hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\n\n # ************* TASK 3: CALCULATE THE SIGNATURE *************\n # Create the signing key using the function defined above.\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n \n # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n # The signing information can be either in a query string value or in \n # a header named Authorization. This code shows how to use a header.\n # Create authorization header and add to request headers\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + \\\n 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n # The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n # and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n # be included in the canonical_headers and signed_headers, as noted\n # earlier. Order here is not significant.\n # Python note: The 'host' header is added automatically by the Python 'requests' library.\n if action == 'AssumeRole':\n headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}\n else:\n headers = {\n 'authorization': authorization_header,\n 'host': host,\n 'x-amz-access-token': access_token,\n 'x-amz-date': amzdate, \n 'x-amz-security-token': security_token\n }\n\n # ************* SEND THE REQUEST *************\n request_url = endpoint + '?' + canonical_querystring\n logging.info(f\"BEGIN REQUEST++++++++++++++++++++++++++++++++++++'\")\n logging.info(f\"Request URL = {request_url}\")\n r = requests.get(request_url, headers=headers)\n\n logging.info('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\n logging.info('Response code: %d\\n' % r.status_code)\n\n return r\n service = 'sts'\nhost = 'sts.amazonaws.com'\nregion = 'us-east-1'\nendpoint = 'https://sts.amazonaws.com'\nresponse = _get_signature_session('AssumeRole', access_key, secret_key, service, host, region, endpoint)\naccess_token = json.loads(_get_access_token(lwa_app_id, lwa_client_secret, refresh_token).content)['access_token']\ntmp_session_token_, tmp_access_key, tmp_secret_access_key = get_session_token_from_xml(response.content.decode('utf-8'))\n service = 'execute-api'\nhost = 'sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sellingpartnerapi-na.amazon.com/orders/v0/orders'\nresponse = _get_signature_session('orders', tmp_access_key, tmp_secret_access_key, service, host, region, endpoint,\n access_token = access_token, security_token = tmp_session_token_)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17004692/" ]
74,558,928
<p>Google Play again rejected my app because I'm apparently using REQUEST_INSTALL_PACKAGES permission in my app. I never had this permission ever, I never had this issue before.</p> <p>I checked merged manifest to find that kind of permission. There is none.</p> <p>I've added</p> <pre><code>&lt;uses-permission android:name=&quot;android.permission.REQUEST_INSTALL_PACKAGES&quot; tools:node=&quot;remove&quot;/&gt; </code></pre> <p>tag into my AndroidManifest.xml to be certain that my App is not using this kind of permission EVER. Even Merged Manifest is not containing that permission and at the bottom of the Merged Manifest there is Android Studio warning that I'm removing something that is not even present in my app:</p> <pre><code>Warning uses-permission#android.permission.REQUEST_INSTALL_PACKAGES was tagged at AndroidManifest.xml:25 to remove other declarations but no other declaration present MyApp.app main manifest (this file), line 24 </code></pre> <p>So either I'm missing something or their app validation is broken and Google is false-flagging my app validation for some unknown reason.</p> <p>There has to be some serious issues with their validation methods past 2 weeks because amount of issues I've got with my app is unacceptable. App has same permissions and using same libraries and their version for past 2 years and I never had any issues like this before.</p> <p>And I'm not sure what else I can do to get my app validated and accepted again.</p>
[ { "answer_id": 74626058, "author": "ChalsBP", "author_id": 14839276, "author_profile": "https://Stackoverflow.com/users/14839276", "pm_score": 1, "selected": true, "text": "\n# AWS Version 4 signing example\n\n# EC2 API (DescribeRegions)\n\n# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n# This version makes a GET request and passes the signature\n# in the Authorization header.\nimport sys, os, base64, datetime, hashlib, hmac \nimport requests # pip install requests\nimport boto3\n\ncredentials = {\n \n 'lwa_refresh_token': 'whatever',\n 'lwa_client_secret': 'whatever',\n 'lwa_client_id': 'whatever',\n 'aws_secret_access_key': 'whatever',\n 'aws_access_key': 'whatever',\n 'role_arn': 'whatever:role/whatever'\n}\n\n\n# get Access Token and assign to 'x-amz-access-token'\nresponse = requests.post('https://api.amazon.com/auth/o2/token',\n headers={'Content-Type': 'application/x-www-form-urlencoded'},\n data={\n 'grant_type': 'refresh_token',\n 'refresh_token': credentials['lwa_refresh_token'],\n 'client_id': credentials['lwa_client_id'],\n 'client_secret': credentials['lwa_client_secret']\n }\n)\ncredentials['x-amz-access-token'] = response.json()['access_token']\n\n# get AWS STS Session Token and assign to 'x-amz-security-token'\nsts_client = boto3.client(\n 'sts',\n aws_access_key_id=credentials['aws_access_key'],\n aws_secret_access_key=credentials['aws_secret_access_key']\n)\n\nassumed_role_object=sts_client.assume_role(\n RoleArn=credentials['role_arn'],\n RoleSessionName=\"whatever role sesion name you got\"\n)\ncredentials['x-amz-security-token'] = assumed_role_object['Credentials']['SessionToken']\ncredentials['aws_access_key'] = assumed_role_object['Credentials']['AccessKeyId']\ncredentials['aws_secret_access_key'] = assumed_role_object['Credentials']['SecretAccessKey']\n\n# ************* REQUEST VALUES *************\nmethod = 'GET'\nservice = 'execute-api'\nhost = 'sandbox.sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sandbox.sellingpartnerapi-na.amazon.com/orders/v0/orders'\nrequest_parameters = 'CreatedAfter=TEST_CASE_200&MarketplaceIds=ATVPDKIKX0DER'\n\n# Key derivation functions. See:\n# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n# Read AWS access key from env. variables or configuration file. Best practice is NOT\n# to embed credentials in code.\naccess_key = credentials['aws_access_key']\n# No deberia de ser security-token, si no secret_access_key?¿\nsecret_key = credentials['aws_secret_access_key']\nif access_key is None or secret_key is None:\n print('No access key is available.')\n sys.exit()\n\n# Create a date for headers and the credential string\nt = datetime.datetime.utcnow()\namzdate = t.strftime('%Y%m%dT%H%M%SZ')\ndatestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n\n# ************* TASK 1: CREATE A CANONICAL REQUEST *************\n# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n# Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n# Step 2: Create canonical URI--the part of the URI from domain to query \n# string (use '/' if no path)\ncanonical_uri = '/orders/v0/orders' \n\n# Step 3: Create the canonical query string. In this example (a GET request),\n# request parameters are in the query string. Query string values must\n# be URL-encoded (space=%20). The parameters must be sorted by name.\n# For this example, the query string is pre-formatted in the request_parameters variable.\ncanonical_querystring = request_parameters\n\n# Step 4: Create the canonical headers and signed headers. Header names\n# must be trimmed and lowercase, and sorted in code point order from\n# low to high. Note that there is a trailing \\n.\ncanonical_headers = 'host:' + host + '\\n' + 'user-agent:' + 'Ladder data ingestion' + '\\n' + 'x-amz-access-token:' + credentials['x-amz-access-token'] + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + credentials['x-amz-security-token'] + '\\n'\n \n# Step 5: Create the list of signed headers. This lists the headers\n# in the canonical_headers list, delimited with \";\" and in alpha order.\n# Note: The request can include any headers; canonical_headers and\n# signed_headers lists those that you want to be included in the \n# hash of the request. \"Host\" and \"x-amz-date\" are always required.\nsigned_headers = 'host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token'\n\n# Step 6: Create payload hash (hash of the request body content). For GET\n# requests, the payload is an empty string (\"\").\npayload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n# Step 7: Combine elements to create canonical request\ncanonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\nprint(\"My Canonical String:\")\nprint(canonical_request+'\\n')\n\n# ************* TASK 2: CREATE THE STRING TO SIGN*************\n# Match the algorithm to the hashing algorithm you use, either SHA-1 or\n# SHA-256 (recommended)\nalgorithm = 'AWS4-HMAC-SHA256'\ncredential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\nstring_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\nprint(\"My String to Sign\")\nprint(string_to_sign+'\\n')\n\n# ************* TASK 3: CALCULATE THE SIGNATURE *************\n# Create the signing key using the function defined above.\nsigning_key = getSignatureKey(secret_key, datestamp, region, service)\n\n# Sign the string_to_sign using the signing_key\nsignature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n\n\n# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n# The signing information can be either in a query string value or in \n# a header named Authorization. This code shows how to use a header.\n# Create authorization header and add to request headers\nauthorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n\n# The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n# and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n# be included in the canonical_headers and signed_headers, as noted\n# earlier. Order here is not significant.\n# Python note: The 'host' header is added automatically by the Python 'requests' library.\nheaders = {\n 'authorization': authorization_header,\n 'host': host,\n 'user-agent': 'Ladder data ingestion',\n 'x-amz-access-token': credentials['x-amz-access-token'],\n 'x-amz-date': amzdate, \n 'x-amz-security-token': credentials['x-amz-security-token']\n}\n\n\n# ************* SEND THE REQUEST *************\nrequest_url = endpoint + '?' + canonical_querystring\n\nprint('\\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')\nprint('Request URL = ' + request_url)\nr = requests.get(request_url, headers=headers)\n\nprint('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\nprint('Response code: %d\\n' % r.status_code)\nprint(r.text)\n\n" }, { "answer_id": 74636735, "author": "Otro Fulano", "author_id": 6494882, "author_profile": "https://Stackoverflow.com/users/6494882", "pm_score": 1, "selected": false, "text": "import hashlib\nimport hmac\nimport logging\nfrom collections import OrderedDict\nfrom urllib.parse import urlencode\nimport defusedxml.ElementTree as ET\nfrom sdc_etl_libs.api_helpers.API import API\nimport sys, datetime, hashlib, hmac \nimport requests\nimport json\nfrom bs4 import BeautifulSoup\ndef get_session_token_from_xml(content):\n soup = BeautifulSoup(content, \"xml\")\n return soup.find('SessionToken').text, soup.find('AccessKeyId').text, soup.find('SecretAccessKey').text\n\ndef set_params(action_):\n\n logging.info(f\"Setting params according to action {action_}\")\n params = dict()\n if action_ == 'AssumeRole':\n params['Version'] = '2011-06-15'\n params['Action'] = action_\n params['RoleSessionName'] = <<ROLE NAME>>\n params['RoleArn'] = <<ROLE ARN>>\n params['DurationSeconds']='3600'\n elif action_ == 'orders':\n params['MarketplaceIds'] = <<MARKET PLACE>>\n params['LastUpdatedAfter'] = '2022-11-27T14:00:00Z'\n params['LastUpdatedBefore'] = '2022-11-27T16:00:00Z'\n else:\n raise Exception(\"Action is not implemented.\")\n return params\ndef _get_access_token(lwa_app_id, lwa_client_secret, refresh_token):\n url = \"https://api.amazon.com/auth/O2/token\"\n\n payload=f'client_id={lwa_app_id}&client_secret={lwa_client_secret}&refresh_token={refresh_token}&grant_type=refresh_token'\n headers = {\n 'Host': 'api.amazon.com',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n return response\ndef format_params_to_create_signature(params_to_format_):\n \"\"\"\n URL encodes the parameter name and values\n https://docs.developer.amazonservices.com/en_US/dev_guide/DG_QueryString.html\n :param params_to_format_: dict. Parameters that should be ordered in natural byte order\n and url encoded.\n :return: str.\n \"\"\"\n logging.info(\"Format params.\")\n params_in_order = OrderedDict(sorted(params_to_format_.items()))\n params_formatted = urlencode(params_in_order, doseq=True)\n return params_formatted\n\ndef sign(key, msg):\n \n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\ndef _get_signature_request(action, access_key, secret_key, service, host, region, endpoint, \nmethod: str = 'GET', access_token: str = None, security_token: str = None):\n \n # ************* REQUEST VALUES *************\n params = set_params(action)\n fparams = format_params_to_create_signature(params)\n request_parameters = fparams\n\n # Read AWS access key from env. variables or configuration file. Best practice is NOT\n # to embed credentials in code.\n if access_key is None or secret_key is None:\n raise Exception(\"Access key or secret key are not implemented.\")\n\n # Create a date for headers and the credential string\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ')\n datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n # ************* TASK 1: CREATE A CANONICAL REQUEST *************\n # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n # Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n # Step 2: Create canonical URI--the part of the URI from domain to query \n # string (use '/' if no path)\n if action == 'AssumeRole':\n canonical_uri = '/' \n else:\n canonical_uri = '/orders/v0/orders' \n\n # Step 3: Create the canonical query string. In this example (a GET request),\n # request parameters are in the query string. Query string values must\n # be URL-encoded (space=%20). The parameters must be sorted by name.\n # For this example, the query string is pre-formatted in the request_parameters variable.\n canonical_querystring = request_parameters\n\n # Step 4: Create the canonical headers and signed headers. Header names\n # must be trimmed and lowercase, and sorted in code point order from\n # low to high. Note that there is a trailing \\n.\n\n # Step 5: Create the list of signed headers. This lists the headers\n # in the canonical_headers list, delimited with \";\" and in alpha order.\n # Note: The request can include any headers; canonical_headers and\n # signed_headers lists those that you want to be included in the \n # hash of the request. \"Host\" and \"x-amz-date\" are always required.\n if action == 'AssumeRole':\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'\n\n signed_headers = 'host;x-amz-date'\n else:\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-access-token:' + \\\n access_token + '\\n' + 'x-amz-date:' + amzdate + '\\n' + 'x-amz-security-token:' + \\\n security_token + '\\n'\n\n signed_headers = 'host;x-amz-access-token;x-amz-date;x-amz-security-token'\n \n\n # Step 6: Create payload hash (hash of the request body content). For GET\n # requests, the payload is an empty string (\"\").\n payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n # Step 7: Combine elements to create canonical request\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + \\\n signed_headers + '\\n' + payload_hash\n\n # ************* TASK 2: CREATE THE STRING TO SIGN*************\n # Match the algorithm to the hashing algorithm you use, either SHA-1 or\n # SHA-256 (recommended)\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + \\\n hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\n\n # ************* TASK 3: CALCULATE THE SIGNATURE *************\n # Create the signing key using the function defined above.\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n \n # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n # The signing information can be either in a query string value or in \n # a header named Authorization. This code shows how to use a header.\n # Create authorization header and add to request headers\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + \\\n 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n # The request can include any headers, but MUST include \"host\", \"x-amz-date\", \n # and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n # be included in the canonical_headers and signed_headers, as noted\n # earlier. Order here is not significant.\n # Python note: The 'host' header is added automatically by the Python 'requests' library.\n if action == 'AssumeRole':\n headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}\n else:\n headers = {\n 'authorization': authorization_header,\n 'host': host,\n 'x-amz-access-token': access_token,\n 'x-amz-date': amzdate, \n 'x-amz-security-token': security_token\n }\n\n # ************* SEND THE REQUEST *************\n request_url = endpoint + '?' + canonical_querystring\n logging.info(f\"BEGIN REQUEST++++++++++++++++++++++++++++++++++++'\")\n logging.info(f\"Request URL = {request_url}\")\n r = requests.get(request_url, headers=headers)\n\n logging.info('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\n logging.info('Response code: %d\\n' % r.status_code)\n\n return r\n service = 'sts'\nhost = 'sts.amazonaws.com'\nregion = 'us-east-1'\nendpoint = 'https://sts.amazonaws.com'\nresponse = _get_signature_session('AssumeRole', access_key, secret_key, service, host, region, endpoint)\naccess_token = json.loads(_get_access_token(lwa_app_id, lwa_client_secret, refresh_token).content)['access_token']\ntmp_session_token_, tmp_access_key, tmp_secret_access_key = get_session_token_from_xml(response.content.decode('utf-8'))\n service = 'execute-api'\nhost = 'sellingpartnerapi-na.amazon.com'\nregion = 'us-east-1'\nendpoint = 'https://sellingpartnerapi-na.amazon.com/orders/v0/orders'\nresponse = _get_signature_session('orders', tmp_access_key, tmp_secret_access_key, service, host, region, endpoint,\n access_token = access_token, security_token = tmp_session_token_)\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9046350/" ]
74,558,945
<p>I have a register function inside my Express application to create a new user. Inside this function there are a few tasks: create the user in Auth0, send an email, send a response to the client.</p> <p>I want to be able to catch the errors coming from Auth0 or Postmark to send back specific errors to the client and log them to the console. I though I could achieve this by adding a catch to an await function (I want to avoid a waterfall of <code>.then()</code> and <code>.catch()</code> blocks). This sends the error to the client but doesn't stop the code from executing. The email part is still trying to execute while the user object is undefined and I'm getting the error <code>Cannot set headers after they are sent to the client</code>.</p> <p>How can I fix this by keeping the <code>async/await</code> functionality and keep the seperate error handling for each action?</p> <p><strong>Register function</strong></p> <pre><code>export const register = asyncHandler(async (req, res, next) =&gt; { // Create user in Auth0 const user = await auth0ManagementClient.createUser({ email: req.body.email, password: generateToken(12), verify_email: false, connection: 'auth0-database-connection' }).catch((error) =&gt; { const auth0_error = { title: error.name, description: error.message, status_code: error.statusCode } console.log(auth0_error); if(error.statusCode &gt;= 400 &amp;&amp; error.statusCode &lt; 500) { return next(new ErrorResponse('Unable to create user', `We were unable to complete your registration. ${error.message}`, error.statusCode, 'user_creation_failed')); } else { return next(new ErrorResponse('Internal server error', `We have issues on our side. Please try again`, 500, 'internal_server_error')); } }); // Send welcome mail await sendWelcomeEmail(user.email) .catch((error) =&gt; { const postmark_error = { description: error.Message, status_code: error.ErrorCode } console.log(postmark_error); if(error.statusCode &gt;= 400 &amp;&amp; error.statusCode &lt; 500) { return next(new ErrorResponse('Unable to send welcome email', `We were unable to send a welcome email to you`, error.statusCode, 'welcome_email_failed')); } else { return next(new ErrorResponse('Internal server error', `We have issues on our side. Please try again`, 500, 'internal_server_error')); } }); res.status(201).json({ message: 'User succesfully registered. Check your mailbox to verify your account and continue the onboarding.', data: { user } }); }); </code></pre> <p><strong>asyncHandler.js</strong></p> <pre><code>const asyncHandler = fn =&gt; ( req, res, next) =&gt; Promise.resolve(fn(req, res, next)).catch(next); export default asyncHandler; </code></pre>
[ { "answer_id": 74559083, "author": "Trevor Dixon", "author_id": 711902, "author_profile": "https://Stackoverflow.com/users/711902", "pm_score": 2, "selected": true, "text": "async function handler(req, res, next) {\n let user;\n\n try {\n user = await auth0ManagementClient.createUser(...);\n } catch (error) {\n return next(new ErrorResponse(...));\n }\n\n try {\n await sendWelcomeEmail(user.email);\n } catch (error) {\n return next(new ErrorResponse(...));\n }\n\n res.status(201).json(...);\n}\n" }, { "answer_id": 74559206, "author": "Thomas Zimmermann", "author_id": 13527621, "author_profile": "https://Stackoverflow.com/users/13527621", "pm_score": 0, "selected": false, "text": "return return .catch() Promise.then().catch() user catch() return" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391416/" ]
74,558,954
<p>I have a slice of</p> <pre class="lang-golang prettyprint-override"><code>type Node struct { Id string Children []Node } </code></pre> <p>I have a diretory structure modelled by this slice. It can happen that there are multi level folder structure in this directory which eventually do not have any files in them. See:ű</p> <pre><code>folder1/folder2/folder3/folder4 folder1/file1.txt </code></pre> <p>I would want to clean up those folders which only have empty folders in them. So in this example only folder1 would remain with a file in it, everything below would be deleted. However I can't seem to come up with a good idea to do so. I'm perfectly fine with creating a new tree and not mutating the original one, but I don't know how I could traverse the tree effectively and see if the last child is childless and then go back to the root and remove that child which has turned out to be just a list of empty folders. Any idea would be welcomed!</p> <p>My initial solution which only removes leaves and not the parent folder also:</p> <pre class="lang-golang prettyprint-override"><code>func removeChildlessFolders(original, tree []Node) []Node { for i, node := range original { if len(node.Children) == 0 { continue } dir := Node{} dir.Id = node.Id dir.Children = append(dir.Children, node.Children...) tree = append(tree, dir) removeChildlessFolders(original[i].Children, node.Children) } return tree } </code></pre>
[ { "answer_id": 74571062, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 0, "selected": false, "text": "folder1/folder2/folder3/folder4/file1.txt folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/ folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/file2.txt folder1/file1.txt folder1/file2.txt Node type Node struct {\n name string\n isDir bool\n children []Node\n}\n getSafePath func getSafePath(parent Node, safePath string, foldersToDel []string) (string, []string) {\n if len(parent.children) == 1 && !parent.children[0].isDir {\n fileName := filepath.Base(parent.children[0].name)\n if err := os.Rename(parent.children[0].name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n return safePath, foldersToDel\n }\n\n if len(parent.children) == 1 && parent.children[0].isDir {\n foldersToDel = append(foldersToDel, parent.children[0].name)\n newChildren := []Node{}\n newChildren = append(newChildren, parent.children[0].children...)\n parent.children = newChildren\n\n safePath, foldersToDel = getSafePath(parent, safePath, foldersToDel)\n return safePath, foldersToDel\n }\n\n for _, v := range parent.children {\n if !v.isDir {\n fileName := filepath.Base(v.name)\n if err := os.Rename(v.name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n } else {\n foldersToDel = append(foldersToDel, v.name)\n safePath, foldersToDel = getSafePath(v, safePath, foldersToDel)\n }\n }\n\n return safePath, foldersToDel\n}\n main.go // code omitted for brevity\nsafeDir := \"folder1\"\nfoldersToDel := []string{}\n_, foldersToDel = getSafePath(end, safeDir, foldersToDel)\n\nfor i := len(foldersToDel) - 1; i >= 0; i-- {\n if err := os.Remove(foldersToDel[i]); err != nil {\n panic(err)\n }\n}\n" }, { "answer_id": 74574327, "author": "Mayukh Sarkar", "author_id": 4037927, "author_profile": "https://Stackoverflow.com/users/4037927", "pm_score": 3, "selected": true, "text": "Input Dir test-folder\n├── folder1\n│   └── folder2\n│   └── folder3\n├── folder4\n│   ├── folder5\n│   └── joker\n└── folder6\n └── file.txt\n Expected Result test-folder\n└── folder6\n └── file.txt\n n-ary Node type Node struct {\n Id string\n Children []*Node\n}\n func ifDir(path string) bool {\n file, err := os.Open(path)\n if err != nil {\n panic(err)\n }\n defer file.Close()\n info, err := file.Stat()\n if err != nil {\n panic(err)\n }\n if info.IsDir() {\n return true\n }\n return false\n}\n n-ary tree queue 500 func buildTreeFromDir(baseDir string) *Node {\n _, err := ioutil.ReadDir(baseDir)\n if err != nil {\n return nil\n }\n root := &Node{\n Id: baseDir,\n }\n //////////\n queue := make(chan *Node, 500) // Consider that there can not be any dir with > 500 depth\n queue <- root\n for {\n if len(queue) == 0 {\n break\n }\n data, ok := <-queue\n if ok {\n // Iterate all the contents in the dir\n curDir := (*data).Id\n if ifDir(curDir) {\n contents, _ := ioutil.ReadDir(curDir)\n\n data.Children = make([]*Node, len(contents))\n for i, content := range contents {\n node := new(Node)\n node.Id = filepath.Join(curDir, content.Name())\n data.Children[i] = node\n if content.IsDir() {\n queue <- node\n }\n }\n }\n }\n }\n return root\n}\n func printDirTree(root *Node) {\n fmt.Println(root.Id)\n for _, each := range root.Children {\n printDirTree(each)\n }\n if len(root.Children) == 0 {\n fmt.Println(\"===\")\n }\n\n}\n func recursiveEmptyDelete(root *Node) {\n // If the current root is not pointing to any dir\n if root == nil {\n return\n }\n for _, each := range root.Children {\n recursiveEmptyDelete(each)\n }\n if !ifDir(root.Id) {\n return\n } else if content, _ := ioutil.ReadDir(root.Id); len(content) != 0 {\n return\n }\n os.Remove(root.Id)\n}\n main() func main() {\n root := buildTreeFromDir(\"test-folder\")\n printDirTree(root)\n recursiveEmptyDelete(root)\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13503614/" ]
74,558,962
<p>I want to align 2 texts left and right using bootstrap. I have used primevue component InlineMessage.</p> <pre><code>&lt;InlineMessage severity=&quot;error&quot; class=&quot;my-4 block align-items-center&quot;&gt;Error Request Percentage &lt;span class=&quot;&quot; &gt; 10%&lt;/span&gt; &lt;/InlineMessage&gt; </code></pre> <p>Can someone help me?</p> <p>I tried to use text-align, align-items but it seems like not applying?</p>
[ { "answer_id": 74571062, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 0, "selected": false, "text": "folder1/folder2/folder3/folder4/file1.txt folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/ folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/file2.txt folder1/file1.txt folder1/file2.txt Node type Node struct {\n name string\n isDir bool\n children []Node\n}\n getSafePath func getSafePath(parent Node, safePath string, foldersToDel []string) (string, []string) {\n if len(parent.children) == 1 && !parent.children[0].isDir {\n fileName := filepath.Base(parent.children[0].name)\n if err := os.Rename(parent.children[0].name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n return safePath, foldersToDel\n }\n\n if len(parent.children) == 1 && parent.children[0].isDir {\n foldersToDel = append(foldersToDel, parent.children[0].name)\n newChildren := []Node{}\n newChildren = append(newChildren, parent.children[0].children...)\n parent.children = newChildren\n\n safePath, foldersToDel = getSafePath(parent, safePath, foldersToDel)\n return safePath, foldersToDel\n }\n\n for _, v := range parent.children {\n if !v.isDir {\n fileName := filepath.Base(v.name)\n if err := os.Rename(v.name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n } else {\n foldersToDel = append(foldersToDel, v.name)\n safePath, foldersToDel = getSafePath(v, safePath, foldersToDel)\n }\n }\n\n return safePath, foldersToDel\n}\n main.go // code omitted for brevity\nsafeDir := \"folder1\"\nfoldersToDel := []string{}\n_, foldersToDel = getSafePath(end, safeDir, foldersToDel)\n\nfor i := len(foldersToDel) - 1; i >= 0; i-- {\n if err := os.Remove(foldersToDel[i]); err != nil {\n panic(err)\n }\n}\n" }, { "answer_id": 74574327, "author": "Mayukh Sarkar", "author_id": 4037927, "author_profile": "https://Stackoverflow.com/users/4037927", "pm_score": 3, "selected": true, "text": "Input Dir test-folder\n├── folder1\n│   └── folder2\n│   └── folder3\n├── folder4\n│   ├── folder5\n│   └── joker\n└── folder6\n └── file.txt\n Expected Result test-folder\n└── folder6\n └── file.txt\n n-ary Node type Node struct {\n Id string\n Children []*Node\n}\n func ifDir(path string) bool {\n file, err := os.Open(path)\n if err != nil {\n panic(err)\n }\n defer file.Close()\n info, err := file.Stat()\n if err != nil {\n panic(err)\n }\n if info.IsDir() {\n return true\n }\n return false\n}\n n-ary tree queue 500 func buildTreeFromDir(baseDir string) *Node {\n _, err := ioutil.ReadDir(baseDir)\n if err != nil {\n return nil\n }\n root := &Node{\n Id: baseDir,\n }\n //////////\n queue := make(chan *Node, 500) // Consider that there can not be any dir with > 500 depth\n queue <- root\n for {\n if len(queue) == 0 {\n break\n }\n data, ok := <-queue\n if ok {\n // Iterate all the contents in the dir\n curDir := (*data).Id\n if ifDir(curDir) {\n contents, _ := ioutil.ReadDir(curDir)\n\n data.Children = make([]*Node, len(contents))\n for i, content := range contents {\n node := new(Node)\n node.Id = filepath.Join(curDir, content.Name())\n data.Children[i] = node\n if content.IsDir() {\n queue <- node\n }\n }\n }\n }\n }\n return root\n}\n func printDirTree(root *Node) {\n fmt.Println(root.Id)\n for _, each := range root.Children {\n printDirTree(each)\n }\n if len(root.Children) == 0 {\n fmt.Println(\"===\")\n }\n\n}\n func recursiveEmptyDelete(root *Node) {\n // If the current root is not pointing to any dir\n if root == nil {\n return\n }\n for _, each := range root.Children {\n recursiveEmptyDelete(each)\n }\n if !ifDir(root.Id) {\n return\n } else if content, _ := ioutil.ReadDir(root.Id); len(content) != 0 {\n return\n }\n os.Remove(root.Id)\n}\n main() func main() {\n root := buildTreeFromDir(\"test-folder\")\n printDirTree(root)\n recursiveEmptyDelete(root)\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19286575/" ]
74,558,975
<p>I am trying to convert a <strong>Maven</strong> project (with source code created using a Bukkit/Spigot API and the Java programming language) to a <strong>.jar</strong> file on <strong>eclipse</strong> (to then add as a plugin to my minecraft server).</p> <p>I have selected <strong>'run as'</strong> when clicking on the project name, and then I selected <strong>'maven build'</strong> (screenshot 1).</p> <p>I then typed in <strong>'package'</strong> in the <strong>'goal'</strong> box (screenshot 2).</p> <p>However, although it runs successfully (with no errors)(screenshot 3), there is no <strong>.jar</strong> file appearing in the 'target' folder.</p> <p>I would be so grateful for a helping hand!</p> <p>Screenshot 1:</p> <p><a href="https://i.stack.imgur.com/k33OW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k33OW.png" alt="enter image description here" /></a></p> <p>Screenshot 2:</p> <p><a href="https://i.stack.imgur.com/Uy7vM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uy7vM.png" alt="enter image description here" /></a></p> <p>Screenshot 3:</p> <p><a href="https://i.stack.imgur.com/kf7xO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kf7xO.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74571062, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 0, "selected": false, "text": "folder1/folder2/folder3/folder4/file1.txt folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/ folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/file2.txt folder1/file1.txt folder1/file2.txt Node type Node struct {\n name string\n isDir bool\n children []Node\n}\n getSafePath func getSafePath(parent Node, safePath string, foldersToDel []string) (string, []string) {\n if len(parent.children) == 1 && !parent.children[0].isDir {\n fileName := filepath.Base(parent.children[0].name)\n if err := os.Rename(parent.children[0].name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n return safePath, foldersToDel\n }\n\n if len(parent.children) == 1 && parent.children[0].isDir {\n foldersToDel = append(foldersToDel, parent.children[0].name)\n newChildren := []Node{}\n newChildren = append(newChildren, parent.children[0].children...)\n parent.children = newChildren\n\n safePath, foldersToDel = getSafePath(parent, safePath, foldersToDel)\n return safePath, foldersToDel\n }\n\n for _, v := range parent.children {\n if !v.isDir {\n fileName := filepath.Base(v.name)\n if err := os.Rename(v.name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n } else {\n foldersToDel = append(foldersToDel, v.name)\n safePath, foldersToDel = getSafePath(v, safePath, foldersToDel)\n }\n }\n\n return safePath, foldersToDel\n}\n main.go // code omitted for brevity\nsafeDir := \"folder1\"\nfoldersToDel := []string{}\n_, foldersToDel = getSafePath(end, safeDir, foldersToDel)\n\nfor i := len(foldersToDel) - 1; i >= 0; i-- {\n if err := os.Remove(foldersToDel[i]); err != nil {\n panic(err)\n }\n}\n" }, { "answer_id": 74574327, "author": "Mayukh Sarkar", "author_id": 4037927, "author_profile": "https://Stackoverflow.com/users/4037927", "pm_score": 3, "selected": true, "text": "Input Dir test-folder\n├── folder1\n│   └── folder2\n│   └── folder3\n├── folder4\n│   ├── folder5\n│   └── joker\n└── folder6\n └── file.txt\n Expected Result test-folder\n└── folder6\n └── file.txt\n n-ary Node type Node struct {\n Id string\n Children []*Node\n}\n func ifDir(path string) bool {\n file, err := os.Open(path)\n if err != nil {\n panic(err)\n }\n defer file.Close()\n info, err := file.Stat()\n if err != nil {\n panic(err)\n }\n if info.IsDir() {\n return true\n }\n return false\n}\n n-ary tree queue 500 func buildTreeFromDir(baseDir string) *Node {\n _, err := ioutil.ReadDir(baseDir)\n if err != nil {\n return nil\n }\n root := &Node{\n Id: baseDir,\n }\n //////////\n queue := make(chan *Node, 500) // Consider that there can not be any dir with > 500 depth\n queue <- root\n for {\n if len(queue) == 0 {\n break\n }\n data, ok := <-queue\n if ok {\n // Iterate all the contents in the dir\n curDir := (*data).Id\n if ifDir(curDir) {\n contents, _ := ioutil.ReadDir(curDir)\n\n data.Children = make([]*Node, len(contents))\n for i, content := range contents {\n node := new(Node)\n node.Id = filepath.Join(curDir, content.Name())\n data.Children[i] = node\n if content.IsDir() {\n queue <- node\n }\n }\n }\n }\n }\n return root\n}\n func printDirTree(root *Node) {\n fmt.Println(root.Id)\n for _, each := range root.Children {\n printDirTree(each)\n }\n if len(root.Children) == 0 {\n fmt.Println(\"===\")\n }\n\n}\n func recursiveEmptyDelete(root *Node) {\n // If the current root is not pointing to any dir\n if root == nil {\n return\n }\n for _, each := range root.Children {\n recursiveEmptyDelete(each)\n }\n if !ifDir(root.Id) {\n return\n } else if content, _ := ioutil.ReadDir(root.Id); len(content) != 0 {\n return\n }\n os.Remove(root.Id)\n}\n main() func main() {\n root := buildTreeFromDir(\"test-folder\")\n printDirTree(root)\n recursiveEmptyDelete(root)\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12985497/" ]
74,558,982
<p>How am I able to return view('support') with following:</p> <pre class="lang-php prettyprint-override"><code>-&gt;withInput() -&gt;with('success', 'Found results'); </code></pre> <p>Code</p> <pre class="lang-php prettyprint-override"><code> // if validation do not fail if ($validated-&gt;fails() === false) { //session()-&gt;flashInput($request-&gt;input()); // return return view('siteadmin.support.support', [ 'articles' =&gt; $articles, 'categories' =&gt; $categories, ]); } </code></pre> <p>Following code is not working: Code</p> <pre class="lang-php prettyprint-override"><code> // if validation do not fail if ($validated-&gt;fails() === false) { //session()-&gt;flashInput($request-&gt;input()); // return return view('siteadmin.support.support', [ 'articles' =&gt; $articles, 'categories' =&gt; $categories, ]) -&gt;withInput() -&gt;with('success', 'Found results'); } </code></pre>
[ { "answer_id": 74571062, "author": "Ivan Pesenti", "author_id": 14394371, "author_profile": "https://Stackoverflow.com/users/14394371", "pm_score": 0, "selected": false, "text": "folder1/folder2/folder3/folder4/file1.txt folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/ folder1/file1.txt folder1/folder2/folder3/folder4/file1.txt folder1/folder5/file2.txt folder1/file1.txt folder1/file2.txt Node type Node struct {\n name string\n isDir bool\n children []Node\n}\n getSafePath func getSafePath(parent Node, safePath string, foldersToDel []string) (string, []string) {\n if len(parent.children) == 1 && !parent.children[0].isDir {\n fileName := filepath.Base(parent.children[0].name)\n if err := os.Rename(parent.children[0].name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n return safePath, foldersToDel\n }\n\n if len(parent.children) == 1 && parent.children[0].isDir {\n foldersToDel = append(foldersToDel, parent.children[0].name)\n newChildren := []Node{}\n newChildren = append(newChildren, parent.children[0].children...)\n parent.children = newChildren\n\n safePath, foldersToDel = getSafePath(parent, safePath, foldersToDel)\n return safePath, foldersToDel\n }\n\n for _, v := range parent.children {\n if !v.isDir {\n fileName := filepath.Base(v.name)\n if err := os.Rename(v.name, fmt.Sprintf(\"%v/%v\", safePath, fileName)); err != nil {\n panic(err)\n }\n } else {\n foldersToDel = append(foldersToDel, v.name)\n safePath, foldersToDel = getSafePath(v, safePath, foldersToDel)\n }\n }\n\n return safePath, foldersToDel\n}\n main.go // code omitted for brevity\nsafeDir := \"folder1\"\nfoldersToDel := []string{}\n_, foldersToDel = getSafePath(end, safeDir, foldersToDel)\n\nfor i := len(foldersToDel) - 1; i >= 0; i-- {\n if err := os.Remove(foldersToDel[i]); err != nil {\n panic(err)\n }\n}\n" }, { "answer_id": 74574327, "author": "Mayukh Sarkar", "author_id": 4037927, "author_profile": "https://Stackoverflow.com/users/4037927", "pm_score": 3, "selected": true, "text": "Input Dir test-folder\n├── folder1\n│   └── folder2\n│   └── folder3\n├── folder4\n│   ├── folder5\n│   └── joker\n└── folder6\n └── file.txt\n Expected Result test-folder\n└── folder6\n └── file.txt\n n-ary Node type Node struct {\n Id string\n Children []*Node\n}\n func ifDir(path string) bool {\n file, err := os.Open(path)\n if err != nil {\n panic(err)\n }\n defer file.Close()\n info, err := file.Stat()\n if err != nil {\n panic(err)\n }\n if info.IsDir() {\n return true\n }\n return false\n}\n n-ary tree queue 500 func buildTreeFromDir(baseDir string) *Node {\n _, err := ioutil.ReadDir(baseDir)\n if err != nil {\n return nil\n }\n root := &Node{\n Id: baseDir,\n }\n //////////\n queue := make(chan *Node, 500) // Consider that there can not be any dir with > 500 depth\n queue <- root\n for {\n if len(queue) == 0 {\n break\n }\n data, ok := <-queue\n if ok {\n // Iterate all the contents in the dir\n curDir := (*data).Id\n if ifDir(curDir) {\n contents, _ := ioutil.ReadDir(curDir)\n\n data.Children = make([]*Node, len(contents))\n for i, content := range contents {\n node := new(Node)\n node.Id = filepath.Join(curDir, content.Name())\n data.Children[i] = node\n if content.IsDir() {\n queue <- node\n }\n }\n }\n }\n }\n return root\n}\n func printDirTree(root *Node) {\n fmt.Println(root.Id)\n for _, each := range root.Children {\n printDirTree(each)\n }\n if len(root.Children) == 0 {\n fmt.Println(\"===\")\n }\n\n}\n func recursiveEmptyDelete(root *Node) {\n // If the current root is not pointing to any dir\n if root == nil {\n return\n }\n for _, each := range root.Children {\n recursiveEmptyDelete(each)\n }\n if !ifDir(root.Id) {\n return\n } else if content, _ := ioutil.ReadDir(root.Id); len(content) != 0 {\n return\n }\n os.Remove(root.Id)\n}\n main() func main() {\n root := buildTreeFromDir(\"test-folder\")\n printDirTree(root)\n recursiveEmptyDelete(root)\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13229531/" ]
74,558,993
<p>When i try to use a ListView which contains checkboxes with scrollDirection set to Axis.horizontal inside a SimpleDialog throws an error: RenderShrinkWrappingViewport does not support returning intrinsic dimensions. I tried wrapping the ListView with Containers, Flexible.. but it still thorws an error.</p> <p>If i set the scrollDirection to Axis.vertical it works fine. I am guessing the problem is with it being inside a dialog.</p> <pre><code> @override Widget build(BuildContext context) =&gt; SimpleDialog( backgroundColor: Color.fromARGB(255, 229, 233, 240), contentPadding: EdgeInsets.zero, children: [ Expanded( child: ListView( shrinkWrap: true, scrollDirection: Axis.horizontal, children: [ ...personCheckboxes.map(buildCheckboxes).toList(), ], ), ), </code></pre> <p>The buildCheckboxes function:</p> <pre><code> Widget buildCheckboxes(CheckBoxState checkbox) =&gt; CheckboxListTile( controlAffinity: ListTileControlAffinity.leading, activeColor: Colors.blue, value: checkbox.checked, title: Text(checkbox.title, style: const TextStyle(fontSize: 12)), onChanged: (value) =&gt; setState(() { checkbox.checked = value!; if (checkbox.value == 'M') { maleChecked = checkbox.checked; } else if (checkbox.value == 'F') { femaleChecked = checkbox.checked; } checkResults(); setState(() {}); //runFilterCheckbox(checkbox.value, value); }), ); </code></pre> <p>I have tried wrapping the ListView widget with different widgets (Container). It still produces an error.</p> <pre><code>Widget build(BuildContext context) =&gt; SimpleDialog( backgroundColor: Color.fromARGB(255, 229, 233, 240), contentPadding: EdgeInsets.zero, children: [ Container( height: 100.0, width: 100.0, child: ListView( shrinkWrap: true, scrollDirection: Axis.horizontal, children: [ ...personCheckboxes.map(buildCheckboxes).toList(), ], ), ), </code></pre> <p>Even after wrapping the listView with SizedBox, the problem persist:</p> <pre class="lang-dart prettyprint-override"><code>@override Widget build(BuildContext context) =&gt; SimpleDialog( backgroundColor: Color.fromARGB(255, 229, 233, 240), contentPadding: EdgeInsets.zero, children: [ SizedBox( height: 20.0, width: double.maxFinite, child: ListView( shrinkWrap: true, scrollDirection: Axis.horizontal, children: [ ...personCheckboxes.map(buildCheckboxes).toList(), ], ), ), </code></pre>
[ { "answer_id": 74559063, "author": "Md. Kamrul Amin", "author_id": 6067774, "author_profile": "https://Stackoverflow.com/users/6067774", "pm_score": 1, "selected": false, "text": "width: double.maxFinite, showDialog(\n context: context,\n builder: (BuildContext context) {\n return AlertDialog(\n content: Container(\n width: double.maxFinite,\n child: ListView(\n children: <Widget>[]\n ),\n ),\n );\n }\n);\n" }, { "answer_id": 74561050, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": true, "text": "CheckboxListTile CheckboxListTile MediaQuery.of(context).size.width ListView SizedBox(\n height: MediaQuery.of(context).size.height*.5,\n width: 200, //or \n child: ListView(\n buildCheckboxes(...)=> SizedBox(\n width: 200,\n child: CheckboxListTile(\n controlAffinity: ListTileControlAffinity.leading,\n showDialog(\n context: context,\n builder: (context) => SizedBox(\n height: MediaQuery.of(context).size.height * .5,\n width: 200, //or\n child: Material(..\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74558993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15438511/" ]
74,559,000
<p>im tryting to convert a List of objects to map</p> <pre><code>var mapped; List&lt;Slots&gt;? data=controller.slots; mapped = data!.map((e) { return { DateTime.parse(e.date!): e.slot, }; }).toList(); </code></pre> <p>the output of the variable mapped is</p> <pre><code>[{2022-11-24 00:00:00.000Z: [Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot']}, {2022-11-25 00:00:00.000Z: [Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot']}] </code></pre> <p>and i called this map variable in a function</p> <pre><code> List&lt;dynamic&gt; _getEventsfromDay(DateTime date) { print(mapped); return mapped[date] ?? []; } </code></pre> <p>but it shows me error like</p> <blockquote> <p>Expected a value of type 'int', but got one of type 'DateTime'</p> </blockquote> <p>but when i called the mapped variable with index like <code>mapped[0][date]</code> it works</p> <p>i think it is in iterateable how can i change this to a map varible</p>
[ { "answer_id": 74559063, "author": "Md. Kamrul Amin", "author_id": 6067774, "author_profile": "https://Stackoverflow.com/users/6067774", "pm_score": 1, "selected": false, "text": "width: double.maxFinite, showDialog(\n context: context,\n builder: (BuildContext context) {\n return AlertDialog(\n content: Container(\n width: double.maxFinite,\n child: ListView(\n children: <Widget>[]\n ),\n ),\n );\n }\n);\n" }, { "answer_id": 74561050, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": true, "text": "CheckboxListTile CheckboxListTile MediaQuery.of(context).size.width ListView SizedBox(\n height: MediaQuery.of(context).size.height*.5,\n width: 200, //or \n child: ListView(\n buildCheckboxes(...)=> SizedBox(\n width: 200,\n child: CheckboxListTile(\n controlAffinity: ListTileControlAffinity.leading,\n showDialog(\n context: context,\n builder: (context) => SizedBox(\n height: MediaQuery.of(context).size.height * .5,\n width: 200, //or\n child: Material(..\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4923677/" ]
74,559,054
<p>I am trying to trigger the form submit function from <code>custom component</code>. <br> In general my goal is to trigger a <code>boolean state value</code> which is a part of <code>form</code>, and even though the <code>custom component</code> is imported inside the form, somehow it doesn't work. <br> Problem is about <code>sendEmail</code> function which comes from <code>Custom Component</code></p> <p>Here is the <a href="https://codesandbox.io/s/zealous-shaw-qm4fwx?file=/src/App.js" rel="nofollow noreferrer">codesandbox link</a> and code example below.</p> <p>Custom Component</p> <pre><code>import React from &quot;react&quot;; const CustomComponent = (props) =&gt; { return ( &lt;div&gt; &lt;button onClick={props.sendEmail} type=&quot;submit&quot;&gt; send email &lt;/button&gt; &lt;/div&gt; ); }; export default CustomComponent; </code></pre> <p>App.js</p> <pre><code>import { useState } from &quot;react&quot;; import CustomComp from &quot;./CustomComp&quot;; export default function App() { const [isDone, setIsDone] = useState(false); const [inputText, setInputText] = useState(&quot;&quot;); const handleSubmit = (e) =&gt; { e.preventDefault(); setIsDone(true); console.log(&quot;inputText&quot;, inputText); }; console.log(isDone); const sendEmail = () =&gt; { // this doesn't work handleSubmit(); console.log(&quot;isDone&quot;, isDone); }; const onChangeHandler = (e) =&gt; { setInputText(e.target.value); }; return ( &lt;form&gt; &lt;h1&gt;Hello CodeSandbox&lt;/h1&gt; &lt;input type=&quot;text&quot; onChange={onChangeHandler} value={inputText} /&gt; &lt;CustomComp sendEmail={sendEmail} /&gt; &lt;button onClick={handleSubmit} type=&quot;submit&quot;&gt; submit &lt;/button&gt; &lt;/form&gt; ); } </code></pre> <p>Any help will be appreciated</p>
[ { "answer_id": 74559063, "author": "Md. Kamrul Amin", "author_id": 6067774, "author_profile": "https://Stackoverflow.com/users/6067774", "pm_score": 1, "selected": false, "text": "width: double.maxFinite, showDialog(\n context: context,\n builder: (BuildContext context) {\n return AlertDialog(\n content: Container(\n width: double.maxFinite,\n child: ListView(\n children: <Widget>[]\n ),\n ),\n );\n }\n);\n" }, { "answer_id": 74561050, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": true, "text": "CheckboxListTile CheckboxListTile MediaQuery.of(context).size.width ListView SizedBox(\n height: MediaQuery.of(context).size.height*.5,\n width: 200, //or \n child: ListView(\n buildCheckboxes(...)=> SizedBox(\n width: 200,\n child: CheckboxListTile(\n controlAffinity: ListTileControlAffinity.leading,\n showDialog(\n context: context,\n builder: (context) => SizedBox(\n height: MediaQuery.of(context).size.height * .5,\n width: 200, //or\n child: Material(..\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12971921/" ]
74,559,057
<p>I want to install Ngb in Angular. I use n Node.js version v19.1.0. I already tried --force and --legacy-pear-drops. Also i tried reinstalling Node.js.</p> <p>The log: <code>`npm ERR! code ERESOLVE</code> <code>npm ERR! ERESOLVE could not resolve</code> <code>npm ERR!</code> <code>npm ERR! While resolving: markb@0.0.0</code> <code>npm ERR! Found: @angular/core@14.2.2</code> <code>npm ERR! node_modules/@angular/core</code> <code>npm ERR! peer @angular/core@&quot;14.2.2&quot; from @angular/animations@14.2.2</code> <code>npm ERR! node_modules/@angular/animations</code> <code>npm ERR! peerOptional @angular/animations@&quot;14.2.2&quot; from @angular/platform-browser@14.2.2</code> <code>npm ERR! node_modules/@angular/platform-browser</code> <code>npm ERR! peer @angular/platform-browser@&quot;14.2.2&quot; from @angular/forms@14.2.2</code> <code>npm ERR! node_modules/@angular/forms</code> <code>npm ERR! @angular/forms@&quot;^14.1.0&quot; from the root project</code> <code>npm ERR! 3 more (@angular/platform-browser-dynamic, @angular/router, the root project)</code> <code>npm ERR! @angular/animations@&quot;^14.1.0&quot; from the root project</code> <code>npm ERR! peer @angular/core@&quot;14.2.2&quot; from @angular/common@14.2.2</code> <code>npm ERR! node_modules/@angular/common</code> <code>npm ERR! peer @angular/common@&quot;14.2.2&quot; from @angular/forms@14.2.2</code> <code>npm ERR! node_modules/@angular/forms</code> <code>npm ERR! @angular/forms@&quot;^14.1.0&quot; from the root project</code> <code>npm ERR! peer @angular/common@&quot;14.2.2&quot; from @angular/platform-browser@14.2.2</code> <code>npm ERR! node_modules/@angular/platform-browser</code> <code>npm ERR! peer @angular/platform-browser@&quot;14.2.2&quot; from @angular/forms@14.2.2</code> <code>npm ERR! node_modules/@angular/forms</code> <code>npm ERR! @angular/forms@&quot;^14.1.0&quot; from the root project</code> <code>npm ERR! 3 more (@angular/platform-browser-dynamic, @angular/router, the root project)</code> <code>npm ERR! 3 more (@angular/platform-browser-dynamic, @angular/router, the root project)</code> <code>npm ERR! 6 more (@angular/compiler, @angular/forms, ...)</code> <code>npm ERR!</code> <code>npm ERR! Could not resolve dependency:</code> <code>npm ERR! @ng-bootstrap/ng-bootstrap@&quot;13.1.1&quot; from the root project</code> <code>npm ERR!</code> <code>npm ERR! Conflicting peer dependency: @angular/core@14.2.12</code> <code>npm ERR! node_modules/@angular/core</code> <code>npm ERR! peer @angular/core@&quot;14.2.12&quot; from @angular/forms@14.2.12</code> <code>npm ERR! node_modules/@angular/forms</code> <code>npm ERR! @angular/forms@&quot;^14.1.0&quot; from the root project</code> <code>npm ERR! peer @angular/forms@&quot;^14.1.0&quot; from @ng-bootstrap/ng-bootstrap@13.1.1</code> <code>npm ERR! node_modules/@ng-bootstrap/ng-bootstrap</code> <code>npm ERR! @ng-bootstrap/ng-bootstrap@&quot;13.1.1&quot; from the root project</code> <code>npm ERR!</code> <code>npm ERR! Fix the upstream dependency conflict, or retry</code> <code>npm ERR! this command with --force, or --legacy-peer-deps</code> <code>npm ERR! to accept an incorrect (and potentially broken) dependency resolution.</code> <code>npm ERR!</code> <code>npm ERR! See C:\Users\thomas\AppData\Local\npm-cache\eresolve-report.txt for a full report.</code></p> <p><code>npm ERR! A complete log of this run can be found in:</code> <code>npm ERR! C:\Users\thomas\AppData\Local\npm-cache_logs\2022-11-24T10_07_23_103Z-debug-0.log</code> <code>× Packages installation failed, see above.`</code></p> <p>I expected installs Bootstrap</p>
[ { "answer_id": 74559247, "author": "Vishnu Prabhu", "author_id": 20587586, "author_profile": "https://Stackoverflow.com/users/20587586", "pm_score": 0, "selected": false, "text": "ng add @ng-bootstrap/ng-bootstrap\n ng add @ng-bootstrap/ng-bootstrap --project myProject\n" }, { "answer_id": 74559331, "author": "Mark Baumann", "author_id": 18203720, "author_profile": "https://Stackoverflow.com/users/18203720", "pm_score": 3, "selected": true, "text": "npm config set legacy-peer-deps true npm audit fix" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589673/" ]
74,559,078
<p>i got an error and this is my API wrapper</p> <pre><code> if (method == &quot;get&quot;) { var param = ''; Map&lt;String, dynamic&gt; params = data['params'] != null ? data['params'] : {}; params.forEach((k, v) =&gt; param += k + &quot;=&quot; + (v == null ? '' : v) + &quot;&amp;&quot;); try { Dio dio = new Dio(); dio.options.headers = headers; final response = await dio.get(url + &quot;?&quot; + param); responseJson = _response(response); //print('Response ' + response.data.toString()); } on SocketException { throw FetchDataException('Tidak terhubung ke server'); } . . . </code></pre> <p>and this is the repository:</p> <pre><code> Future&lt;LeaveListModel&gt; fetchResponse(query) async { final response = await _wrapper.apiRequest( &quot;get&quot;, _wrapper.leaveListGetData, {'params': query}, true); return LeaveListModel.fromJson(response); } </code></pre> <p>this is the service, in case you wanted to know:</p> <pre><code>class Service { GetStorage localData = GetStorage(); final String initial = &quot;Service&quot;; final String baseUrl = ConstantConfig().leaveListEndPoint; final String appCode = ConstantConfig().leaveListAppCode; final String outputType = &quot;json&quot;; final String routeAuthConnect = &quot;auth/connect/&quot;; final String routeAuthGetAccessToken = &quot;auth/getAccessToken/&quot;; final String leaveListGetData = &quot;list/&quot;; Future&lt;dynamic&gt; apiRequest( String method, String route, Map&lt;String, dynamic&gt; data, [bool needToken = false]) async { ApiWrapper _apiWrapper = ApiWrapper(); if (needToken) { int thisTime = (DateTime.now().millisecondsSinceEpoch / 1000).round(); String? savedExpired = localData.read(initial + KeyStorage.accessExpired); int expire = savedExpired == null ? 0 : int.parse(savedExpired); if (expire &lt; thisTime) { dynamic tokenResponse = await _apiWrapper.request(baseUrl, initial, appCode, outputType, 'post', routeAuthGetAccessToken, {}); await localData.write(initial + KeyStorage.accessToken, tokenResponse['response']['access_token']); return await _apiWrapper.request( baseUrl, initial, appCode, outputType, method, route, data); } else { return await _apiWrapper.request( baseUrl, initial, appCode, outputType, method, route, data); } } else { return await _apiWrapper.request( baseUrl, initial, appCode, outputType, method, route, data); } } } </code></pre> <p>i just want to call a json file but it show an error, i don't know what's wrong with my code, in case you know how to fix it please let me know</p> <p>this is the error:</p> <pre><code> I/flutter (20696): Call https:xxxxxxxxxxxx I/flutter (20696): type '_InternalLinkedHashMap&lt;dynamic, dynamic&gt;' is not a subtype of type 'Map&lt;String, dynamic&gt;' </code></pre> <p>another error note:</p> <pre><code>I/flutter ( 7626): {} I/flutter ( 7626): 1 I/flutter ( 7626): type '_InternalLinkedHashMap&lt;dynamic, dynamic&gt;' is not a subtype of type 'Map&lt;String, dynamic&gt;' I/flutter ( 7626): {} I/flutter ( 7626): 1 I/flutter ( 7626): type '_InternalLinkedHashMap&lt;dynamic, dynamic&gt;' is not a subtype of type 'Map&lt;String, dynamic&gt;' </code></pre> <p>actually that shows that the process is stopped on <code>Map&lt;String, dynamic&gt; params = data['params'] != null ? data['params'] : {};</code> because i try to debug the API wrapper with <code>print('1');</code>, <code>print('2');</code>, <code>print('3');</code> just to show where the process stop and getting error</p>
[ { "answer_id": 74559247, "author": "Vishnu Prabhu", "author_id": 20587586, "author_profile": "https://Stackoverflow.com/users/20587586", "pm_score": 0, "selected": false, "text": "ng add @ng-bootstrap/ng-bootstrap\n ng add @ng-bootstrap/ng-bootstrap --project myProject\n" }, { "answer_id": 74559331, "author": "Mark Baumann", "author_id": 18203720, "author_profile": "https://Stackoverflow.com/users/18203720", "pm_score": 3, "selected": true, "text": "npm config set legacy-peer-deps true npm audit fix" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13497264/" ]
74,559,086
<p>I am generating text fields dynamically and I am trying to get the contents of the text fields.</p> <pre><code>//I declared a list of string and generated it using the length of my product. late final List&lt;String&gt; recovered; //the length of the products is 3 recovered = List.generate(products.length, (index) =&gt; &quot;&quot;)); TextField( onSubmitted: (value) { recovered.insert(index, value); log(&quot;the value is $value&quot;); setState(() {}); }, controller: myControllers[index], decoration: const InputDecoration( enabledBorder:OutlineInputBorder( borderSide: BorderSide( width: 1, color: Colors.grey)), ), ), </code></pre> <p>I inserted 1,2,4 into the textFields generated by my listView Builder and got the following values [1, 2, 4, , , ] instead of [1, 2, 4].</p>
[ { "answer_id": 74559531, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 3, "selected": true, "text": "insert recovered.insert(index, value);\n recovered[index] = value;\n" }, { "answer_id": 74559557, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 1, "selected": false, "text": "Submit onSubmitted: (value) {\n if(value.isNotEmpty){\n recovered.insert(index, value);\n log(\"the value is $value\");\n setState(() {});\n }\n \n},\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12279038/" ]
74,559,088
<p>I am trying to figure out how to print a requested amount of prime numbers but I am having problems.</p> <p>I can't describe what I did so I'll just paste my code so far:</p> <pre><code>requested_primes = 3 #just for simplicity, i am going to request an input for how many prime integers they #want printed found_primes = 0 examined_number = 2 #starting point for counting while found_primes != requested_primes: #self-evident i hope for i in range(2, examined_number): #trying to check if it's a prime number or not with this one. if examined_number % i == 0: #if it can be neatly divided, it's not a prime and the search has to go #on examined_number += 1 else: #if no neat divisions can occur then i got a prime number and i can print it before going back #and searching for another one, until found_primes == requested_primes print(examined_number, end=' ') examined_number += 1 found_primes += 1 </code></pre> <p>Nothing comes up in the terminal.</p>
[ { "answer_id": 74559531, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 3, "selected": true, "text": "insert recovered.insert(index, value);\n recovered[index] = value;\n" }, { "answer_id": 74559557, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 1, "selected": false, "text": "Submit onSubmitted: (value) {\n if(value.isNotEmpty){\n recovered.insert(index, value);\n log(\"the value is $value\");\n setState(() {});\n }\n \n},\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13598482/" ]
74,559,113
<p>Confused on OOP in Python3:</p> <p>main.py:</p> <pre><code>import ma as m1 r = m1.ma1() r.doit() print(r.m1avar) print(r.m2var) r.m2do() </code></pre> <p>ma.py:</p> <pre><code>import mb as m2 class ma1(m2.mclass2): m1avar = 10 def doit(self): self.logout(&quot;doit!&quot;) def logout(self, a): print(a+&quot; &lt;--- this is correct&quot;) </code></pre> <p>mb.py:</p> <pre><code>class mclass2(): m2var = 5; m1avar = 5; def doit(self): super().logout(&quot;m2 do it&quot;) def m2do(self): super().logout(&quot;child class&quot;) </code></pre> <p>Produces:</p> <pre><code>doit! &lt;--- this is correct 10 5 Traceback (most recent call last): File &quot;/home/alex/Desktop/rrr/m1.py&quot;, line 8, in &lt;module&gt; r.m2do() File &quot;/home/alex/Desktop/rrr/mb.py&quot;, line 11, in m2do super().logout(&quot;child class&quot;) AttributeError: 'super' object has no attribute 'logout' </code></pre> <p>How do I get the lowest class (mclass2) to access methods in a higher class ma1 - specifically the .logout method.</p> <p>Thanks!</p>
[ { "answer_id": 74559622, "author": "tjones", "author_id": 19389117, "author_profile": "https://Stackoverflow.com/users/19389117", "pm_score": 2, "selected": true, "text": "self. super. class mclass2():\n \n m2var = 5;\n m1avar = 5;\n \n def doit(self):\n super().logout(\"m2 do it\")\n \n def m2do(self):\n self.logout(\"child class\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9437961/" ]
74,559,126
<p>I am using <a href="https://underscores.me/" rel="nofollow noreferrer">underscore</a> to develop a wordpress theme.</p> <p>I have a custom post type name <code>project</code>, thus I have, for instance, this url: <code>http://a.site.local/projects/a-beauty/</code>.</p> <p>I have in my <code>template-parts/</code> directory the file <code>content-projects</code>.</p> <pre><code>$ cat template-parts/content-projects.php &lt;h1&gt;Project&lt;/h1&gt; </code></pre> <p>When I browse <code>http://a.site.local/projects/a-beauty/</code>, I have my title <strong>but also the sidebar and the footer</strong> (even if they do not appear in my <code>content-project.php</code> nor in <code>index.php</code>).</p> <p>Where are those widgets coming from / loaded ?</p>
[ { "answer_id": 74578728, "author": "Alexandra Batrak", "author_id": 8870249, "author_profile": "https://Stackoverflow.com/users/8870249", "pm_score": 2, "selected": true, "text": "<?php if( !is_post_type_archive( 'project' ) ) : ?>\n // wrap the code you don't want to show on that archive\n<?php endif; ?>\n <?php if( !is_singular( 'project' ) ) : ?>\n // wrap the code you don't want to show on the post\n<?php endif; ?>\n </div><!-- #page -->\n<?php wp_footer(); ?>\n</body>\n</html>\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4767885/" ]
74,559,160
<p>My team manager wants to implement Tailwind CSS for the first time in the project and I am new to tailwind css The project has some vanilla CSS files so my question is do I need to <strong>write afresh tailwind css stylesheets</strong> right from the scratch or is there a better solution ..please advise</p> <p>I tried converting old vanilla css files to tailwind using command npx tailwindcss -i input.css -o output.css but its not helpful</p>
[ { "answer_id": 74585599, "author": "RK007", "author_id": 14386098, "author_profile": "https://Stackoverflow.com/users/14386098", "pm_score": 2, "selected": true, "text": "npx tailwindcss -i input.css -o output.css tailwind.config.js tw-bg-black // tailwind.config.js\nmodule.exports = {\n prefix: 'tw-',\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589585/" ]
74,559,168
<p>I have an annoying problem I wanted to use custom dialog in recycler view adapter but I need a context for builder and I wrote that but I can't initialized that. I looked up Internet but I can't find anything. Is anyone can help me? Thank you and have a good codes :)</p> <pre><code>private lateinit var context: Context </code></pre> <p>Adapter class</p> <pre><code>class MainAdapter(private val cityList: List&lt;City&gt;) : RecyclerView.Adapter&lt;MainAdapter.ViewHolder&gt;(){ class ViewHolder(binding: CityCardBinding):RecyclerView.ViewHolder(binding.root){ val cityBinding : CityCardBinding = binding } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = CityCardBinding.inflate(LayoutInflater.from(parent.context),parent,false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val city = cityList[position] holder.cityBinding.cityCard = city holder.cityBinding.cardCity.setOnClickListener { } } override fun getItemCount(): Int = cityList.size } </code></pre>
[ { "answer_id": 74561331, "author": "Ayaz Muhammad", "author_id": 6749453, "author_profile": "https://Stackoverflow.com/users/6749453", "pm_score": 0, "selected": false, "text": " binding.rvIssues.layoutManager =\n LinearLayoutManager(myContext, RecyclerView.VERTICAL, false)\n val adapterIssue = AdapterIssues(myContext, messagesList)\n binding.rvIssues.adapter = adapterIssue \n class AdapterIssues(\nvar context: Context,\nvar messagesList: ArrayList<ResourceModel>,\nvar listener: SetOnIssueItemClickListener) :\nRecyclerView.Adapter<AdapterIssues.ViewHolder>() {}\n" }, { "answer_id": 74562061, "author": "krupa parekh", "author_id": 11041834, "author_profile": "https://Stackoverflow.com/users/11041834", "pm_score": 2, "selected": true, "text": "class MyAdapter(private val context: Context) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {\n\n private lateinit var mContext: Context\n\n fun doSomething() {\n mContext = context\n }\n}\n private fun bindAdapter() {\n val adapter = MyAdapter(context = this) // Use requireActivity() for fragments\n}\n holder.cityBinding.cardCity.context" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19023704/" ]
74,559,192
<p>I've managed to automate some tedious code-writing with something like the following:</p> <pre><code>codes&lt;-c(&quot;code1&quot;, &quot;code2&quot;,&quot;code3&quot;) for(i in codes){print(paste0(&quot;repetitivetext&quot;,i))} </code></pre> <p>yielding something like the following output:</p> <pre><code>&quot;repetitivetextcode1&quot; &quot;repetitivetextcode2&quot; &quot;repetitivetextcode3&quot; </code></pre> <p>Now I want to add the beginning and end of the code. I write:</p> <pre><code>paste0(&quot;beginning&quot;,for(i in codes){print(paste0(&quot;repetitivetext&quot;,i))},&quot;end&quot;)¨ </code></pre> <p>Hoping to get something like:</p> <pre><code>beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end </code></pre> <p>Instead I get:</p> <pre><code>&quot;repetitivetextcode1&quot; &quot;repetitivetextcode2&quot; &quot;repetitivetextcode3&quot; &quot;beginningend&quot; </code></pre> <p>How do I get my desired output? Is there for instance a way of collapsing the output of the for loop into a single character string (I already tried the collapse-option in paste0)?</p> <p>This code segment will then have to be pasted together with other similarly created segments, so the lines must be saved in the correct order and they need to be saved as a single character string.</p>
[ { "answer_id": 74559238, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 3, "selected": true, "text": "output for output <- c()\nfor(i in codes){\n output[i] <- paste0(\"repetitivetext\",i)\n }\n paste0 output paste0(\"beginning\", output, ,\"end\")\n[1] \"beginningrepetitivetextcode1end\" \"beginningrepetitivetextcode2end\" \"beginningrepetitivetextcode3end\"\n collapse paste0(\"beginning\",output,\"end\", collapse = \"\")\n[1] \"beginningrepetitivetextcode1endbeginningrepetitivetextcode2endbeginningrepetitivetextcode3end\"\n codes<-c(\"code1\", \"code2\",\"code3\")\n" }, { "answer_id": 74559312, "author": "I_O ", "author_id": 20513099, "author_profile": "https://Stackoverflow.com/users/20513099", "pm_score": 1, "selected": false, "text": "collapse paste0('beginning',\n paste0('repetitivetext', codes, collapse = ''),\n 'end'\n)\n ## [1] \"beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end\"\n" }, { "answer_id": 74559343, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "for codes <- c(\"code1\", \"code2\", \"code3\")\ncodes2 <- paste0(\"repetitivetext\", codes)\nprint(codes2)\n [1] \"repetitivetextcode1\" \"repetitivetextcode2\" \"repetitivetextcode3\"\n paste0(\"beginning\", \n paste0(codes2, collapse = \"\"), \n \"end\"\n)\n [1] \"beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end\"\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5428469/" ]
74,559,219
<p>Hi this is my first question here so go easy on me if I format things incorrectly.</p> <p>I'm trying to model a table where each value is either 1 or 0. I'd like to determine whether the sum of a column is 0 or not 0, then check how many columns are &gt; 0. The underlying problem I'm trying to solve is appointment scheduling, where each column represent one appointment. I've simplified it here as in the original I'm using a dataframe to match clinician competencies to patient needs (each row is a patient need). My problem started when I tried to ensure all variables could only be equal to 1 if in one if they were in one of 2 columns, hence my simplified code here to try to work out where I am going wrong.</p> <p>I've set up a pulp variable dictionary with ROWS and COLS as the keys, and value == 0 or 1.</p> <p>In the problem definition I'm trying to assign a value of 1 to the column sum if sum of the row values in the column is &gt;= 1 and 0 otherwise, then summing the total. This should allow me to set the total number of columns that sum to &gt;= 1, for example only 2 columns are represented by non zero variables.</p> <p>In the code below my aim is for the total sum of all variables to be minimised BUT there should be 2 columns that contain a variable 1 i.e. 2 columns sum to &gt;=1.</p> <p>Thanks in advance.</p> <pre><code>import pulp as Pulp ROWS = range(1, 6) COLS = range(1,5) prob = Pulp.LpProblem(&quot;Fewestcolumns&quot;, Pulp.LpMinimize) choices = Pulp.LpVariable.dicts(&quot;Choice&quot;, (ROWS, COLS), cat=&quot;Integer&quot;, lowBound=0, upBound=1) prob += Pulp.lpSum([choices[row][col] for row in ROWS for col in COLS]) prob += Pulp.lpSum([1 if Pulp.lpSum([choices[row][col] for row in ROWS]) &gt;= 1 else 0 for col in COLS]) == 2 prob.solve() print(&quot;Status:&quot;, Pulp.LpStatus[prob.status]) for v in prob.variables(): print(v.name, &quot;=&quot;, v.varValue)` </code></pre> <p>My results:</p> <pre><code>C:\Users\xxxComputing\LinearProgramming\Scripts\python.exe C:/Users/xxx/Computing/LinearProgramming/LinearProgTest.py Welcome to the CBC MILP Solver Version: 2.10.3 Build Date: Dec 15 2019 command line - C:\Users\xxxx\Computing\LinearProgramming\lib\site-packages\pulp\solverdir\cbc\win\64\cbc.exe C:\Users\simon\AppData\Local\Temp\4f8ff67726844bde8abe98316b6338c4-pulp.mps timeMode elapsed branch printingOptions all solution C:\Users\simon\AppData\Local\Temp\4f8ff67726844bde8abe98316b6338c4-pulp.sol (default strategy 1) At line 2 NAME MODEL At line 3 ROWS At line 6 COLUMNS At line 67 RHS At line 69 BOUNDS At line 90 ENDATA Problem MODEL has 1 rows, 20 columns and 0 elements Coin0008I MODEL read with 0 errors Option for timeMode changed from cpu to elapsed Problem is infeasible - 0.00 seconds Option for printingOptions changed from normal to all Total time (CPU seconds): 0.01 (Wallclock seconds): 0.01 Status: Infeasible Choice_1_1 = 0.0 Choice_1_2 = 0.0 Choice_1_3 = 0.0 Choice_1_4 = 0.0 Choice_2_1 = 0.0 Choice_2_2 = 0.0 Choice_2_3 = 0.0 Choice_2_4 = 0.0 Choice_3_1 = 0.0 Choice_3_2 = 0.0 Choice_3_3 = 0.0 Choice_3_4 = 0.0 Choice_4_1 = 0.0 Choice_4_2 = 0.0 Choice_4_3 = 0.0 Choice_4_4 = 0.0 Choice_5_1 = 0.0 Choice_5_2 = 0.0 Choice_5_3 = 0.0 Choice_5_4 = 0.0 Process finished with exit code 0 </code></pre> <p>I was expecting a list of variables a bit like this, with a possible solution:</p> <pre><code>Status: Optimal Choice_1_1 = 1.0 Choice_1_2 = 1.0 Choice_1_3 = 0.0 Choice_1_4 = 0.0 Choice_2_1 = 0.0 Choice_2_2 = 0.0 Choice_2_3 = 0.0 Choice_2_4 = 0.0 Choice_3_1 = 0.0 Choice_3_2 = 0.0 Choice_3_3 = 0.0 Choice_3_4 = 0.0 Choice_4_1 = 0.0 Choice_4_2 = 0.0 Choice_4_3 = 0.0 Choice_4_4 = 0.0 Choice_5_1 = 0.0 Choice_5_2 = 0.0 Choice_5_3 = 0.0 Choice_5_4 = 0.0 </code></pre> <p>Edits: Many thanks AirSquid for pointing me in the right direction. I'm still struggling with big M constraints.</p> <p>I tried this:</p> <pre><code>import pulp as Pulp ROWS = range(1, 6) COLS = range(1,5) prob = Pulp.LpProblem(&quot;Fewestcolumns&quot;, Pulp.LpMaximize) choices = Pulp.LpVariable.dicts(&quot;Choice&quot;, (ROWS, COLS), cat=&quot;Integer&quot;, lowBound=0, upBound=1) used = Pulp.LpVariable.dicts(&quot;used&quot;, COLS, cat=&quot;Binary&quot;) b = Pulp.LpVariable.dicts(&quot;b&quot;, COLS, cat=&quot;Binary&quot;) prob += Pulp.lpSum([choices[row][col] for row in ROWS for col in COLS]) for rows, items in choices.items(): prob += Pulp.lpSum(cols for cols in items.values()) == 1 M = 20 for col in COLS: prob += b[col] &gt;= (Pulp.lpSum([choices[row][col] for row in ROWS]) - 1) / M prob += used[col] &gt;= M * (b[col] - 1) prob += Pulp.lpSum([used[col] for col in COLS]) == 2 prob.solve() print(&quot;Status:&quot;, Pulp.LpStatus[prob.status]) for v in prob.variables(): print(v.name, &quot;=&quot;, v.varValue) </code></pre> <p>I got the following results:</p> <pre><code> Result - Optimal solution found Objective value: 5.00000000 Enumerated nodes: 0 Total iterations: 0 Time (CPU seconds): 0.00 Time (Wallclock seconds): 0.00 Option for printingOptions changed from normal to all Total time (CPU seconds): 0.01 (Wallclock seconds): 0.02 Status: Optimal Choice_1_1 = 0.0 Choice_1_2 = 0.0 Choice_1_3 = 0.0 Choice_1_4 = 1.0 Choice_2_1 = 0.0 Choice_2_2 = 0.0 Choice_2_3 = 0.0 Choice_2_4 = 1.0 Choice_3_1 = 0.0 Choice_3_2 = 0.0 Choice_3_3 = 0.0 Choice_3_4 = 1.0 Choice_4_1 = 0.0 Choice_4_2 = 0.0 Choice_4_3 = 0.0 Choice_4_4 = 1.0 Choice_5_1 = 0.0 Choice_5_2 = 0.0 Choice_5_3 = 0.0 Choice_5_4 = 1.0 b_1 = 1.0 b_2 = 1.0 b_3 = 1.0 b_4 = 1.0 used_1 = 1.0 used_2 = 1.0 used_3 = 0.0 used_4 = 0.0 Process finished with exit code 0 </code></pre> <p>Not sure what I did wrong - I was hoping for some 1.0s in columns that aren't column 4. Any more hints please?</p>
[ { "answer_id": 74559238, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 3, "selected": true, "text": "output for output <- c()\nfor(i in codes){\n output[i] <- paste0(\"repetitivetext\",i)\n }\n paste0 output paste0(\"beginning\", output, ,\"end\")\n[1] \"beginningrepetitivetextcode1end\" \"beginningrepetitivetextcode2end\" \"beginningrepetitivetextcode3end\"\n collapse paste0(\"beginning\",output,\"end\", collapse = \"\")\n[1] \"beginningrepetitivetextcode1endbeginningrepetitivetextcode2endbeginningrepetitivetextcode3end\"\n codes<-c(\"code1\", \"code2\",\"code3\")\n" }, { "answer_id": 74559312, "author": "I_O ", "author_id": 20513099, "author_profile": "https://Stackoverflow.com/users/20513099", "pm_score": 1, "selected": false, "text": "collapse paste0('beginning',\n paste0('repetitivetext', codes, collapse = ''),\n 'end'\n)\n ## [1] \"beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end\"\n" }, { "answer_id": 74559343, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "for codes <- c(\"code1\", \"code2\", \"code3\")\ncodes2 <- paste0(\"repetitivetext\", codes)\nprint(codes2)\n [1] \"repetitivetextcode1\" \"repetitivetextcode2\" \"repetitivetextcode3\"\n paste0(\"beginning\", \n paste0(codes2, collapse = \"\"), \n \"end\"\n)\n [1] \"beginningrepetitivetextcode1repetitivetextcode2repetitivetextcode3end\"\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589625/" ]
74,559,279
<p>I've been recently working on my own developed home-page, and have some difficulties aligning my items in a flexbox. First flexbox should have three (3) pictures, and all of them should be positioned in one vertical line under each other.</p> <p>This also counts for my second flexbox.</p> <p>Here's my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.flexcontainer-1 { display: flex; justify-content: flex-start; align-items: left; height: auto; width: auto; } .flexcontainer-2 { display: flex; justify-content: flex-end; align-items: right; height: auto; width: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flexcontainer-1"&gt; &lt;!-- Übersicht über alle Immobilien mit entsprechenden Bildern --&gt; &lt;h4&gt;Unsere Immobilien&lt;/h4&gt; &lt;!-- Weiterleitung über Anchor innerhalb des Images zu Einzelbeschreibung, --&gt; &lt;!-- Übergabe der ID aus Datenbank in den Anchor --&gt; &lt;p&gt; &lt;a href="db_immobilien_desc_b.php?id=2"&gt; &lt;img src="../images/haus2.jpg" alt="Beschreibung Haus2"&gt;&lt;/a&gt; &lt;/p&gt; &lt;p&gt; &lt;a href="db_immobilien_desc_b.php?id=3"&gt; &lt;img src="../images/haus3.jpg" alt="Beschreibung Haus3"&gt;&lt;/a&gt; &lt;/p&gt; &lt;p&gt; &lt;a href="db_immobilien_desc_b.php?id=4"&gt; &lt;img src="../images/haus4.jpg" alt="Beschreibung Haus4"&gt;&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="flexcontainer-2"&gt; &lt;p&gt; &lt;a href="db_immobilien_desc_b.php?id=5"&gt; &lt;img src="../images/haus5.jpg" alt="Beschreibung Haus5"&gt;&lt;/a&gt; &lt;/p&gt; &lt;p&gt; &lt;a href="db_immobilien_desc_b.php?id=6"&gt; &lt;img src="../images/haus6.jpg" alt="Beschreibung Haus6"&gt;&lt;/a&gt; &lt;/p&gt; &lt;p&gt; &lt;a href="db_immobilien_desc_b.php?id=7"&gt; &lt;img src="../images/haus7.jpg" alt="Beschreibung Haus6"&gt;&lt;/a&gt; &lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="https://i.stack.imgur.com/YO1sU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YO1sU.png"></a></p> <p>It always creates a gap in the second alignment of pictures and unfortunately I have not found a solution to fix this.</p> <p>I really appreciate tips or advice, how I can improve my coding.</p> <p>Thank you very much in advance.</p> <p>Kind Regards,</p> <p>Lukas</p> <p>I've tried playing around with property <code>justifiy-content</code> and <code>align-items</code>, but that did not work out for me.</p>
[ { "answer_id": 74559439, "author": "superdunck", "author_id": 15721671, "author_profile": "https://Stackoverflow.com/users/15721671", "pm_score": 1, "selected": true, "text": "h4 flexcontainer-1 .container {\n display: flex;\n gap:10px;\n}\n\n.item {\n height: 50px;\n width: 100px;\n background-color: blue\n}\n\n.box {\n display: flex;\n flex-direction: column;\n gap: 10px\n} <div class=\"container\">\n <div class=\"box\">\n <div class=\"item\">House 1</div>\n <div class=\"item\">House 2</div>\n <div class=\"item\">House 3</div>\n </div>\n <div class=\"box\">\n <div class=\"item\">House 4</div>\n <div class=\"item\">House 5</div>\n <div class=\"item\">House 6</div>\n </div>\n</div> p img" }, { "answer_id": 74561706, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 2, "selected": false, "text": "<figure> <main> <section> <article> <main>\n <h4>Unsere Immobilien</h4>\n <ul>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus2\">\n </a>\n <figcaption>PlaceKitten image: 1</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus3\">\n </a>\n <figcaption>PlaceKitten image: 2</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus4\">\n </a>\n <figcaption>PlaceKitten image: 3</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus5\">\n </a>\n <figcaption>PlaceKitten image: 4</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 5</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 6</figcaption>\n </figure>\n </li>\n </ul>\n</main>\n /* CSS custom properties used to provide common theming\n to multiple elements: */\n:root {\n --commonSpacing: 1em;\n}\n\n/* a simple CSS reset to remove default margins,\n and padding; ensuring all browsers use the\n same sizing algorithm for content, and also\n applying the same font-size and font-family: */\n*,\n ::before,\n ::after {\n box-sizing: border-box;\n font-family: system-ui;\n font-size: 16px;\n margin: 0;\n padding: 0;\n}\n\n/* to emphasise the heading: */\nh4 {\n font-size: 1.8em;\n margin-block: calc(0.5 * var(--commonSpacing));\n text-align: center;\n}\n\nmain {\n /* setting the size of the inline axis (width, in English and\n Latin languages) to 80 viewport width units, with a minimum\n size of 30 root-em units, and a maximum size of 1300 pixels: */\n inline-size: clamp(30rem, 80vw, 1300px);\n /* centering the element on the inline axis: */\n margin-inline: auto;\n}\n\nul {\n /* using multi-column layout,\n ensuring two columns: */\n column-count: 2;\n /* removing default list-markers: */\n list-style-type: none;\n /* centering the <figure> elements\n within the <li>: */\n text-align: center;\n}\n\nli {\n /* ensuring that the <li> doesn't have\n its contents spread over columns,\n leaving unsightly orphans at the\n end, or beginning, of a column: */\n break-inside: avoid;\n /* spacing the elements out: */\n margin-block-end: var(--commonSpacing);\n} <main>\n <h4>Unsere Immobilien</h4>\n <ul>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus2\">\n </a>\n <figcaption>PlaceKitten image: 1</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus3\">\n </a>\n <figcaption>PlaceKitten image: 2</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus4\">\n </a>\n <figcaption>PlaceKitten image: 3</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus5\">\n </a>\n <figcaption>PlaceKitten image: 4</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 5</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 6</figcaption>\n </figure>\n </li>\n </ul>\n</main> /* CSS custom properties used to provide common theming\n to multiple elements: */\n:root {\n --commonSpacing: 1em;\n}\n\n\n/* a simple CSS reset to remove default margins,\n and padding; ensuring all browsers use the\n same sizing algorithm for content, and also\n applying the same font-size and font-family: */\n*,\n::before,\n::after {\n box-sizing: border-box;\n font-family: system-ui;\n font-size: 16px;\n margin: 0;\n padding: 0;\n}\n\nmain {\n /* setting the size of the inline axis (width, in English and\n Latin languages) to 80 viewport width units, with a minimum\n size of 30 root-em units, and a maximum size of 1300 pixels: */\n inline-size: clamp(30rem, 80vw, 1300px);\n /* centering the element on the inline axis: */\n margin-inline: auto;\n}\n\n\n/* to emphasise the heading: */\nh4 {\n font-size: 1.8em;\n margin-block: calc(0.5 * var(--commonSpacing));\n text-align: center;\n}\n\nul {\n /* using grid layout: */\n display: grid;\n /* spacing adjacent elements: */\n gap: var(--commonSpacing);\n /* defining two columns, each taking one fraction of\n the available space:*/\n grid-template-columns: repeat(2, 1fr);\n list-style-type: none;\n text-align: center;\n} <main>\n <h4>Unsere Immobilien</h4>\n <ul>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus2\">\n </a>\n <figcaption>PlaceKitten image: 1</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus3\">\n </a>\n <figcaption>PlaceKitten image: 2</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus4\">\n </a>\n <figcaption>PlaceKitten image: 3</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus5\">\n </a>\n <figcaption>PlaceKitten image: 4</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 5</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 6</figcaption>\n </figure>\n </li>\n </ul>\n</main> /* CSS custom properties used to provide common theming\n to multiple elements: */\n:root {\n --commonSpacing: 1em;\n}\n\n\n/* a simple CSS reset to remove default margins,\n and padding; ensuring all browsers use the\n same sizing algorithm for content, and also\n applying the same font-size and font-family: */\n*,\n::before,\n::after {\n box-sizing: border-box;\n font-family: system-ui;\n font-size: 16px;\n margin: 0;\n padding: 0;\n}\n\nmain {\n /* setting the size of the inline axis (width, in English and\n Latin languages) to 80 viewport width units, with a minimum\n size of 30 root-em units, and a maximum size of 1300 pixels: */\n inline-size: clamp(30rem, 80vw, 1300px);\n /* centering the element on the inline axis: */\n margin-inline: auto;\n}\n\n\n/* to emphasise the heading: */\nh4 {\n font-size: 1.8em;\n margin-block: calc(0.5 * var(--commonSpacing));\n text-align: center;\n}\n\nul {\n /* using flexbox layout: */\n display: flex;\n /* shorthand for:\n flex-direction: row;\n flex-wrap: wrap; */\n flex-flow: row wrap;\n /* setting a gap between adjacent elements: */\n gap: var(--commonSpacing);\n /* removing default list-markers: */\n list-style-type: none;\n}\n\nli {\n /* allowomg the <li> to expand to take up\n more room: */\n flex-grow: 1;\n /* setting the size of the element to be\n 45% of that of the parent; flex-basis\n always refers to the inline-axis of flex-items,\n which can be modified by updating the\n flex-direction of the parent: */\n flex-basis: 45%;\n /* centering the content within the <li>: */\n text-align: center;\n} <main>\n <h4>Unsere Immobilien</h4>\n <ul>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus2\">\n </a>\n <figcaption>PlaceKitten image: 1</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus3\">\n </a>\n <figcaption>PlaceKitten image: 2</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus4\">\n </a>\n <figcaption>PlaceKitten image: 3</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus5\">\n </a>\n <figcaption>PlaceKitten image: 4</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 5</figcaption>\n </figure>\n </li>\n <li>\n <figure>\n <a href=\"#\">\n <img src=\"//placekitten.com/300/200\" alt=\"Beschreibung Haus6\">\n </a>\n <figcaption>PlaceKitten image: 6</figcaption>\n </figure>\n </li>\n </ul>\n</main> box-sizing break-inside clamp() column-count display flex-basis flex-direction flex-grow flex-flow flex-wrap gap grid-template-columns inline-size list-style-type margin-block margin-inline repeat() text-align var()" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589730/" ]
74,559,336
<p>I want to make sure that the receiving data is a valid timestamp. is there a way to make sure starts_at and expired_at fields are timestamps?</p> <pre><code>$rules = [ 'user_id' =&gt; 'required|int|exists:users,id', 'starts_at' =&gt; 'required|int|min:1', 'expires_at' =&gt; 'required|int|gt:starts_at', ]; </code></pre>
[ { "answer_id": 74559474, "author": "Lokendra Singh Panwar", "author_id": 5602878, "author_profile": "https://Stackoverflow.com/users/5602878", "pm_score": -1, "selected": false, "text": "AppServiceProvider class AppServiceProvider extends ServiceProvider \n{\n public function boot()\n {\n Validator::extend('new-format', function($attribute, $value, $formats) {\n\n foreach($formats as $format) {\n\n $parsed = date_parse_from_format($format, $value);\n\n // validation success\n if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {\n return true;\n }\n }\n\n // validation failed\n return false;\n });\n }\n}\n 'starts_at' => 'new-format:\"Y-m-d H:i:s.u\",\"Y-m-d\"'" }, { "answer_id": 74560052, "author": "xenooooo", "author_id": 20283630, "author_profile": "https://Stackoverflow.com/users/20283630", "pm_score": -1, "selected": false, "text": "date before after $rule = [\n 'starts_at' => 'date',\n 'expired_at' => 'date|after:starts_at',\n]\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19128775/" ]
74,559,363
<p>Just trying to add authentication to my NuxtJs 3 app folloging <code>nuxt/auth</code> <a href="https://auth.nuxtjs.org/guide/setup#installation" rel="nofollow noreferrer">configuration docs</a>, but still get an error during app start:</p> <p><a href="https://i.stack.imgur.com/XFaWE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XFaWE.png" alt="enter image description here" /></a></p> <pre class="lang-js prettyprint-override"><code>// nuxt.config.js export default defineNuxtConfig({ auth: { // ... }, modules: [ // '@nuxtjs/axios', '@nuxtjs/auth-next' ], }) </code></pre> <p>Received same error for <code>@nuxtjs/axios</code> but I just commented it out since its official <a href="https://axios.nuxtjs.org/" rel="nofollow noreferrer">documentation</a> indicates to switch to <a href="https://v3.nuxtjs.org/getting-started/data-fetching/#usefetch" rel="nofollow noreferrer"><code>$fetch API</code></a>.</p> <p>Cannot figure out where the error is</p>
[ { "answer_id": 74559670, "author": "Tristan", "author_id": 13001005, "author_profile": "https://Stackoverflow.com/users/13001005", "pm_score": 1, "selected": false, "text": "nuxt/auth" }, { "answer_id": 74559673, "author": "kissu", "author_id": 8816585, "author_profile": "https://Stackoverflow.com/users/8816585", "pm_score": 3, "selected": true, "text": "nuxt-auth" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3030926/" ]
74,559,371
<p>I have N div of the same fixed size (both width and height). I want to display them in lines with a fixed sapcing vetween each other. I N elements do not fit in one line, creates another line. It would look like this:<a href="https://i.stack.imgur.com/A5zmj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A5zmj.png" alt="one line display with line return" /></a></p> <p>I tried with <code>display flex</code> but it does not go to a new line. I tried with grid but the number of columns depends on how many items can fit in the width.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code> .item{ width: 300px; height: 400px; background-color: grey; margin: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;h1&gt;Aleno&lt;/h1&gt; &lt;div style="display: flex;" &gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74559412, "author": "Moussa Bistami", "author_id": 15628525, "author_profile": "https://Stackoverflow.com/users/15628525", "pm_score": 3, "selected": true, "text": "flex-wrap flex-wrap: wrap;\n" }, { "answer_id": 74559505, "author": "Muhammad Tahir Ali", "author_id": 14988695, "author_profile": "https://Stackoverflow.com/users/14988695", "pm_score": 0, "selected": false, "text": "flex-wrap: wrap;" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12065403/" ]
74,559,378
<p>I have a multi-module project and I want to add another dependency automatically if a submodule contains a specific dependency.</p> <p>So far I've added this on my root <code>build.gradle.kts</code></p> <pre><code>subprojects { apply { plugin(&quot;java&quot;) } project.configurations.implementation.get().allDependencies.forEach { println(it.name) } } </code></pre> <p>But it prints nothing. How can I get all dependencies implemented by a subproject and then another if it contains one already?</p> <p>Thanks</p>
[ { "answer_id": 74667684, "author": "pizzamanyes", "author_id": 20670513, "author_profile": "https://Stackoverflow.com/users/20670513", "pm_score": -1, "selected": false, "text": "subprojects {\n apply {\n plugin(\"java\")\n }\n\n project.configurations.implementation.get().allDependencies.forEach {\n if (it.name == \"specific-dependency\") {\n // Add another dependency here\n dependencies {\n implementation(\"com.example:another-dependency:1.0.0\")\n }\n }\n }\n}\n" }, { "answer_id": 74668947, "author": "Begging", "author_id": 16606223, "author_profile": "https://Stackoverflow.com/users/16606223", "pm_score": 1, "selected": false, "text": "afterEvaluate subprojects {\n apply {\n plugin(\"java\")\n }\n\n afterEvaluate {\n project.configurations.implementation.get().getDependencies().forEach {\n println(it.name)\n // Check if the dependency is the one you're looking for\n // and add another dependency if needed\n }\n }\n}\n\n" }, { "answer_id": 74669413, "author": "thatthing", "author_id": 624493, "author_profile": "https://Stackoverflow.com/users/624493", "pm_score": 0, "selected": false, "text": "getDependencies() Configuration class contains() subprojects {\napply {\n plugin(\"java\")\n}\n\nval implementationDependencies = project.configurations.implementation.get().getDependencies()\nimplementationDependencies.forEach {\n println(it.name)\n\n // Check if a specific dependency is present\n if (it.name == \"your-dependency-name\") {\n // Add another dependency if the specific one is present\n project.dependencies {\n implementation(\"org.another.dependency:1.0.0\")\n }\n }\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18232723/" ]
74,559,428
<p>I need to process a zip file(that contains a text file) using task groups in airflow. No. of lines can vary from 1 to 50 Million. I want to read the text file in the zip file process each line and write the processed line to another text file, zip it, update Postgres tables and call another DAG to transmit this new zip file to an SFTP server.</p> <p>Since a single task can take more time to process a file with millions of lines, I would like to process the file using a task group. That is, a single task in the task group can process certain no. of lines and transform them. For ex. if we receive a file with 15 Million lines, 6 task groups can be called to process 2.5 Million lines each.</p> <p>But I am confused how to make the task group dynamic and pass the offset to each task. Below is a sample that I tried with fixed offset in islice(),</p> <pre><code>def start_task(**context): print(&quot;starting the Main task...&quot;) def apply_transformation(line): return f&quot;{line}_NEW&quot; def task1(**context): data = context['dag_run'].conf file_name = data.get(&quot;file_name&quot;) with zipfile.ZipFile(file_name) as zf: for name in zf.namelist(): with io.TextIOWrapper(zf.open(name), encoding=&quot;UTF-8&quot;) as fp: for record in islice(fp, 1, 2000000): apply_transformation(record) def task2(**context): data = context['dag_run'].conf file_name = data.get(&quot;file_name&quot;) with zipfile.ZipFile(file_name) as zf: for name in zf.namelist(): with io.TextIOWrapper(zf.open(name), encoding=&quot;UTF-8&quot;) as fp: for record in islice(fp, 2000001, 4000000): apply_transformation(record) def task3(**context): data = context['dag_run'].conf file_name = data.get(&quot;file_name&quot;) with zipfile.ZipFile(file_name) as zf: for name in zf.namelist(): with io.TextIOWrapper(zf.open(name), encoding=&quot;UTF-8&quot;) as fp: for record in islice(fp, 4000001, 6000000): apply_transformation(record) def task4(**context): data = context['dag_run'].conf file_name = data.get(&quot;file_name&quot;) with zipfile.ZipFile(file_name) as zf: for name in zf.namelist(): with io.TextIOWrapper(zf.open(name), encoding=&quot;UTF-8&quot;) as fp: for record in islice(fp, 6000001, 8000000): apply_transformation(record) def task5(**context): data = context['dag_run'].conf file_name = data.get(&quot;file_name&quot;) with zipfile.ZipFile(file_name) as zf: for name in zf.namelist(): with io.TextIOWrapper(zf.open(name), encoding=&quot;UTF-8&quot;) as fp: for record in islice(fp, 8000001, 10000000): apply_transformation(record) def final_task(**context): print(&quot;This is the final task to update postgres tables and call SFTP DAG...&quot;) with DAG(&quot;main&quot;, schedule_interval=None, default_args=default_args, catchup=False) as dag: st = PythonOperator( task_id='start_task', dag=dag, python_callable=start_task ) with TaskGroup(group_id='task_group_1') as tg1: t1 = PythonOperator( task_id='task1', python_callable=task1, dag=dag, ) t2 = PythonOperator( task_id='task2', python_callable=task2, dag=dag, ) t3 = PythonOperator( task_id='task3', python_callable=task3, dag=dag, ) t4 = PythonOperator( task_id='task4', python_callable=task4, dag=dag, ) t5 = PythonOperator( task_id='task5', python_callable=task5, dag=dag, ) ft = PythonOperator( task_id='final_task', dag=dag, python_callable=final_task ) st &gt;&gt; tg1 &gt;&gt; ft </code></pre> <p>After applying transformation to each line, I want to get these transformed lines from different tasks and merge them into a new file and do rest of the operations in the <code>final_task</code>.</p> <p>Or are there any other methods to process large files with millions of lines in parallel?</p>
[ { "answer_id": 74678876, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "def process_lines(**context):\n # Read the parameters passed to the operator\n data = context['dag_run'].conf\n file_name = data.get(\"file_name\")\n offset = data.get(\"offset\")\n num_lines = data.get(\"num_lines\")\n\n # Open the zip file and read the text file\n with zipfile.ZipFile(file_name) as zf:\n for name in zf.namelist():\n with io.TextIOWrapper(zf.open(name), encoding=\"UTF-8\") as fp:\n # Read the lines from the specified offset and process them\n for record in islice(fp, offset, offset + num_lines):\n apply_transformation(record)\n\n\nwith DAG(\"main\",\n schedule_interval=None,\n default_args=default_args, catchup=False) as dag:\n\n st = PythonOperator(\n task_id='start_task',\n dag=dag,\n python_callable=start_task\n )\n\n with TaskGroup(group_id='task_group_1') as tg1:\n # Call the process_lines operator with the appropriate offset and number of lines to process\n t1 = PythonOperator(\n task_id='task1',\n python_callable=process_lines,\n dag=dag,\n op_kwargs={\"offset\": 1, \"num_lines\": 2000000}\n )\n t2 = PythonOperator(\n task_id='task2',\n python_callable=process_lines,\n dag=dag,\n op_kwargs={\"offset\": 2000001, \"num_lines\": 2000000}\n )\n t3 = PythonOperator(\n task_id='task3',\n python_callable=process_lines,\n dag=dag,\n op_kwargs={\"offset\": 4000001, \"num_lines\": 2000000}\n )\n # Add other tasks to the task group in a similar way\n\n # Add dependencies between the tasks in the task group\n tg1 >> final_task\n" }, { "answer_id": 74681054, "author": "Boatti", "author_id": 19192614, "author_profile": "https://Stackoverflow.com/users/19192614", "pm_score": -1, "selected": false, "text": "def calculate_offsets(task_id, num_tasks, num_lines):\n chunk_size = num_lines // num_tasks\n start_offset = (task_id - 1) * chunk_size\n end_offset = task_id * chunk_size\n if task_id == num_tasks:\n end_offset = num_lines\n return start_offset, end_offset\n def apply_transformation(start_offset, end_offset, file_name):\n with zipfile.ZipFile(file_name) as zf:\n for name in zf.namelist():\n with io.TextIOWrapper(zf.open(name), encoding=\"UTF-8\") as fp:\n for record in islice(fp, start_offset, end_offset):\n # Apply the transformation here and write the result to a new file\n def task1(**context):\n data = context['dag_run'].conf\n file_name = data.get(\"file_name\")\n num_lines = data.get(\"num_lines\")\n start_offset, end_offset = calculate_offsets(1, 6, num_lines)\n apply_transformation(start_offset, end_offset, file_name)\n\ndef task2(**context):\n data = context['dag_run'].conf\n file_name = data.get(\"file_name\")\n num_lines = data.get(\"num_lines\")\n start_offset, end_offset = calculate_offsets(2, 6, num_lines)\n apply_transformation(start_offset, end_offset, file_name)\n\n# Define the other tasks in the same way\nOnce you have defined the tasks, you can call them in the task group and pass the necessary parameters to them. For example:\n\nCopy code\nwith DAG(\"main\",\n schedule_interval=None,\n default_args=default_args, catchup=False) as dag:\n\n st = PythonOperator(\n task_id='start_task',\n dag=dag,\n python_callable=start_task\n )\n\n with TaskGroup(group_id='task_group_1') as tg1:\n t1 = PythonOperator(\n task_id='task1',\n python_callable=task1,\n dag=dag,\n op_kwargs={'file_name': '{{ dag_run.conf.file_name }}',\n 'num_lines': '{{ dag_run.conf.num_lines }}'}\n )\n\n t2 = PythonOperator(\n task_id='task2',\n python_callable=task2,\n dag=dag,\n op_kwargs={'file_name': '{{ dag_run.conf.file_name }}',\n 'num_lines': '{{ dag_run.conf.num_lines }}'}\n )\n\n # Call the other tasks in the same way\n\n ft = PythonOperator(\n task_id='final_task',\n dag=dag,\n python_callable=final_task\n )\n\n st >> tg1 >> ft\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516217/" ]
74,559,440
<p>The program should return edit text, where you have to replace&quot; - &quot;, &quot;: &quot;, &quot;; &quot;, &quot;, &quot;, &quot; &quot; with &quot;\t&quot;.</p> <p>The problem here is the result</p> <pre><code>Input: Китай: 1405023000; 24.08.2020; 17.99% Expected Китай 1405023000 24.08.2020 17.99% Myne Китай: 1405023000; 24.08.2020; 17.99% </code></pre> <p>So for some reason, I believe he messing with the order of `stringSeparators` elements or what. I am interested in this moment</p> <pre><code>public static string ReplaceIncorrectSeparators(string text) { string populationEdited = &quot;&quot;; string[] stringSeparators = new string[] {&quot; - &quot;, &quot;: &quot;, &quot;; &quot;, &quot;, &quot;, &quot; &quot;}; for (int i = 0; i &lt; stringSeparators.Length; i++) { populationEdited = text.Replace(stringSeparators[i], &quot;\t&quot;); } return populationEdited; } </code></pre> <p>I've already solved the problem in another way but I want to solve it with separators.</p>
[ { "answer_id": 74559510, "author": "Sergey Kudriavtsev", "author_id": 625594, "author_profile": "https://Stackoverflow.com/users/625594", "pm_score": 3, "selected": true, "text": "Replace public static string ReplaceIncorrectSeparators(string text)\n{\n string populationEdited = text; // You need to start with the original\n string[] stringSeparators = new string[] {\" - \", \": \", \"; \", \", \", \" \"};\n for (int i = 0; i < stringSeparators.Length; i++)\n {\n // And here instead of text.Replace you do populationEdited.Replace\n populationEdited = populationEdited.Replace(stringSeparators[i], \"\\t\");\n }\n\n return populationEdited;\n}\n" }, { "answer_id": 74559658, "author": "netblognet", "author_id": 251719, "author_profile": "https://Stackoverflow.com/users/251719", "pm_score": 1, "selected": false, "text": "public static string ReplaceIncorrectSeparators(string text)\n{\n Regex regex = new Regex(@\" - |: |; |, | \");\n return regex.Replace(text, \"\\t\");\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20138135/" ]
74,559,450
<p>I have a program where i'm required to seperate as much out as possible as different methods and classes.</p> <p>I have a rng, thats a class. I want to use the output from the rng in another class to compare it against a user selection to decide if they win or lose.</p> <p>This is my rng.</p> <pre><code>package stockGame; import javax.swing.JOptionPane; // Import this just in case I need a popup window import java.util.Random; // Import this so i can use the random number //The purpose of this class is to generate a random number between 1 and 12 public class Dice { public static void Dice(){ Random random = new Random (); JOptionPane.showMessageDialog(null,&quot;The Computer picked &quot; + (random.nextInt(12)+1)); } } </code></pre> <p>Here is my if loop in the second class. I want to be able to say. If (option ==1 AND RNG is GREATER/LESS/EQUAL to 6){ That way it can compare and decide if the user has won or lost.</p> <pre><code>if (option ==1){ output = &quot;You chose to trade less than £6 and the computer rolled RNG, so you win/lose,&quot;; JOptionPane.showMessageDialog(null, output, &quot;The Message&quot;, JOptionPane.INFORMATION_MESSAGE); } if (option ==2){ output = &quot;You chose to trade more than £6&quot;; JOptionPane.showMessageDialog(null, output, &quot;The Message&quot;, JOptionPane.INFORMATION_MESSAGE); } if (option==3){ output = &quot;You chose to trade exactly £6&quot;; JOptionPane.showMessageDialog(null, output, &quot;The Message&quot;, JOptionPane.INFORMATION_MESSAGE); } </code></pre> <p>Hoping to get the ouput generated from RNG class to be used in another class</p>
[ { "answer_id": 74559510, "author": "Sergey Kudriavtsev", "author_id": 625594, "author_profile": "https://Stackoverflow.com/users/625594", "pm_score": 3, "selected": true, "text": "Replace public static string ReplaceIncorrectSeparators(string text)\n{\n string populationEdited = text; // You need to start with the original\n string[] stringSeparators = new string[] {\" - \", \": \", \"; \", \", \", \" \"};\n for (int i = 0; i < stringSeparators.Length; i++)\n {\n // And here instead of text.Replace you do populationEdited.Replace\n populationEdited = populationEdited.Replace(stringSeparators[i], \"\\t\");\n }\n\n return populationEdited;\n}\n" }, { "answer_id": 74559658, "author": "netblognet", "author_id": 251719, "author_profile": "https://Stackoverflow.com/users/251719", "pm_score": 1, "selected": false, "text": "public static string ReplaceIncorrectSeparators(string text)\n{\n Regex regex = new Regex(@\" - |: |; |, | \");\n return regex.Replace(text, \"\\t\");\n}\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15765957/" ]
74,559,457
<p>I'm using a cached network image to load in an image from firebase and if the image is URL is null it loads a circle avatar with an icon in it.</p> <p>It does not work fine in the emulator</p> <p>Exception has occurred. ArgumentError (Invalid argument(s): No host specified in URI ) Here's The Code</p> <pre><code>class ProfileScreen extends StatefulWidget { final String uid; const ProfileScreen({ Key? key, required this.uid, }) : super(key: key); @override State&lt;ProfileScreen&gt; createState() =&gt; _ProfileScreenState(); } class _ProfileScreenState extends State&lt;ProfileScreen&gt; { final ProfileController profileController = Get.put(ProfileController()); @override void initState() { super.initState(); profileController.updateUserId(widget.uid); } @override Widget build(BuildContext context) { return GetBuilder&lt;ProfileController&gt;( init: ProfileController(), builder: (controller) { if (controller.user.isEmpty) { return const Center( child: CircularProgressIndicator(), ); } return Scaffold( appBar: AppBar( backgroundColor: Colors.black12, leading: const Icon( Icons.person_add_alt_1_outlined, ), actions: const [ Icon(Icons.more_horiz), ], title: Text( controller.user['name']??&quot;&quot;, style: const TextStyle( fontWeight: FontWeight.bold, color: Colors.white, ), ), ), body: SafeArea( child: SingleChildScrollView( child: Column( children: [ SizedBox( child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ClipOval( child: CachedNetworkImage( fit: BoxFit.cover, imageUrl: controller.user['profilePhoto']??&quot;&quot;, height: 100, width: 100, placeholder: (context, url) =&gt; const CircularProgressIndicator(), errorWidget: (context, url, error) =&gt; const Icon( Icons.error, ), ), ) ], ), const SizedBox( height: 15, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ Text( controller.user['following'], style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 5), const Text( 'Following', style: TextStyle( fontSize: 14, ), ), ], ), Container( color: Colors.black54, width: 1, height: 15, margin: const EdgeInsets.symmetric( horizontal: 15, ), ), Column( children: [ Text( controller.user['followers'], style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 5), const Text( 'Followers', style: TextStyle( fontSize: 14, ), ), ], ), Container( color: Colors.black54, width: 1, height: 15, margin: const EdgeInsets.symmetric( horizontal: 15, ), ), Column( children: [ Text( controller.user['likes'], style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 5), const Text( 'Likes', style: TextStyle( fontSize: 14, ), ), ], ), ], ), const SizedBox( height: 15, ), Container( width: 140, height: 47, decoration: BoxDecoration( border: Border.all( color: Colors.black12, ), ), child: Center( child: InkWell( onTap: () { if (widget.uid == authController.user?.uid) { authController.signOut(); } else { controller.followUser(); } }, child: Text( widget.uid == authController.user?.uid ? 'Sign Out' : controller.user['isFollowing'] ? 'Unfollow' : 'Follow', style: const TextStyle( fontSize: 15, fontWeight: FontWeight.bold, ), ), ), ), ), const SizedBox( height: 25, ), // video list GridView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: controller.user['thumbnails'].length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 1, crossAxisSpacing: 5, ), itemBuilder: (context, index) { String thumbnail = controller.user['thumbnails'][index]; return CachedNetworkImage( imageUrl: thumbnail, fit: BoxFit.cover, ); }, ) ], ), ), ], ), ), ), ); }); } } </code></pre> <p>[enter image description here][1] [1]: https://i.stack.imgur.com/IScNW.png</p> <p>What I can do to fix this error</p>
[ { "answer_id": 74559497, "author": "VincentDR", "author_id": 19540575, "author_profile": "https://Stackoverflow.com/users/19540575", "pm_score": 0, "selected": false, "text": " CachedNetworkImage(\n ...\n imageUrl: controller.user['profilePhoto']??\"\",\n ...\n ),\n" }, { "answer_id": 74559513, "author": "Siddharth Mehra", "author_id": 16985146, "author_profile": "https://Stackoverflow.com/users/16985146", "pm_score": 1, "selected": false, "text": "controller.user['profilePhoto'] CachedNetworkImage(\n fit: BoxFit.cover,\n imageUrl: controller.user['profilePhoto']??\"\",\n height: 100,\n width: 100,\n placeholder: (context, url) =>\n const CircularProgressIndicator(),\n errorWidget: (context, url, error) =>\n const Icon(\n Icons.error,\n ),\n ),\n controller.user['profilePhoto']==null?\n const Icon(\n Icons.error,\n ):\n CachedNetworkImage(\n fit: BoxFit.cover,\n imageUrl: controller.user['profilePhoto'],\n height: 100,\n width: 100,\n placeholder: (context, url) =>\n const CircularProgressIndicator(),\n errorWidget: (context, url, error) =>\n const Icon(\n Icons.error,\n ),\n ),\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20547259/" ]
74,559,544
<p>I am using <a href="https://pub.dev/packages/pin_code_fields" rel="nofollow noreferrer">PinCodeTextField</a> plugin to verify PIN in Flutter, After failure validation I am trying to clear PinCodeTextField values through controller using pinLoginController.clear().</p> <pre><code>class LoginPage extends State&lt;LoginWithPin&gt; { //Your code here @override Widget build(BuildContext context) { TextEditingController? pinLoginController = new TextEditingController(); final String requiredPIN = &quot;&quot;; String _title = '4.0'; return MaterialApp( debugShowCheckedModeBanner: false, title: &quot;4.0&quot;, home: Scaffold( appBar: AppBar(title: Text(_title)), body: Center( child: Padding( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Enter Device PIN to Login', style: TextStyle(fontSize: 20.0), ), SizedBox(height: 40.0), PinCodeTextField( appContext: context, inputFormatters: [FilteringTextInputFormatter.digitsOnly], keyboardType: TextInputType.number, autoFocus: true, readOnly: false, obscureText: true, length: 6, onChanged: (value) { print(&quot;Login Pin: &quot; + value); }, pinTheme: PinTheme( shape: PinCodeFieldShape.underline, borderRadius: BorderRadius.circular(6), fieldHeight: 60, fieldWidth: 40, inactiveColor: Colors.blueAccent, activeColor: Colors.black, selectedColor: Colors.purple, ), controller: pinLoginController, onCompleted: (value) async { if (value == requiredPIN) { print('valid pin'); } else { print('invalid pin' + pinLoginController.text); setState(() { print('invalid pin state' + pinLoginController.text); pinLoginController.clear(); }); } }, ), ], ), ), ), ), ); } } </code></pre> <p>Since I am new to Flutter, Kindly provide what I am missing. Thank you.</p> <p>EDIT 1 :</p> <p>I edited with whole class.</p>
[ { "answer_id": 74559609, "author": "eamirho3ein", "author_id": 10306997, "author_profile": "https://Stackoverflow.com/users/10306997", "pm_score": 2, "selected": true, "text": "setState onCompleted: (value) async {\n if (value == requiredPIN) { \n print('valid pin');\n } else {\n print('invalid pin' + pinLoginController.text);\n \n setState(() {\n pinLoginController.clear();\n });\n \n }\n },\n TextEditingController? pinLoginController = new TextEditingController();\nfinal String requiredPIN = \"\";\nString _title = '4.0';\n\n@override\n Widget build(BuildContext context) {\n \n ...\n}\n" }, { "answer_id": 74559644, "author": "hari kurniawan", "author_id": 20547245, "author_profile": "https://Stackoverflow.com/users/20547245", "pm_score": 0, "selected": false, "text": "pinLoginController.text = pinLoginController.text.substring(0, pinLoginController.text.length - length of your pin);\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954020/" ]
74,559,576
<p>I am using useState hooks and when I click on the button of input value it updated my state and adds new elements in the array. I want to implement this here when I click the same value of positive and negative number both of the same number should be removed from the array For Example when I click on a button and elements are added, if I add 3 and after -3 both of the number should be removed from the array as shown in the example</p> <p>[-3, 1, 2, 3, 4] = [1, 2, 4]</p> <p>Help me for solving this problem</p> <pre><code>import &quot;./styles.css&quot;; import { useState } from &quot;react&quot;; export default function App() { const [data, setData] = useState([]); const [number, setNumber] = useState(&quot;&quot;); const onDataSubmit = (event) =&gt; { event.preventDefault(); setData([...data, number]); }; return ( &lt;div className=&quot;app&quot;&gt; &lt;div className=&quot;container&quot;&gt; &lt;div className=&quot;container1&quot;&gt; &lt;div className=&quot;input&quot;&gt; &lt;input id=&quot;title&quot; type=&quot;number&quot; value={number} onChange={(event) =&gt; setNumber(event.target.value)} name=&quot;title&quot; placeholder=&quot;Title&quot; /&gt; &lt;/div&gt; &lt;div&gt; &lt;button className=&quot;btn&quot; onClick={onDataSubmit}&gt; Submit &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;container2&quot;&gt;{data.sort((a, b) =&gt; a - b)}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74559700, "author": "NAZIR HUSSAIN", "author_id": 20587701, "author_profile": "https://Stackoverflow.com/users/20587701", "pm_score": 0, "selected": false, "text": " let array = [-3, 1, 2, 3, 4]\n let positiveArray=array.map(n=>Math.abs(n))\n let newData = positiveArray.filter((n, i,a) => {\n let arr = [...positiveArray];\n arr.splice(i, 1);\n return !(arr.includes(n));\n })\nconsole.log(newData); // [1,2,4]\n" }, { "answer_id": 74559720, "author": "Gia Huy Nguyễn", "author_id": 20485039, "author_profile": "https://Stackoverflow.com/users/20485039", "pm_score": 0, "selected": false, "text": "setData(prev => \n prev.reduce((val, item) => {\n if (item + number !== 0) {\n val.push(item);\n } else {\n val.splice(0, 1);\n }\n return val;\n }, [number])\n);\n" }, { "answer_id": 74559834, "author": "RubenSmn", "author_id": 20088324, "author_profile": "https://Stackoverflow.com/users/20088324", "pm_score": 1, "selected": false, "text": "// new number is 3\n[-3,1,2] => [1,2]\n // new number is -2\n[-3,1,2] => [-3,1]\n const onDataSubmit = (event) => {\n event.preventDefault();\n const absNumber = Math.abs(number);\n // both check if number is positive or negative\n if (\n data.find(\n (n) => Math.abs(n) === absNumber || -Math.abs(n) === -absNumber\n ) === undefined\n )\n return setData([...data, number]);\n \n // if number is not in the array add the new number\n setData((prevData) => {\n return prevData.filter(\n (n) => Math.abs(n) !== absNumber || -Math.abs(n) !== -absNumber\n );\n });\n};\n" }, { "answer_id": 74560034, "author": "pope_maverick", "author_id": 3065781, "author_profile": "https://Stackoverflow.com/users/3065781", "pm_score": 0, "selected": false, "text": " const onDataSubmit = (event) => {\n event.preventDefault();\n \n const newData = [...data]; \n const index = newData.indexOf(number * -1);\n \n if (index !== -1) {\n newData.splice(index, 1);\n setData(newData);\n \n return\n }\n \n setData([...data, number])\n };\n" }, { "answer_id": 74561362, "author": "Jet Ezra", "author_id": 13639031, "author_profile": "https://Stackoverflow.com/users/13639031", "pm_score": 1, "selected": false, "text": "const update_data = num => {\n if (!data.includes(num) && !data.includes(Math.abs(num)*-1) && !data.includes(Math.abs(num))) {\n setData([...data, num])\n } else {\n setData(data.filter(y => y + num !== 0))\n }\n}\n let data = [1, 2, 3, 4, 5, 6, 7, -8]\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15138000/" ]
74,559,586
<p>I have a data frame with a grouping variable <code>ID</code>, a factor <code>F</code> and a value <code>V</code> that looks something like this:</p> <pre><code>df &lt;- data.frame(ID = c(rep(1, 3), rep(2, 3)), F = factor(c(&quot;A&quot;,&quot;B&quot;,&quot;X&quot;,&quot;C&quot;,&quot;D&quot;,&quot;X&quot;)), V = c(30, 32, 25, 31, 37, 24) ) &gt; df ID F V 1 1 A 30 2 1 B 32 3 1 X 25 4 2 C 31 5 2 D 37 6 2 X 24 </code></pre> <p>Now, I would like to add a new column <code>New</code>, which has the same value within each group (by <code>ID</code>) based on the value for <code>V</code> in the row where <code>F==X</code> using the <code>tidyverse</code> environment. Ideally, those rows would be removed afterwards so that the new data frame looks like this:</p> <pre><code>&gt; df ID F V New 1 1 A 30 25 2 1 B 32 25 3 2 C 31 24 4 2 D 37 24 </code></pre> <p>I know that I have to use the <code>group_by()</code> function and probably also <code>mutate()</code>, but I couldn't quite manage to get my desired result.</p>
[ { "answer_id": 74559709, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "df %>%\n group_by(ID) %>%\n mutate(New = V[F =='X']) %>%\n filter(F != 'X')\n\n# A tibble: 4 × 4\n# Groups: ID [2]\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n" }, { "answer_id": 74559830, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "library(dplyr)\n\ndf %>% \n group_by(ID) %>% # grouping variables by ID\n mutate(New = ifelse(F == \"X\",\n V,\n NA)) %>% # adding New column\n summarise(New = max(New, na.rm = T)) %>% # Filtering rows with filled New column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% # SQL-like join\n select(ID, F, V, New) # reordering the columns to the desired order\n \n # A tibble: 4 × 4\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n df %>% filter(F == \"X\") %>% # filtering the rows with \"X\" in F column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% joining to the same dataset without \"X\" rows\n select(ID, F= F.y, V = V.y, New = V.x) #reordering and renaming of columns\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18322855/" ]
74,559,636
<p>I want to capture the username of the user during registration using user flow. I couldn't find that in attributes and even didn't find the azure user profile list. I am getting username attribute in login id token but that is coming as empty. I want to understand how azure b2c captures username of user and is there any capability to take unique username during registration using user flow</p> <p><a href="https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-profile-attributes#azure-ad-user-resource-type" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-profile-attributes#azure-ad-user-resource-type</a></p> <p>I tried to create custom attribute for username but sadly we can add validation using user flow, want to understand how to use build in username</p>
[ { "answer_id": 74559709, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "df %>%\n group_by(ID) %>%\n mutate(New = V[F =='X']) %>%\n filter(F != 'X')\n\n# A tibble: 4 × 4\n# Groups: ID [2]\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n" }, { "answer_id": 74559830, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "library(dplyr)\n\ndf %>% \n group_by(ID) %>% # grouping variables by ID\n mutate(New = ifelse(F == \"X\",\n V,\n NA)) %>% # adding New column\n summarise(New = max(New, na.rm = T)) %>% # Filtering rows with filled New column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% # SQL-like join\n select(ID, F, V, New) # reordering the columns to the desired order\n \n # A tibble: 4 × 4\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n df %>% filter(F == \"X\") %>% # filtering the rows with \"X\" in F column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% joining to the same dataset without \"X\" rows\n select(ID, F= F.y, V = V.y, New = V.x) #reordering and renaming of columns\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11673124/" ]
74,559,642
<p>I have a React Typescript project and use Craco. I have a CommonJS repo bundle which I want to integrate into the project.</p> <p>Using Craco start, the project works and there are no problems. On the build however, the error is:</p> <p>Attempted import error: 'B' is not exported from './test' (imported as 'test').</p> <p>I tried simplifying the problem by using a test and basically this is what we have.</p> <p>File: ./test.js</p> <pre><code>class A { test() { console.log('a') } } module.exports = A class B { test() { console.log('a') } } module.exports = B module.exports = { A, B } </code></pre> <p>File: ./service.ts</p> <pre><code>import * as test from './test' console.log(test.B) </code></pre> <p>I think it is something with the Webpack on Craco build and other types of JS maybe?</p>
[ { "answer_id": 74559709, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "df %>%\n group_by(ID) %>%\n mutate(New = V[F =='X']) %>%\n filter(F != 'X')\n\n# A tibble: 4 × 4\n# Groups: ID [2]\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n" }, { "answer_id": 74559830, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "library(dplyr)\n\ndf %>% \n group_by(ID) %>% # grouping variables by ID\n mutate(New = ifelse(F == \"X\",\n V,\n NA)) %>% # adding New column\n summarise(New = max(New, na.rm = T)) %>% # Filtering rows with filled New column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% # SQL-like join\n select(ID, F, V, New) # reordering the columns to the desired order\n \n # A tibble: 4 × 4\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n df %>% filter(F == \"X\") %>% # filtering the rows with \"X\" in F column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% joining to the same dataset without \"X\" rows\n select(ID, F= F.y, V = V.y, New = V.x) #reordering and renaming of columns\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14715707/" ]
74,559,676
<p>How do I let a variable amount of array's show up? I should give a list on the webpage with all the elements of the array.</p> <p>I tried this:</p> <pre><code>cons function = () =&gt;{for (let i = 0; i &lt; array.length; i++) { &lt;li&gt; &lt;p&gt;{array[i]}&lt;/p&gt; &lt;/li&gt; }} </code></pre> <p>and call it like this:</p> <pre><code>const page = () =&gt; { return ( &lt;div&gt; &lt;ul&gt; &lt;Classes/&gt; &lt;/ul&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74559709, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "df %>%\n group_by(ID) %>%\n mutate(New = V[F =='X']) %>%\n filter(F != 'X')\n\n# A tibble: 4 × 4\n# Groups: ID [2]\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n" }, { "answer_id": 74559830, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 0, "selected": false, "text": "library(dplyr)\n\ndf %>% \n group_by(ID) %>% # grouping variables by ID\n mutate(New = ifelse(F == \"X\",\n V,\n NA)) %>% # adding New column\n summarise(New = max(New, na.rm = T)) %>% # Filtering rows with filled New column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% # SQL-like join\n select(ID, F, V, New) # reordering the columns to the desired order\n \n # A tibble: 4 × 4\n ID F V New\n <dbl> <fct> <dbl> <dbl>\n1 1 A 30 25\n2 1 B 32 25\n3 2 C 31 24\n4 2 D 37 24\n df %>% filter(F == \"X\") %>% # filtering the rows with \"X\" in F column\n right_join(df %>% filter(F != \"X\"), by = \"ID\") %>% joining to the same dataset without \"X\" rows\n select(ID, F= F.y, V = V.y, New = V.x) #reordering and renaming of columns\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589989/" ]
74,559,691
<p>I want to get only columns whose names start with <code>'Q1'</code> and those starting with <code>'Q3'</code>, I know that this is possible by doing:</p> <pre><code>new_df=df[['Q1_1', 'Q1_2', 'Q1_3','Q3_1', 'Q3_2', 'Q3_3']] </code></pre> <p>But since my real <code>df</code> is too large (more than 70 variables) I search a way to get the <code>new_df</code> by using only desired first letters in the columns titles.</p> <p>My example dataframe is:</p> <pre><code>df=pd.DataFrame({ 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2': np.random.random(10), 'Q1_3': np.random.randint(2, size=10), 'Q2_1': [np.random.randint(1,100) for i in range(10)], 'Q2_2': np.random.random(10), 'Q2_3': np.random.randint(2, size=10), 'Q3_1': [np.random.randint(1,100) for i in range(10)], 'Q3_2': np.random.random(10), 'Q3_3': np.random.randint(2, size=10), 'Q4_1': [np.random.randint(1,100) for i in range(10)], 'Q4_2': np.random.random(10), 'Q4_3': np.random.randint(2, size=10) }) </code></pre> <p><code>df</code> has the following display:</p> <pre><code> Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3 0 92 0.551722 1 36 0.063269 1 95 0.541573 1 91 0.521076 1 1 89 0.951076 1 82 0.853572 1 49 0.782290 1 98 0.232572 0 2 88 0.909953 1 19 0.544450 1 66 0.021061 1 51 0.951225 0 3 66 0.904642 1 17 0.727190 1 85 0.697792 0 35 0.412844 1 4 78 0.802783 1 23 0.634575 1 77 0.759861 0 55 0.460012 0 5 41 0.943271 1 63 0.460578 1 95 0.004986 1 89 0.970059 0 6 54 0.600558 0 18 0.031487 0 84 0.716314 0 84 0.636364 1 7 2 0.458006 0 95 0.029421 0 10 0.927356 1 27 0.031572 1 8 38 0.029658 1 30 0.125706 1 94 0.096702 1 32 0.241613 1 9 52 0.584300 1 85 0.026642 0 78 0.358952 0 70 0.696008 0 </code></pre> <p>I want a simpler way to get the following sub-df:</p> <pre><code> Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3 0 92 0.551722 1 95 0.541573 1 1 89 0.951076 1 49 0.782290 1 2 88 0.909953 1 66 0.021061 1 3 66 0.904642 1 85 0.697792 0 4 78 0.802783 1 77 0.759861 0 5 41 0.943271 1 95 0.004986 1 6 54 0.600558 0 84 0.716314 0 7 2 0.458006 0 10 0.927356 1 8 38 0.029658 1 94 0.096702 1 9 52 0.584300 1 78 0.358952 0 </code></pre> <p>Please if you need more detail let me know in comments,</p> <p>Any help from your side will be highly appreciated.</p>
[ { "answer_id": 74559767, "author": "Anastasiya-Romanova 秀", "author_id": 3397819, "author_profile": "https://Stackoverflow.com/users/3397819", "pm_score": 2, "selected": false, "text": "cols = [col for col in df.columns if col[:2] in ('Q1', 'Q3')]\nnew_df = df[cols].copy()\n" }, { "answer_id": 74559899, "author": "Anoushiravan R", "author_id": 14314520, "author_profile": "https://Stackoverflow.com/users/14314520", "pm_score": 3, "selected": true, "text": "pd.DataFrame.filter df.filter(regex = r'Q1_\\d|Q3_\\d')\n\n Q1_1 Q1_2 Q1_3 Q3_1 Q3_2 Q3_3\n0 5 0.631041 0 46 0.768563 0\n1 32 0.594106 1 46 0.982396 1\n2 78 0.703139 1 38 0.252107 0\n3 98 0.353230 0 35 0.324079 0\n4 77 0.913203 1 11 0.456287 0\n5 62 0.565350 1 77 0.387365 0\n6 38 0.975652 1 59 0.276421 1\n7 97 0.505808 1 84 0.035756 0\n8 15 0.525452 0 57 0.675310 1\n9 94 0.545259 0 25 0.628030 0\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15852600/" ]
74,559,692
<pre><code>test_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18'] my_result = {'list_a': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'], 'list_b': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'], 'list_c': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']} </code></pre> <p>here is a example of test_list and my_result. i want to create multiple lists from a list taking every nth item using for loop in python. I tried but failed. Can anyone help me solving this probem? thanks in advance.</p>
[ { "answer_id": 74559763, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 1, "selected": false, "text": "list_a = []\nlist_b = []\nlist_c = []\n\n\nfor i in range(len(test_list)):\n if i % 3 == 0:\n list_a.append(test_list[i])\n if i % 3 == 1:\n list_b.append(test_list[i])\n if i % 3 == 2:\n list_c.append(test_list[i])\n" }, { "answer_id": 74559782, "author": "Epsi95", "author_id": 6660638, "author_profile": "https://Stackoverflow.com/users/6660638", "pm_score": 0, "selected": false, "text": "num_list = 3\n\nout = dict(zip([f'list_{i}' for i in range(1, num_list+1)], [[test_list[j] for j in range(i, len(test_list), num_list)] for i in range(num_list)]))\n\n# {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],\n# 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],\n# 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}\n" }, { "answer_id": 74559808, "author": "Lucas M. Uriarte", "author_id": 14543462, "author_profile": "https://Stackoverflow.com/users/14543462", "pm_score": 0, "selected": false, "text": "def reorder_list(original_list, interval):\n return {f\"list_{i+1}\": original_list[i::interval] for i in range(interval)}\n\n reorder_list(test_list, 3) \n>>> {'list_1': ['a1', 'a4', 'a7', 'a10', 'a13', 'a16'],\n 'list_2': ['a2', 'a5', 'a8', 'a11', 'a14', 'a17'],\n 'list_3': ['a3', 'a6', 'a9', 'a12', 'a15', 'a18']}\n" }, { "answer_id": 74559814, "author": "to_data", "author_id": 18317391, "author_profile": "https://Stackoverflow.com/users/18317391", "pm_score": 0, "selected": false, "text": "result={}\nfor i in range (0,n):\n result[f\"list_{i}\"]=test_list[i::n]\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17322414/" ]
74,559,698
<p>I've initialized a blank angular project with <code>ng new</code> and configured the launch.json in visual studio code with default chrome launch</p> <pre><code>&quot;configurations&quot;: [ { &quot;type&quot;: &quot;chrome&quot;, &quot;request&quot;: &quot;launch&quot;, &quot;name&quot;: &quot;Launch Chrome against localhost&quot;, &quot;url&quot;: &quot;http://localhost-app.myapp.com:4200&quot;, &quot;webRoot&quot;: &quot;${workspaceFolder}&quot; } ] </code></pre> <p>I've mapped in my host file 127.0.0.1 to this custom url and modified in <code>package.json</code> the start script with</p> <pre><code>&quot;start&quot;: &quot;ng serve --disable-host-check&quot;, </code></pre> <p>application work calling custom URL but VSC debugger <strong>does not bind breakpoints</strong>.</p> <p>If I set <code>localhost</code> in launch.json and remove <code>--disable-host-check</code>, debugger works as usual launched on localhost.</p> <p>Is there any way to make VSC debugger work on <code>localhost-app.myapp.com</code> my custom host?</p>
[ { "answer_id": 74560465, "author": "Rade Vignjevic", "author_id": 11707861, "author_profile": "https://Stackoverflow.com/users/11707861", "pm_score": -1, "selected": false, "text": " \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"chrome\",\n \"request\": \"launch\",\n \"name\": \"Launch Chrome against localhost\",\n \"url\": \"http://localhost:4200\",\n \"webRoot\": \"${workspaceFolder}\"\n },\n {\n \"type\": \"chrome\",\n \"request\": \"attach\",\n \"name\": \"Attach to Chrome\",\n \"port\": 9222,\n \"webRoot\": \"${workspaceFolder}\"\n }\n ]\n \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2936170/" ]
74,559,703
<p>Hi guys I have the following code written in typescript</p> <pre><code> const { data: { pageCollection } } = await apolloClient.query&lt;PageSlugsQuery&gt;({ query: GET_PAGE_SLUGS }) ( [...(pageCollection?.items ?? [])].forEach((page) =&gt; { console.log('PAGEEE', page) })) </code></pre> <p>Whe I use the second line I'm getting the error <code>Block scoped variable pageCollection can not be used before its declaration </code></p> <p>And when I remove brackets in the second line</p> <pre><code> [...(pageCollection?.items ?? [])].forEach((page) =&gt; { console.log('PAGEEE', page) }) </code></pre> <p>then I get the following error <code> Cannot find name 'forEach'.</code></p> <p>Does anyone know what could be a potential problem?</p>
[ { "answer_id": 74560465, "author": "Rade Vignjevic", "author_id": 11707861, "author_profile": "https://Stackoverflow.com/users/11707861", "pm_score": -1, "selected": false, "text": " \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"chrome\",\n \"request\": \"launch\",\n \"name\": \"Launch Chrome against localhost\",\n \"url\": \"http://localhost:4200\",\n \"webRoot\": \"${workspaceFolder}\"\n },\n {\n \"type\": \"chrome\",\n \"request\": \"attach\",\n \"name\": \"Attach to Chrome\",\n \"port\": 9222,\n \"webRoot\": \"${workspaceFolder}\"\n }\n ]\n \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4397306/" ]
74,559,746
<p>I'm bulding a receipes app for practising, using spoonicular api. I'm stuck trying to display favourites recipes saved on local storage.</p> <p>I have an array of ids saved in localstorage and Everytime i add a receipe i want to call api and display on screen. To do that I map over the array and get the object but I can't use the data outside map function. here the code thank you if someone can help</p> <pre><code> const getMyList = () =&gt; { fav.map(async(id) =&gt; { try{ const {data:res} = await axios.get(url) return res console.log(res) } catch(error) { console.log(error) } }) setNewArr([...newArr, res]) } useEffect(() =&gt; { getMyList() },[]); </code></pre>
[ { "answer_id": 74560465, "author": "Rade Vignjevic", "author_id": 11707861, "author_profile": "https://Stackoverflow.com/users/11707861", "pm_score": -1, "selected": false, "text": " \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"chrome\",\n \"request\": \"launch\",\n \"name\": \"Launch Chrome against localhost\",\n \"url\": \"http://localhost:4200\",\n \"webRoot\": \"${workspaceFolder}\"\n },\n {\n \"type\": \"chrome\",\n \"request\": \"attach\",\n \"name\": \"Attach to Chrome\",\n \"port\": 9222,\n \"webRoot\": \"${workspaceFolder}\"\n }\n ]\n \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19373182/" ]
74,559,753
<p>I'm making a kivy app that works on android smartphone. It colaborates with sqlite3. But as I try to transport as a android apk using my buildozer, suddenly my buildozer denied to work. The Error message is this.</p> <pre><code>[DEBUG]: -&gt; running mv sqlite-amalgamation-3350500 /mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/sqlite3/armeabi-v7a__ndk_target_21/sqlite3 [DEBUG]: /usr/bin/mv: cannot move 'sqlite-amalgamation-3350500' to '/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/sqlite3/armeabi-v7a__ndk_target_21/sqlite3': Permission denied Exception in thread background thread for pid 463: Traceback (most recent call last): File &quot;/usr/lib/python3.10/threading.py&quot;, line 1016, in _bootstrap_inner self.run() File &quot;/usr/lib/python3.10/threading.py&quot;, line 953, in run self._target(*self._args, **self._kwargs) File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 1641, in wrap fn(*rgs, **kwargs) File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 2569, in background_thread handle_exit_code(exit_code) File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 2269, in fn return self.command.handle_command_exit_code(exit_code) File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 869, in handle_command_exit_code raise exc sh.ErrorReturnCode_1: RAN: /usr/bin/mv sqlite-amalgamation-3350500 /mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/sqlite3/armeabi-v7a__ndk_target_21/sqlite3 STDOUT: /usr/bin/mv: cannot move 'sqlite-amalgamation-3350500' to '/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/sqlite3/armeabi-v7a__ndk_target_21/sqlite3': Permission denied STDERR: Traceback (most recent call last): File &quot;/usr/lib/python3.10/runpy.py&quot;, line 196, in _run_module_as_main return _run_code(code, main_globals, None, File &quot;/usr/lib/python3.10/runpy.py&quot;, line 86, in _run_code exec(code, run_globals) File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py&quot;, line 1297, in &lt;module&gt; main() File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py&quot;, line 18, in main ToolchainCL() File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py&quot;, line 730, in __init__ getattr(self, command)(args) File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py&quot;, line 153, in wrapper_func build_dist_from_args(ctx, dist, args) File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py&quot;, line 212, in build_dist_from_args build_recipes(build_order, python_modules, ctx, File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/build.py&quot;, line 491, in build_recipes recipe.prepare_build_dir(arch.arch) File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py&quot;, line 587, in prepare_build_dir self.unpack(arch) File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py&quot;, line 461, in unpack shprint(sh.mv, root_directory, directory_name) File &quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py&quot;, line 167, in shprint for line in output: File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 915, in next self.wait() File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 845, in wait self.handle_command_exit_code(exit_code) File &quot;/home/leejieung/.local/lib/python3.10/site-packages/sh.py&quot;, line 869, in handle_command_exit_code raise exc sh.ErrorReturnCode_1: RAN: /usr/bin/mv sqlite-amalgamation-3350500 /mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/sqlite3/armeabi-v7a__ndk_target_21/sqlite3 STDOUT: /usr/bin/mv: cannot move 'sqlite-amalgamation-3350500' to '/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/sqlite3/armeabi-v7a__ndk_target_21/sqlite3': Permission denied STDERR: # Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=LingoAdventure --bootstrap=sdl2 --requirements=python3,kivy --arch arm64-v8a --arch armeabi-v7a --copy-libs --color=always --storage-dir=&quot;/mnt/c/KivyApk/Lingo_Chans/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a&quot; --ndk-api=21 --ignore-setup-py --debug # ENVIRONMENT: # SHELL = '/bin/bash' # WSL_DISTRO_NAME = 'Ubuntu' # WT_SESSION = '3eb1ebcd-3650-44c7-983c-054f1eff6565' # NAME = 'LeeJE-Laptop' # PWD = '/mnt/c/KivyApk/Lingo_Chans' # LOGNAME = 'leejieung' # HOME = '/home/leejieung' # LANG = 'C.UTF-8' # WSL_INTEROP = '/run/WSL/43_interop' # LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:' # WAYLAND_DISPLAY = 'wayland-0' # LESSCLOSE = '/usr/bin/lesspipe %s %s' # TERM = 'xterm-256color' # LESSOPEN = '| /usr/bin/lesspipe %s' # USER = 'leejieung' # DISPLAY = ':0' # SHLVL = '1' # XDG_RUNTIME_DIR = '/mnt/wslg/runtime-dir' # WSLENV = 'WT_SESSION::WT_PROFILE_ID' # XDG_DATA_DIRS = '/usr/local/share:/usr/share:/var/lib/snapd/desktop' # PATH = ('/home/leejieung/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/leejieung/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/wsl/lib:/mnt/c/Program ' 'Files (x86)/Common ' 'Files/Oracle/Java/javapath:/mnt/c/windows/system32:/mnt/c/windows:/mnt/c/windows/System32/Wbem:/mnt/c/windows/System32/WindowsPowerShell/v1.0/:/mnt/c/windows/System32/OpenSSH/:/mnt/c/Program ' 'Files (x86)/NVIDIA Corporation/PhysX/Common:/mnt/c/Program Files/NVIDIA ' 'Corporation/NVIDIA NvDLISR:/mnt/c/Program Files/MySQL/MySQL Server ' '8.0/bin:/mnt/c/Program Files/PowerShell/7/:/mnt/c/Program ' 'Files/Docker/Docker/resources/bin:/mnt/c/Users/lje64/AppData/Local/Programs/Python/Python310/Scripts/:/mnt/c/Users/lje64/AppData/Local/Programs/Python/Python310/:/mnt/c/Users/lje64/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/lje64/AppData/Local/Programs/Microsoft ' 'VS Code/bin:/snap/bin') # HOSTTYPE = 'x86_64' # PULSE_SERVER = '/mnt/wslg/PulseServer' # WT_PROFILE_ID = '{61c54bbd-c2c6-5271-96e7-009a87ff44bf}' # _ = '/home/leejieung/.local/bin/buildozer' # PACKAGES_PATH = '/home/leejieung/.buildozer/android/packages' # ANDROIDSDK = '/home/leejieung/.buildozer/android/platform/android-sdk' # ANDROIDNDK = '/home/leejieung/.buildozer/android/platform/android-ndk-r23b' # ANDROIDAPI = '27' # ANDROIDMINAPI = '21' # # Buildozer failed to execute the last command # The error might be hidden in the log above this error # Please read the full log, and search for it before # raising an issue with buildozer itself. # In case of a bug report, please add a full log with log_level = 2 </code></pre> <p>What's the problem? Please tell me the solution as quick as possible...</p> <p>I searched into whole internet but I cannot find any clues</p>
[ { "answer_id": 74560465, "author": "Rade Vignjevic", "author_id": 11707861, "author_profile": "https://Stackoverflow.com/users/11707861", "pm_score": -1, "selected": false, "text": " \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"type\": \"chrome\",\n \"request\": \"launch\",\n \"name\": \"Launch Chrome against localhost\",\n \"url\": \"http://localhost:4200\",\n \"webRoot\": \"${workspaceFolder}\"\n },\n {\n \"type\": \"chrome\",\n \"request\": \"attach\",\n \"name\": \"Attach to Chrome\",\n \"port\": 9222,\n \"webRoot\": \"${workspaceFolder}\"\n }\n ]\n \n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20590060/" ]
74,559,760
<p>I prevent copy paste in textformfield(Flutter web) using Ctrl+C and Ctrl+V by adding</p> <pre class="lang-dart prettyprint-override"><code>enableInteractiveSelection: false, toolbarOptions: ToolbarOptions( copy: false, cut: false, paste: false, selectAll: false, ), </code></pre> <p>But still, it is possible to copy-paste by the following method, <a href="https://i.stack.imgur.com/TK9nI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TK9nI.png" alt="enter image description here" /></a></p> <p>Is it possible to prevent ?</p>
[ { "answer_id": 74560335, "author": "RESMA RAJ", "author_id": 11118094, "author_profile": "https://Stackoverflow.com/users/11118094", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n document.oncontextmenu = new Function('return false')\n document.body.oncut = new Function('return false');\n document.body.oncopy = new Function('return false');\n document.body.onpaste = new Function('return false');\n</script>\n" }, { "answer_id": 74560384, "author": "Sayyid J", "author_id": 15366030, "author_profile": "https://Stackoverflow.com/users/15366030", "pm_score": 2, "selected": true, "text": "Widget build(BuildContext context) {\n return SizedBox(\n width: 300,\n child: Listener(\n onPointerDown: (event){\n if(event.kind == PointerDeviceKind.mouse && event.buttons == kSecondaryMouseButton){\n print('yoo the user try to right click unfocus this so he cant paste');\n _focusNode.unfocus();\n }\n },\n child: TextField(\n enableInteractiveSelection: false,\n toolbarOptions: ToolbarOptions(\n paste: false\n ),\n onChanged: (data){\n print(data);\n },\n focusNode: _focusNode,\n controller: _textEditingController,\n ),\n ),\n );\n }\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11118094/" ]
74,559,762
<p>I am trying to solve a leetcode problem and am facing an issue with my code. What i want is that prev store the value of the previous node but when i run the recursive code the value of prev always becomes None.</p> <pre><code># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -&gt; bool: if not root: return True prev = None if root: if not self.isValidBST(root.left): return False if prev is not None and prev &gt;= root.val: return False prev = root.val return self.isValidBST(root.right) </code></pre> <p>Can you please explain why this code is failing especially why the value of prev always becomes None in every recursion call</p>
[ { "answer_id": 74560747, "author": "riigs", "author_id": 19844059, "author_profile": "https://Stackoverflow.com/users/19844059", "pm_score": 0, "selected": false, "text": "prev if prev is not None and prev >= root.val: prev None" }, { "answer_id": 74561979, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": false, "text": "prev prev prev if prev is not None prev None prev prev, these calls (except for the base case), all set is back to . But this is undesired: you should maintain the previous value, except for the case where the top-level (first) call is made: only then should be initialised to prev self prev prev None class Solution:\n def isValidBSTHelper(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return True\n if not self.isValidBSTHelper(root.left):\n return False\n if self.prev is not None and self.prev >= root.val:\n return False\n self.prev = root.val\n return self.isValidBSTHelper(root.right)\n\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n self.prev = None # Attribute has larger scope\n return self.isValidBSTHelper(root)\n class Solution:\n def inorder(self, root: Optional[TreeNode]):\n if root:\n yield from self.inorder(root.left)\n yield root.val\n yield from self.inorder(root.right)\n \n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n values = self.inorder(root)\n prev = next(values, None) # get first value and advance\n for val in values:\n if prev >= val:\n return False\n prev = val\n return True\n zip isValidBST inorder def isValidBST(self, root: Optional[TreeNode]) -> bool:\n previous = self.inorder(root)\n values = self.inorder(root)\n next(values, None) # move one iterator one step forward\n return all(a < b for a, b in zip(previous, values)) # all pairs must be in order\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306281/" ]
74,559,770
<p>suppose we have a main.py file and a_file.py that has a list</p> <p>like this :</p> <p><strong>main.py</strong></p> <pre><code>from a_file import * while true: example = input(&quot;Enter Something : &quot;) a_list.append(example) if example == 'showlist': print(a_list) </code></pre> <p><strong>a_file.py</strong></p> <pre><code>a_list = [] </code></pre> <p>so as you can see the main.py file has a input that whatever you type in it gets stored in the a_list list in a_file.py</p> <p>when you first want to run the main.py</p> <p>it will ask some input in a loop and whatever you type gets appended to the a_list in the a_file.py</p> <p>Here is the problem...</p> <p>i want whatever you type in the input get stored in the list permanently</p> <p>because when you close the python script and run it again , the list will be empty</p> <p>so i want that everything that gets stored in the list permanently be in the list</p> <p>so good luck helping me.. Thanks for reading my problem</p>
[ { "answer_id": 74560747, "author": "riigs", "author_id": 19844059, "author_profile": "https://Stackoverflow.com/users/19844059", "pm_score": 0, "selected": false, "text": "prev if prev is not None and prev >= root.val: prev None" }, { "answer_id": 74561979, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": false, "text": "prev prev prev if prev is not None prev None prev prev, these calls (except for the base case), all set is back to . But this is undesired: you should maintain the previous value, except for the case where the top-level (first) call is made: only then should be initialised to prev self prev prev None class Solution:\n def isValidBSTHelper(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return True\n if not self.isValidBSTHelper(root.left):\n return False\n if self.prev is not None and self.prev >= root.val:\n return False\n self.prev = root.val\n return self.isValidBSTHelper(root.right)\n\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n self.prev = None # Attribute has larger scope\n return self.isValidBSTHelper(root)\n class Solution:\n def inorder(self, root: Optional[TreeNode]):\n if root:\n yield from self.inorder(root.left)\n yield root.val\n yield from self.inorder(root.right)\n \n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n values = self.inorder(root)\n prev = next(values, None) # get first value and advance\n for val in values:\n if prev >= val:\n return False\n prev = val\n return True\n zip isValidBST inorder def isValidBST(self, root: Optional[TreeNode]) -> bool:\n previous = self.inorder(root)\n values = self.inorder(root)\n next(values, None) # move one iterator one step forward\n return all(a < b for a, b in zip(previous, values)) # all pairs must be in order\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19728979/" ]
74,559,776
<p>I'm trying to use the canvas API function <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath" rel="nofollow noreferrer"><code>isPointInPath</code></a> to check if the user mouse is hovering a polygon on a canvas layer within a Leaflet map.</p> <p>Thus, I'm creating a canvas layer and get the associated context :</p> <pre class="lang-js prettyprint-override"><code>const canvasLayer = L.canvas().addTo(map) const canvas = document.querySelectorAll('canvas')[0] const context = canvas.getContext('2d') </code></pre> <p>To test the function, I'm creating a disk, centered somewhere in the map. To do that I use the usual Leaflet projection to go the layer pixel coordinated from latitude / longitude coordinates :</p> <pre class="lang-js prettyprint-override"><code>const diskCenter = [37.8, -96.9] const diskCenterProjected = map.latLngToLayerPoint(new L.LatLng(origin[0], origin[1])) context.beginPath() context.arc( diskCenterProjected.x, diskCenterProjected.y, 20, 0, 2 * Math.PI ) context.stroke() context.closePath() </code></pre> <p>As this disk is within the canvas layer of Leaflet, it moves correcly along the map when panning or zooming. However, I'm not able to map the mouse position obtains from the <code>mousemove</code> event.</p> <pre class="lang-js prettyprint-override"><code>canvas.addEventListener('mousemove', (e) =&gt; { console.log(e.pageX, e.pageY, context.isPointInPath(e.pageX, e.pageY)) }) </code></pre> <p><code>pageX</code> and <code>pageY</code> are always within the layer container bounds of course, but <code>context.isPointInPath(e.pageX, e.pageY))</code> is never triggered properly. Indeed, there is a disk that triggers somewhere in the map, but doesn't match the original disk I've created !</p> <p>I do believe there is something to do with the transformation applied by Leaflet on the canvas layer. For instance, without any panning or zooming, with the initial map loaded, there is already a transformation (transform and width/height change) applied to the canvas element :</p> <pre class="lang-js prettyprint-override"><code>&lt;canvas class=&quot;leaflet-zoom-animated&quot; width=&quot;1958&quot; height=&quot;1910&quot; style=&quot;transform: translate3d(-82px, -80px, 0px); width: 979px; height: 955px;&quot;&gt;&lt;/canvas&gt;``` </code></pre>
[ { "answer_id": 74560747, "author": "riigs", "author_id": 19844059, "author_profile": "https://Stackoverflow.com/users/19844059", "pm_score": 0, "selected": false, "text": "prev if prev is not None and prev >= root.val: prev None" }, { "answer_id": 74561979, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": false, "text": "prev prev prev if prev is not None prev None prev prev, these calls (except for the base case), all set is back to . But this is undesired: you should maintain the previous value, except for the case where the top-level (first) call is made: only then should be initialised to prev self prev prev None class Solution:\n def isValidBSTHelper(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return True\n if not self.isValidBSTHelper(root.left):\n return False\n if self.prev is not None and self.prev >= root.val:\n return False\n self.prev = root.val\n return self.isValidBSTHelper(root.right)\n\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n self.prev = None # Attribute has larger scope\n return self.isValidBSTHelper(root)\n class Solution:\n def inorder(self, root: Optional[TreeNode]):\n if root:\n yield from self.inorder(root.left)\n yield root.val\n yield from self.inorder(root.right)\n \n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n values = self.inorder(root)\n prev = next(values, None) # get first value and advance\n for val in values:\n if prev >= val:\n return False\n prev = val\n return True\n zip isValidBST inorder def isValidBST(self, root: Optional[TreeNode]) -> bool:\n previous = self.inorder(root)\n values = self.inorder(root)\n next(values, None) # move one iterator one step forward\n return all(a < b for a, b in zip(previous, values)) # all pairs must be in order\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7315793/" ]
74,559,779
<p>I'm trying to download a single file with a GET request URL that doesn't specify the filename of the returned file. It returns zip files if you request multiple filter items, but single xlsx files if you only have one filter item. I want to download the file into a folder then find out its name, rather than save it into a tempfile with a random name.</p> <pre><code># web GET request web &lt;- &quot;https://www.find-school-performance-data.service.gov.uk/download-data?download=true&amp;regions=0&amp;filters=GIAS&amp;fileformat=xls&amp;year=2021-2022&amp;meta=false&quot; tf &lt;- tempfile() td &lt;- tempdir() # this works fine, but gives the file a random name download.file(web, tf, mode=&quot;wb&quot;) #these don't work as it wants me to give the full file name, not just the folder download.file(web, td, mode=&quot;wb&quot;) download.file(web, paste0(td,&quot;\\&quot;), mode=&quot;wb&quot;) Warning messages: 1: In download.file(web, paste0(td, &quot;\\&quot;), mode = &quot;wb&quot;) : URL https://www.find-school-performance-data.service.gov.uk/download-data?download=true&amp;regions=0&amp;filters=GIAS&amp;fileformat=xls&amp;year=2021-2022&amp;meta=false: cannot open destfile 'C:\Users\USER\AppData\Local\Temp\RtmpWi98JC\', reason 'No such file or directory' 2: In download.file(web, paste0(td, &quot;\\&quot;), mode = &quot;wb&quot;) : download had nonzero exit status </code></pre>
[ { "answer_id": 74560603, "author": "pluke", "author_id": 948397, "author_profile": "https://Stackoverflow.com/users/948397", "pm_score": 2, "selected": true, "text": "httr library(httr)\n\ntd <- tempdir()\nweb <- \"https://www.find-school-performance-data.service.gov.uk/download-data?download=true&regions=0&filters=GIAS&fileformat=xls&year=2021-2022&meta=false\"\n\n# load header response from web GET request\nhdr <- HEAD(web)\nfilename <- gsub(\".*name=\", \"\", headers(hdr)$`content-disposition`)\n # download to temp directory using original name\ndownload.file(web, paste0(td,\"\\\\\",filename), mode=\"wb\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/948397/" ]
74,559,784
<p>My kubernetes cluster is running in a restricted environment where we are unable to open ports as we want(only a range of ports are allowed for customized use), Some how I have started the kubernetes API server(6443 by default) on a allowed port using the config options with 'kubeadm init' , is there any way to change the default port of 10250 (kubelet API)?</p>
[ { "answer_id": 74560603, "author": "pluke", "author_id": 948397, "author_profile": "https://Stackoverflow.com/users/948397", "pm_score": 2, "selected": true, "text": "httr library(httr)\n\ntd <- tempdir()\nweb <- \"https://www.find-school-performance-data.service.gov.uk/download-data?download=true&regions=0&filters=GIAS&fileformat=xls&year=2021-2022&meta=false\"\n\n# load header response from web GET request\nhdr <- HEAD(web)\nfilename <- gsub(\".*name=\", \"\", headers(hdr)$`content-disposition`)\n # download to temp directory using original name\ndownload.file(web, paste0(td,\"\\\\\",filename), mode=\"wb\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672382/" ]
74,559,811
<p>It is necessary to realize the volume of the TV. struct Setting var volume range 0...100. How to write to print the volume level?</p> <p>Another question: Is it possible to better make the brand and model of the TV in the same field? var tvName</p> <pre><code>struct Setting { var volume = (0...100) enum Display: String { case colorful = &quot;Color&quot; case blackwhite = &quot;Black&amp;White&quot; } } class Tv { var tvName = (firm: &quot;&quot;, model: 0) var isActive = Bool() enum Channels: String { case news = &quot;News&quot; case serials = &quot;Serials&quot; case horror = &quot;Horror&quot; case comedy = &quot;Comedy&quot; case history = &quot;History&quot; case cartoons = &quot;Cartoons&quot; } func tvStatus() { if isActive == true { print(&quot;The TV \(tvName.0) \(tvName.1) is on and shows the channel \(channelOldTv), display: \(display), volume: &quot;) } else { print(&quot;TV is off&quot;) } } } let oldTv = Tv() let channelOldTv = Tv.Channels.serials.rawValue let display = Setting.Display.colorful.rawValue oldTv.tvName.firm = &quot;LG&quot; oldTv.tvName.model = 6643 oldTv.isActive = true oldTv.tvStatus() </code></pre>
[ { "answer_id": 74560603, "author": "pluke", "author_id": 948397, "author_profile": "https://Stackoverflow.com/users/948397", "pm_score": 2, "selected": true, "text": "httr library(httr)\n\ntd <- tempdir()\nweb <- \"https://www.find-school-performance-data.service.gov.uk/download-data?download=true&regions=0&filters=GIAS&fileformat=xls&year=2021-2022&meta=false\"\n\n# load header response from web GET request\nhdr <- HEAD(web)\nfilename <- gsub(\".*name=\", \"\", headers(hdr)$`content-disposition`)\n # download to temp directory using original name\ndownload.file(web, paste0(td,\"\\\\\",filename), mode=\"wb\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20371003/" ]
74,559,884
<p>i have this firestore collection that needs to update according to the data within array of objects, at first this was not a problem. but as the data grows. to update the data to firebase is we have to compare each id and then perform update to all of the data.</p> <p>here i have some array,</p> <pre><code>let newCategoriesUpdate = [ { category_id: 100001, parent_category_id: 0, name: &quot;Health&quot;, isActive: true, has_children: true, }, { category_id: 100019, parent_category_id: 100001, name: &quot;Medical Equipment&quot;, isActive: true, has_children: false, }, { category_id: 100020, parent_category_id: 100001, name: &quot;Laboratory&quot;, isActive: false, has_children: false, }, ] </code></pre> <p>the list contains more than 200 objects which need to compare on each loop, which takes more time and memory.</p> <p>Here's what i've implemented in firebase to update the collection from array of objects above</p> <pre><code> const handleUpdateCategories = () =&gt; { db.collection(&quot;category&quot;) .get() .then((snapshot) =&gt; { snapshot.forEach((docRef) =&gt; { let name = &quot;My Category&quot;; if (docRef.data().name === name) { let categoryRef = docRef.id; db.collection(&quot;category&quot;) .doc(categoryRef) .collection(&quot;categoryList&quot;) .get() .then((snapshotCollection) =&gt; { // loop collection from firebase snapshotCollection.forEach((catListDocRef) =&gt; { let categoryListRefId = catListDocRef.id; // need to compare each loop in array // loop array to update newCategoriesUpdate.map((category) =&gt; { if ( catListDocRef.data().categoryId === category.category_id ) { db.collection(&quot;category&quot;) .doc(categoryRef) .collection(&quot;categoryList&quot;) .doc(categoryListRefId) .set( { categoryId: category.category_id, isActive: category.isActive, categoryName: category.name, }, { merge: true } ) .then(() =&gt; { console.log(&quot;UPDATE Success&quot;); }) .catch((err) =&gt; { console.log(&quot;ERR&quot;, err); }); } }); }); }); } }); }); }; </code></pre> <p>This method works, and in the console also shows the message &quot;UPDATE Success&quot; multiple times.</p> <p>Is there a better alternative to update multiple collection from array of objects?</p>
[ { "answer_id": 74560603, "author": "pluke", "author_id": 948397, "author_profile": "https://Stackoverflow.com/users/948397", "pm_score": 2, "selected": true, "text": "httr library(httr)\n\ntd <- tempdir()\nweb <- \"https://www.find-school-performance-data.service.gov.uk/download-data?download=true&regions=0&filters=GIAS&fileformat=xls&year=2021-2022&meta=false\"\n\n# load header response from web GET request\nhdr <- HEAD(web)\nfilename <- gsub(\".*name=\", \"\", headers(hdr)$`content-disposition`)\n # download to temp directory using original name\ndownload.file(web, paste0(td,\"\\\\\",filename), mode=\"wb\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9675410/" ]
74,559,896
<p>I am trying to modify the following script so that my legends are changed to that list in <code>speeds</code>. How can I do this without changing the <code>iterator</code> list?</p> <pre><code>x = np.arange(10) iterator = [1, 2, 3] speeds =[*range(100,300,500)] for a in iterator: plt.plot(x, a*x, label=f'{a}rpm') plt.legend(loc='best') </code></pre> <p><strong>Modified script</strong>:</p> <pre><code>x = np.arange(10) iterator = [1, 2, 3] speeds =[*range(100,300,500)] for a in iterator and b in speeds: plt.plot(x, a*x, label=f'{b}rpm') plt.legend(loc='best') plt.show() </code></pre> <p><strong>Desired Outcome</strong>: legends are changed to that in <code>speeds</code> list ie,</p> <pre><code>1rpm -&gt; 100rpm 2rpm -&gt; 300rpm 3prm -&gt; 500rpm </code></pre>
[ { "answer_id": 74560603, "author": "pluke", "author_id": 948397, "author_profile": "https://Stackoverflow.com/users/948397", "pm_score": 2, "selected": true, "text": "httr library(httr)\n\ntd <- tempdir()\nweb <- \"https://www.find-school-performance-data.service.gov.uk/download-data?download=true&regions=0&filters=GIAS&fileformat=xls&year=2021-2022&meta=false\"\n\n# load header response from web GET request\nhdr <- HEAD(web)\nfilename <- gsub(\".*name=\", \"\", headers(hdr)$`content-disposition`)\n # download to temp directory using original name\ndownload.file(web, paste0(td,\"\\\\\",filename), mode=\"wb\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106985/" ]
74,559,938
<pre><code>a=&quot;|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |&quot; b=&quot;|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|&quot; </code></pre> <p>both of these strings should be 98 characters, but when printing with a monospaced font (in my terminal) it shows <code>b</code> as being longer</p> <p><a href="https://i.stack.imgur.com/4dP9L.png" rel="nofollow noreferrer">terminal output when printing length of each string followed by string</a></p> <p>This shouldn't be an issue but I'm trying to draw a box around some text and this glitch causes the table to be misaligned. Is it possible that the font is not properly monospaced? I am using VS Code for the Web.</p> <p>Thank you kindly for your time.</p>
[ { "answer_id": 74560020, "author": "Anentropic", "author_id": 202168, "author_profile": "https://Stackoverflow.com/users/202168", "pm_score": 2, "selected": true, "text": "a In [4]: for i, char in enumerate(a):\n ...: print((i, char))\n ...:\n(0, '|')\n(1, ':')\n(2, 'w')\n(3, 'a')\n(4, 't')\n(5, 'c')\n(6, 'h')\n(7, ':')\n(8, '️')\n(9, ' ')\n(10, ':')\n(11, 'm')\n(12, 'o')\n(13, 'b')\n(14, 'i')\n(15, 'l')\n(16, 'e')\n(17, ' ')\n(18, 'p')\n(19, 'h')\n(20, 'o')\n(21, 'n')\n(22, 'e')\n(23, ':')\n(24, ' ')\n(25, ':')\n(26, 'm')\n(27, 'o')\n(28, 'b')\n(29, 'i')\n(30, 'l')\n(31, 'e')\n(32, ' ')\n(33, 'p')\n(34, 'h')\n(35, 'o')\n(36, 'n')\n(37, 'e')\n(38, ' ')\n(39, 'w')\n(40, 'i')\n(41, 't')\n(42, 'h')\n(43, ' ')\n(44, 'a')\n(45, 'r')\n(46, 'r')\n(47, 'o')\n(48, 'w')\n(49, ':')\n(50, ' ')\n(51, ':')\n(52, 'l')\n(53, 'a')\n(54, 'p')\n(55, 't')\n(56, 'o')\n(57, 'p')\n(58, ':')\n(59, ' ')\n(60, ':')\n(61, 'k')\n(62, 'e')\n(63, 'y')\n(64, 'b')\n(65, 'o')\n(66, 'a')\n(67, 'r')\n(68, 'd')\n(69, ':')\n(70, ' ')\n(71, ':')\n(72, 'd')\n(73, 'e')\n(74, 's')\n(75, 'k')\n(76, 't')\n(77, 'o')\n(78, 'p')\n(79, ' ')\n(80, 'c')\n(81, 'o')\n(82, 'm')\n(83, 'p')\n(84, 'u')\n(85, 't')\n(86, 'e')\n(87, 'r')\n(88, ':')\n(89, ' ')\n(90, ' ')\n(91, ' ')\n(92, ' ')\n(93, ' ')\n(94, ' ')\n(95, ' ')\n(96, ' ')\n(97, '|')\n 8 In [5]: ord(a[8])\nOut[5]: 65039\n" }, { "answer_id": 74560082, "author": "aviya-yahav", "author_id": 20590210, "author_profile": "https://Stackoverflow.com/users/20590210", "pm_score": 0, "selected": false, "text": "a=\"|:watch:️ :mobile phone: :mobile phone with arrow: :laptop: :keyboard: :desktop computer: |\"\nb=\"|:printer: :computer mouse: :trackball: :joystick: :clamp: :computer disk: :floppy disk: :optical|\"\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395346/" ]
74,559,959
<p>I need to convert the ‘content’ column from a string dictionary to a dictionary in python. After that I will use the following line of code:</p> <p>df[‘content’].apply(pd.Series).</p> <p>To have the dictionary values as a column name and the dictionary value in a cell.</p> <p>I can’t do this now because there are missing values in the dictionary string.</p> <p>How can I handle missing values in the dictionary when I use the function eval(String dictionary) -&gt; dictionary?</p> <p>[I'm working on the 'content' column that I want to convert to the correct format first, I tried with the eval() function, but it doesn't work, because there are missing values. This is json data.</p> <p>My goal is to have the content column data for the keys in the column titles and the values in the cells](<a href="https://i.stack.imgur.com/1CsIl.png" rel="nofollow noreferrer">https://i.stack.imgur.com/1CsIl.png</a>)</p>
[ { "answer_id": 74560207, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": true, "text": "import json\nimport numpy as np\ndf['content']=df['content'].apply(lambda x: json.loads(x) if pd.notna(x) else np.nan)\n\n v1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],axis=1).join(v1)\n\n def check_json(x):\n import ast\n import json\n if pd.isna(x):\n return np.nan\n else:\n try:\n return json.loads(x)\n except:\n try:\n mask=x.replace('{','').replace('}','') #missing dictionary\n mask=mask.split(\",\")\n for i in range(0,len(mask)):\n if not len(mask[i].partition(\":\")[-1]) > 0:\n print(mask[i])\n mask[i]=mask[i] + '\"None\"' # ---> you can replace None with what do you want \n return json.loads(str({','.join(mask)}).replace(\"\\'\", \"\"))\n except:\n try:\n x=x.replace(\"\\'\", \"\\\"\")\n mask=x.replace('{','').replace('}',\"\") #missing dictionary\n mask=mask.split(\",\")\n for i in range(0,len(mask)):\n if not len(mask[i].partition(\":\")[-1]) > 0:\n print(mask[i])\n mask[i]=mask[i] + '\"None\"' # ---> you can replace None with what do you want \n b=str({','.join(mask)}).replace(\"\\'\", \"\")\n return ast.literal_eval(b)\n except:\n print(\"Could not parse json object. Returning nan\")\n return np.nan\n\ndf['content']=df['content'].apply(lambda x: check_json(x))\n\nv1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],axis=1).join(v1)\n\n" }, { "answer_id": 74560410, "author": "John Collins", "author_id": 20590267, "author_profile": "https://Stackoverflow.com/users/20590267", "pm_score": -1, "selected": false, "text": "import pandas as pd\nimport numpy as np\nimport json\n\n## setting up an example dataframe. note that row2 has a null value\njson_example = [\n '{\"row1_key1\":\"row1_value1\",\"row1_key2\":\"row1_value2\"}',\n '{\"row2_key1\":\"row2_value1\",\"row2_key2\": null}'\n ]\n\ndf= pd.DataFrame()\n\ndf['Content'] = json_example\n\n## using string replace on the string representation of the json to clean it up\n\ndf['Content'].apply(lambda x: x.replace('null','\"0\"'))\n\n## using lambda x to first load the string into a dict, then applying pd.Series()\n\ndf['Content'].apply(lambda x: pd.Series(json.loads(x)))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14098467/" ]
74,559,963
<p>So I'm working in this table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Raumeinheit</th> <th>Langzeitarbeitslose</th> </tr> </thead> <tbody> <tr> <td>Hamburg</td> <td>33,23</td> </tr> <tr> <td>Berlin</td> <td>44,56</td> </tr> </tbody> </table> </div> <p>I'm trying to calculate the mean of Langzeitarbeitslose but I can't because</p> <pre><code>is.numeric </code></pre> <p>comes out as false because the column Langzeitarbeitslose is defined as character.</p> <p>I think this might be because here in Germany we use &quot;,&quot; to show decimals and not &quot;.&quot;</p> <p>I already tried</p> <pre><code>as.numeric(gsub(&quot;,&quot;, &quot;.&quot;, West_data$Langzeitarbeitslose)) </code></pre> <p>that gave me a working table in the console preview but when I looked at the table with</p> <pre><code>view(West_Data) </code></pre> <p>It still showed the Decimals of Langzeitarbeitslose seperated with ',' and</p> <pre><code>is.numeric(West_Data$Langzeitarbeitslose) </code></pre> <p>came back as false.</p>
[ { "answer_id": 74560207, "author": "Bushmaster", "author_id": 15415267, "author_profile": "https://Stackoverflow.com/users/15415267", "pm_score": 1, "selected": true, "text": "import json\nimport numpy as np\ndf['content']=df['content'].apply(lambda x: json.loads(x) if pd.notna(x) else np.nan)\n\n v1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],axis=1).join(v1)\n\n def check_json(x):\n import ast\n import json\n if pd.isna(x):\n return np.nan\n else:\n try:\n return json.loads(x)\n except:\n try:\n mask=x.replace('{','').replace('}','') #missing dictionary\n mask=mask.split(\",\")\n for i in range(0,len(mask)):\n if not len(mask[i].partition(\":\")[-1]) > 0:\n print(mask[i])\n mask[i]=mask[i] + '\"None\"' # ---> you can replace None with what do you want \n return json.loads(str({','.join(mask)}).replace(\"\\'\", \"\"))\n except:\n try:\n x=x.replace(\"\\'\", \"\\\"\")\n mask=x.replace('{','').replace('}',\"\") #missing dictionary\n mask=mask.split(\",\")\n for i in range(0,len(mask)):\n if not len(mask[i].partition(\":\")[-1]) > 0:\n print(mask[i])\n mask[i]=mask[i] + '\"None\"' # ---> you can replace None with what do you want \n b=str({','.join(mask)}).replace(\"\\'\", \"\")\n return ast.literal_eval(b)\n except:\n print(\"Could not parse json object. Returning nan\")\n return np.nan\n\ndf['content']=df['content'].apply(lambda x: check_json(x))\n\nv1 = df['Content'].apply(pd.Series)\ndf = df.drop(['Content'],axis=1).join(v1)\n\n" }, { "answer_id": 74560410, "author": "John Collins", "author_id": 20590267, "author_profile": "https://Stackoverflow.com/users/20590267", "pm_score": -1, "selected": false, "text": "import pandas as pd\nimport numpy as np\nimport json\n\n## setting up an example dataframe. note that row2 has a null value\njson_example = [\n '{\"row1_key1\":\"row1_value1\",\"row1_key2\":\"row1_value2\"}',\n '{\"row2_key1\":\"row2_value1\",\"row2_key2\": null}'\n ]\n\ndf= pd.DataFrame()\n\ndf['Content'] = json_example\n\n## using string replace on the string representation of the json to clean it up\n\ndf['Content'].apply(lambda x: x.replace('null','\"0\"'))\n\n## using lambda x to first load the string into a dict, then applying pd.Series()\n\ndf['Content'].apply(lambda x: pd.Series(json.loads(x)))\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20575692/" ]
74,559,964
<p>I have a column in my dataset which is formatted as dates. I am aiming to obtain the most recent date by using the max() function. The date column is formatted like (ex. 21.12.2018), and I have used the folowing lines of code:</p> <pre><code>MD$Date&lt;- as.Date(MD$Date, &quot;%d.%m.%Y&quot;) analysis_date &lt;- max(MD$Date) </code></pre> <p>Howevere, analysis_date returns the value NA. Any tips?</p>
[ { "answer_id": 74566818, "author": "Enoch", "author_id": 3587230, "author_profile": "https://Stackoverflow.com/users/3587230", "pm_score": 1, "selected": false, "text": "dplyr tidyverse # package\nlibrary(dplyr)\n\n# Sample database\nMD <- data.frame(\n Date = c(\"21.12.2018\", NA, \"20.12.2018\", \"19.12.2018\")\n )\n\n# Get the most recent date\nMD |> \n slice_max(\n as.Date(Date, \"%d.%m.%Y\")\n )\n" }, { "answer_id": 74568649, "author": "Yomi.blaze93", "author_id": 16087142, "author_profile": "https://Stackoverflow.com/users/16087142", "pm_score": 0, "selected": false, "text": "my_dates_update <- as.Date(my_dates) # Convert character to Date\n \n class(my_dates_update) # Check the class of updated dates, it should return date as type\n \n min(my_dates_updated) # Earliest date\n \n max(my_dates_updated) # Latest date\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18705501/" ]
74,559,973
<p>Trying to process a CSV file using AWK, however I have met a problem that many of my cells in my row already contain comma <code>,</code>, meaning I can not separate field using <code>awk -F,</code>.</p> <p>CSV FILE</p> <pre><code>Name,...DATE,COLUMNX,ADDRESSES host1,...,NOV 24, 2022,['Element1', 'Element2'],&quot;['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]&quot; host2,...,NOV 24, 2022,['Element3'],&quot;['192.168.x.101', 'fe80:XX']&quot; </code></pre> <p>The <code>...</code> represents rows/columns containing <code>[</code>, <code>,</code>, <code>'</code>, <code>&quot;</code></p> <p>What I have tried:<br /> <code>awk -F, '{print $X}'</code><br /> This give me following output:</p> <pre><code>'Element2'] &quot;['192.168.x.101' </code></pre> <p>What I want to accomplish:</p> <pre><code>host1 192.168.x.99 host1 192.168.x.100 host2 192.168.x.101 </code></pre>
[ { "answer_id": 74560229, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": "' , F ' , -F'[,'\\''=]' awk -F'[,'\\'']' 'NR>1{print $1\" \"$35}' data.csv\n data.csv:\nName,...DATE,COLUMNX,ADDRESSES\nhost1,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\nhost2,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['192.168.xxx.yy', 'fe80:XX','192.168.x.100', fe80:XX]\"\nhost3,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['192.xxx.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\nhost4,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['xxx.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\n host1 192.168.x.99\nhost2 192.168.xxx.yy\nhost3 192.xxx.x.99\nhost4 xxx.168.x.99\n" }, { "answer_id": 74560927, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "awk $ ruby -r 'csv' -ne 'lines=$_\n CSV.parse(lines) do |i| \n i.each do |j| \n printf(\"%s \", j)\n end\n puts \"\"\n end' file | \nawk '{gsub(/\\[\\047|\\047\\]|\\047|\\]|,/, \"\", $0)}\n /^host/{for(i=1;i<=NF;i++){if($i~/^[0-9]+\\.+/){print $1, $i}}}'\nhost1 192.168.x.99\nhost1 192.168.x.100\nhost2 192.168.x.101\n" }, { "answer_id": 74560984, "author": "j_b", "author_id": 16482938, "author_profile": "https://Stackoverflow.com/users/16482938", "pm_score": 0, "selected": false, "text": "awk awk -F\",\\\"|\\\"$\" 'NR>1 { \\\ngsub(/\\047|[\\[\\]]/,\"\"); \\\nsplit($2,a,\", \"); \\\nsplit($1,h,\",\"); \\\nfor (n in a) {if (a[n] ~ /^[0-9]/) printf \"%s %s\\n\", h[1], a[n]}}' src.csv\n host1 192.168.x.100\nhost1 192.168.x.99\nhost2 192.168.x.101\n -F\",\\\"|\\\"$\" gsub(/\\047|[\\[\\]]/,\"\"); split($2,a,\", \"); a split($1,h,\",\"); h for (n in a) {if (a[n] ~ /^[0-9]/) printf \"%s %s\\n\", h[1], a[n] a" }, { "answer_id": 74567030, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 0, "selected": false, "text": "FPAT $ cat tst.awk\nBEGIN {\n FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")|([[][^]]+])\"\n}\nNR > 1 {\n n = split($NF,a,/\\047/)\n for ( i=2; i<=n; i+=4 ) {\n print $1, a[i]\n }\n}\n $ awk -f tst.awk file\nhost1 192.168.x.99\nhost1 192.168.x.100\nhost2 192.168.x.101\n FPAT split() ' $ cat tst.awk\nBEGIN {\n FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")|([[][^]]+])\"\n}\nNR > 1 {\n print \"=============\"\n print\n for ( i=1; i<=NF; i++ ) {\n print i, \"<\" $i \">\"\n }\n n = split($NF,a,/\\047/)\n for ( i=1; i<=n; i++ ) {\n print \"\\t\" NF \".\" i, \"<\" a[i] \">\"\n }\n for ( i=2; i<=n; i+=4 ) {\n print $1, a[i]\n }\n}\n $ awk -f tst.awk file\n=============\nhost1,...,NOV 24, 2022,['Element1', 'Element2'],\"['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\n1 <host1>\n2 <...>\n3 <NOV 24>\n4 < 2022>\n5 <['Element1', 'Element2']>\n6 <\"['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\">\n 6.1 <\"[>\n 6.2 <192.168.x.99>\n 6.3 <, >\n 6.4 <fe80:XX>\n 6.5 <,>\n 6.6 <192.168.x.100>\n 6.7 <, fe80:XX]\">\nhost1 192.168.x.99\nhost1 192.168.x.100\n=============\nhost2,...,NOV 24, 2022,['Element3'],\"['192.168.x.101', 'fe80:XX']\"\n1 <host2>\n2 <...>\n3 <NOV 24>\n4 < 2022>\n5 <['Element3']>\n6 <\"['192.168.x.101', 'fe80:XX']\">\n 6.1 <\"[>\n 6.2 <192.168.x.101>\n 6.3 <, >\n 6.4 <fe80:XX>\n 6.5 <]\">\nhost2 192.168.x.101\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17487397/" ]
74,559,985
<p>I have this ef query that give me the following result</p> <pre><code>IQueryable&lt;A&gt; | Id | count | | 1 | 5 | | 2 | 6 | IQueryable&lt;B&gt; | Id | count | | 1 | 1 | | 2 | 2 | | 3 | 9 | </code></pre> <p>When I do</p> <pre><code>IQueryable&lt;Something&gt; C = A.union(B) </code></pre> <p>Result that I got is this</p> <pre><code>| Id | count | | 1 | 5 | | 2 | 6 | | 1 | 1 | | 2 | 2 | | 3 | 9 | </code></pre> <p>Whish is logical.</p> <p>What I want is a <code>UnionBy(Id)</code></p> <pre><code>IQueryable&lt;Something&gt; C = A.unionBy(B,c=&gt;c.Id) </code></pre> <p>and this work perfectly in my case</p> <pre><code>| Id | count | | 1 | 5 | -- FROM A | 2 | 6 | -- FROM A | 3 | 9 | -- FROM B </code></pre> <p>If the <code>Query</code> <code>A</code> or <code>B</code> are already executed by that I mean a <code>ToList()</code> was made it work perfectly and I have no problem in anyway. But in my case, both queries are not executed and thus using this function result in.</p> <blockquote> <p><code>System.InvalidOperationException</code> query could not be translated.</p> </blockquote> <p>the alternative is to use a <code>GroupBy</code> however I have no idea how to replacte <code>UnionBy</code> behavior with the <code>GroupBy</code></p> <p>FYI: the query works perfectly using the <code>IQueryable.Union</code> and it's mandatory in my case that the request stay in <code>IQueryable</code> and not executed until later</p> <p><strong>UPDATE</strong></p> <p>⚠️ The solution that I'm looking for must stay in <code>IQueryable</code> without a <code>toList()</code> execution</p>
[ { "answer_id": 74560229, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": "' , F ' , -F'[,'\\''=]' awk -F'[,'\\'']' 'NR>1{print $1\" \"$35}' data.csv\n data.csv:\nName,...DATE,COLUMNX,ADDRESSES\nhost1,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\nhost2,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['192.168.xxx.yy', 'fe80:XX','192.168.x.100', fe80:XX]\"\nhost3,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['192.xxx.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\nhost4,['El3', 'El6'],['El7', 'El12'],['El1', 'El2'],['El', 'E12'],NOV 24, 2022,['Element1', 'Element2'],\"['xxx.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\n host1 192.168.x.99\nhost2 192.168.xxx.yy\nhost3 192.xxx.x.99\nhost4 xxx.168.x.99\n" }, { "answer_id": 74560927, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "awk $ ruby -r 'csv' -ne 'lines=$_\n CSV.parse(lines) do |i| \n i.each do |j| \n printf(\"%s \", j)\n end\n puts \"\"\n end' file | \nawk '{gsub(/\\[\\047|\\047\\]|\\047|\\]|,/, \"\", $0)}\n /^host/{for(i=1;i<=NF;i++){if($i~/^[0-9]+\\.+/){print $1, $i}}}'\nhost1 192.168.x.99\nhost1 192.168.x.100\nhost2 192.168.x.101\n" }, { "answer_id": 74560984, "author": "j_b", "author_id": 16482938, "author_profile": "https://Stackoverflow.com/users/16482938", "pm_score": 0, "selected": false, "text": "awk awk -F\",\\\"|\\\"$\" 'NR>1 { \\\ngsub(/\\047|[\\[\\]]/,\"\"); \\\nsplit($2,a,\", \"); \\\nsplit($1,h,\",\"); \\\nfor (n in a) {if (a[n] ~ /^[0-9]/) printf \"%s %s\\n\", h[1], a[n]}}' src.csv\n host1 192.168.x.100\nhost1 192.168.x.99\nhost2 192.168.x.101\n -F\",\\\"|\\\"$\" gsub(/\\047|[\\[\\]]/,\"\"); split($2,a,\", \"); a split($1,h,\",\"); h for (n in a) {if (a[n] ~ /^[0-9]/) printf \"%s %s\\n\", h[1], a[n] a" }, { "answer_id": 74567030, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 0, "selected": false, "text": "FPAT $ cat tst.awk\nBEGIN {\n FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")|([[][^]]+])\"\n}\nNR > 1 {\n n = split($NF,a,/\\047/)\n for ( i=2; i<=n; i+=4 ) {\n print $1, a[i]\n }\n}\n $ awk -f tst.awk file\nhost1 192.168.x.99\nhost1 192.168.x.100\nhost2 192.168.x.101\n FPAT split() ' $ cat tst.awk\nBEGIN {\n FPAT = \"([^,]*)|(\\\"[^\\\"]+\\\")|([[][^]]+])\"\n}\nNR > 1 {\n print \"=============\"\n print\n for ( i=1; i<=NF; i++ ) {\n print i, \"<\" $i \">\"\n }\n n = split($NF,a,/\\047/)\n for ( i=1; i<=n; i++ ) {\n print \"\\t\" NF \".\" i, \"<\" a[i] \">\"\n }\n for ( i=2; i<=n; i+=4 ) {\n print $1, a[i]\n }\n}\n $ awk -f tst.awk file\n=============\nhost1,...,NOV 24, 2022,['Element1', 'Element2'],\"['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\"\n1 <host1>\n2 <...>\n3 <NOV 24>\n4 < 2022>\n5 <['Element1', 'Element2']>\n6 <\"['192.168.x.99', 'fe80:XX','192.168.x.100', fe80:XX]\">\n 6.1 <\"[>\n 6.2 <192.168.x.99>\n 6.3 <, >\n 6.4 <fe80:XX>\n 6.5 <,>\n 6.6 <192.168.x.100>\n 6.7 <, fe80:XX]\">\nhost1 192.168.x.99\nhost1 192.168.x.100\n=============\nhost2,...,NOV 24, 2022,['Element3'],\"['192.168.x.101', 'fe80:XX']\"\n1 <host2>\n2 <...>\n3 <NOV 24>\n4 < 2022>\n5 <['Element3']>\n6 <\"['192.168.x.101', 'fe80:XX']\">\n 6.1 <\"[>\n 6.2 <192.168.x.101>\n 6.3 <, >\n 6.4 <fe80:XX>\n 6.5 <]\">\nhost2 192.168.x.101\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74559985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2954082/" ]
74,560,013
<p>I has been install a ruby version 3.1.2 at my Mac computer and I want to uninstall it completely.</p> <p>When I check by this command</p> <pre><code>which -a ruby </code></pre> <p>It show me this</p> <pre><code>/Users/nguyencuc/.rubies/ruby-3.1.2/bin/ruby /usr/bin/ruby </code></pre> <p>So, as this page said, <a href="https://mac.install.guide/ruby/9.html" rel="nofollow noreferrer">https://mac.install.guide/ruby/9.html</a>, maybe it is a system ruby ?</p> <p>So how can I completely uninstall this ruby to install another version of ruby ? Could you please give me some advices ? Thank you very much for your time.</p>
[ { "answer_id": 74561257, "author": "Taimoor Hassan", "author_id": 13000257, "author_profile": "https://Stackoverflow.com/users/13000257", "pm_score": 0, "selected": false, "text": "rbenv uninstall 3.1.2\n rbenv install *version*\n" }, { "answer_id": 74577550, "author": "Syed Uzair", "author_id": 16464593, "author_profile": "https://Stackoverflow.com/users/16464593", "pm_score": 1, "selected": false, "text": "brew uninstall --force ruby whereis ruby rm" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74560013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15347191/" ]
74,560,023
<pre><code>df = pd.DataFrame({'ID' : ['ID 1', 'ID 1', 'ID 1', 'ID 2', 'ID 2', 'ID 3', 'ID 3'], 'Code' : ['Apple', 'A123', 'Apple', 'Banana', 'Banana', 'K123', 'K123'], 'Code_Type' : ['Code name', 'Code ID', 'Code name', 'Code name', 'Code name', 'Code ID', 'Code ID']} ) df </code></pre> <p>I have a pandas dataframe (~100k rows) that looks something like this.</p> <pre><code>ID Code Code_Type ID 1 Apple Code name ID 1 Apple Code name ID 1 A123 Code ID ID 2 Banana Code name ID 2 Banana Code name ID 3 K123 Code ID ID 3 K123 Code ID </code></pre> <p>I am trying to iterate through my dataframe and for each ID take the code based on conditions around the code type.</p> <p>If an ID has both a code name and a code ID associated to it, then take the code ID value and apply it to the code column.</p> <p>If it has only a code name or a code ID then just pass.</p> <p>So far the setup I have is something like this.</p> <pre><code>for index, value, value2 in zip(df.ID, df.Code, df.Code_Type): print(index, value, value2) </code></pre> <p>However I am not quite sure where to go from here and end up with the resulting dataframe below.</p> <pre><code>ID Code Code_Type ID 1 A123 Code name ID 1 A123 Code name ID 1 A123 Code ID ID 2 Banana Code name ID 2 Banana Code name ID 3 K123 Code ID ID 3 K123 Code ID </code></pre> <p>Ideally I would like to create a dictionary mapping like this and just apply that to the dataframe.</p> <pre><code>{'ID 1' : 'A123', 'ID 2' : 'Banana', 'ID 3' : 'K123'} </code></pre> <p>Any help at all is greatly appreciated.</p>
[ { "answer_id": 74561257, "author": "Taimoor Hassan", "author_id": 13000257, "author_profile": "https://Stackoverflow.com/users/13000257", "pm_score": 0, "selected": false, "text": "rbenv uninstall 3.1.2\n rbenv install *version*\n" }, { "answer_id": 74577550, "author": "Syed Uzair", "author_id": 16464593, "author_profile": "https://Stackoverflow.com/users/16464593", "pm_score": 1, "selected": false, "text": "brew uninstall --force ruby whereis ruby rm" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74560023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589857/" ]
74,560,024
<p>For my data the average normally lies between 8,000 and 10,000 and I want to indicate this range on my bar chart below, I want to show to red lines from y=10,000 and y=8,000 and potentially shade the area in between them, if possible. <a href="https://i.stack.imgur.com/6ll76.png" rel="nofollow noreferrer">Bar chart attachted</a></p> <pre><code>Monthly_accidents2 %&gt;% ggplot(aes(x=Month,y=Traffic_Accidents))+ geom_bar(stat =&quot;identity&quot;,fill = &quot;#97B3C6&quot;)+ geom_text(aes(label = Traffic_Accidents), vjust = 0.5, colour = &quot;white&quot;)+ ylim(0,12000)+ #coord_flip()+ theme_dark()+ labs(x=NULL, y=&quot;Number of traffic accidents&quot;, title = &quot; Traffic Accidents throughout the year&quot;) </code></pre> <p>Thanks for any possible help in advance.</p> <p>I tried creating a data set and adding the two lines but it didn't work.</p>
[ { "answer_id": 74560388, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 1, "selected": false, "text": "geom_hline annotate Monthly_accidents2 <- data.frame(\n Month = factor(month.abb, month.abb),\n Traffic_Accidents = 1000 * seq_len(12)\n)\n\nlibrary(ggplot2)\n\nbase <- ggplot(Monthly_accidents2, aes(x = Month, y = Traffic_Accidents)) +\n geom_col(fill = \"#97B3C6\") +\n geom_text(aes(label = Traffic_Accidents), vjust = 0.5, colour = \"white\") +\n ylim(0, 12000) +\n theme_dark() +\n labs(\n x = NULL,\n y = \"Number of traffic accidents\",\n title = \"Traffic Accidents throughout the year\"\n ) +\n theme(plot.title = element_text(hjust = .5))\n\nbase +\n geom_hline(yintercept = c(8000, 10000), color = \"red\") +\n annotate(geom = \"rect\", ymin = 8000, ymax = 10000, xmin = -Inf, xmax = Inf, fill = \"red\", alpha = .2)\n" }, { "answer_id": 74560427, "author": "Paul Stafford Allen", "author_id": 16730940, "author_profile": "https://Stackoverflow.com/users/16730940", "pm_score": 0, "selected": false, "text": " +\ngeom_hline(aes(yintercept = c(8000, 10000), color = \"red\"))\n" }, { "answer_id": 74560503, "author": "Bowhaven", "author_id": 11844999, "author_profile": "https://Stackoverflow.com/users/11844999", "pm_score": 2, "selected": true, "text": "Monthly_accidents2 %>%\n ggplot(aes(x=Month,y=Traffic_Accidents))+\n geom_bar(stat =\"identity\",fill = \"#97B3C6\")+\n geom_text(aes(label = Traffic_Accidents), vjust = 0.5, colour = \"white\")+\n ylim(0,12000)+\n geom_hline(yintercept = c(8000, 10000), colour = 'red')+\n geom_rect(aes(xmin = min(as.integer(Monthly_accidents2$Month)) - 0.5,\n xmax = max(as.integer(Monthly_accidents2$Month)) + 0.5,\n ymin = 8000, ymax = 10000), alpha = 0.2, fill = 'darkred')+\n #coord_flip()+\n theme_dark()+\n labs(x=NULL,\n y=\"Number of traffic accidents\",\n title = \" Traffic Accidents throughout the year\")\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74560024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16053575/" ]
74,560,025
<p>I need to use a function <code>func(uint8_t* buffer, uint size)</code>; supposing I can't change its parameters, I want to pass it a string.</p> <p>I have a <code>vector&lt;string&gt;</code> that I must convert to <code>uint8_t*</code> and then read it and convert it back to <code>vector&lt;string&gt;</code>. I tried this code for reading (printing) the <code>vector.data()</code> output but it prints garbage:</p> <pre><code>#include &lt;cstdint&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;iostream&gt; int main() { std::string a1 = {&quot;ath&quot;}; std::cout &lt;&lt;&quot;1: &quot;&lt;&lt; a1&lt;&lt;&quot; end\n&quot;; std::vector&lt;std::string&gt; vec; vec.push_back(a1); uint8_t *ptr = reinterpret_cast&lt;uint8_t*&gt;(vec.data()); std::cout &lt;&lt;&quot;2: &quot;&lt;&lt; ptr[0]&lt;&lt;&quot; end\n&quot;; } </code></pre> <p>output:</p> <pre><code>1: ath end 2: � end </code></pre> <p>questions:</p> <ol> <li>why this doesn't work?</li> <li>I saw in some links that they init a <code>std::string</code> with <code>char*</code> array like this:</li> </ol> <pre><code>char *ptr={'a'}; std::string myStr(ptr); </code></pre> <p>I suppose this works because of added '\0', is this related to my problem?</p>
[ { "answer_id": 74560339, "author": "YSC", "author_id": 5470596, "author_profile": "https://Stackoverflow.com/users/5470596", "pm_score": 0, "selected": false, "text": "std::vector<std::string> vec;\n #include <string>\n#include <vector>\n#include <algorithm>\n\nint main(){\n std::vector<std::string> vec;\n // populate\n std::vector<uint8_t*> vec2(vec.size());\n std::transform(begin(vec), end(vec), begin(vec2), [](auto& s){ return reinterpret_cast<unsigned char*>(s.data()); });\n}\n std::basic_string<uint8_t> std::string std::basic_string<char>" }, { "answer_id": 74560358, "author": "Marcus Müller", "author_id": 4433386, "author_profile": "https://Stackoverflow.com/users/4433386", "pm_score": 2, "selected": false, "text": "std::string std::string std::string std::string std::string foo {\"foo\"};\nstd::string bar {\"bar \"};\nstd::string baz {\"bazaz\"};\n\nstd::string complete = foo + bar + baz;\n\nauto* whole_cstring = reinterpret_cast<uint8_t*>(complete.c_str());\n\n// call your C-string-accepting function\nfunc(whole_cstring, complete.length());\n std::vector std::string \nstd::vector<std::string> my_vector_of_strings; \n// insert strings into the vector\n/// … ///\n\nstd::string complete;\nfor(const auto& individual_string : my_vector_of_strings) {\n complete += individual_string;\n}\n\n\nauto* whole_cstring = reinterpret_cast<uint8_t*>(complete.c_str());\n\n// call your C-string-accepting function\nfunc(whole_cstring, complete.length());\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74560025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7047604/" ]
74,560,027
<p>I fetch data from api like this</p> <pre><code>import axios from 'axios' const baseUrl = `${process.env.REACT_APP_URL}/search/users?q=john&amp;per_page=5` export function fetchData(){ axios({ method: &quot;get&quot;, headers: { &quot;Content-Type&quot;: &quot;application/json&quot; }, url: baseUrl, }) .then(function (response) { return response.data; }) .catch(function (error) { return error; }) } </code></pre> <p>and called to another file</p> <pre><code>import {fetchData} from '../../api/service' const dataVal = fetchData() console.log(&quot;data&quot;,dataVal) </code></pre> <p>got undefined in console</p> <p>I am expecting to get array data from the api</p>
[ { "answer_id": 74560339, "author": "YSC", "author_id": 5470596, "author_profile": "https://Stackoverflow.com/users/5470596", "pm_score": 0, "selected": false, "text": "std::vector<std::string> vec;\n #include <string>\n#include <vector>\n#include <algorithm>\n\nint main(){\n std::vector<std::string> vec;\n // populate\n std::vector<uint8_t*> vec2(vec.size());\n std::transform(begin(vec), end(vec), begin(vec2), [](auto& s){ return reinterpret_cast<unsigned char*>(s.data()); });\n}\n std::basic_string<uint8_t> std::string std::basic_string<char>" }, { "answer_id": 74560358, "author": "Marcus Müller", "author_id": 4433386, "author_profile": "https://Stackoverflow.com/users/4433386", "pm_score": 2, "selected": false, "text": "std::string std::string std::string std::string std::string foo {\"foo\"};\nstd::string bar {\"bar \"};\nstd::string baz {\"bazaz\"};\n\nstd::string complete = foo + bar + baz;\n\nauto* whole_cstring = reinterpret_cast<uint8_t*>(complete.c_str());\n\n// call your C-string-accepting function\nfunc(whole_cstring, complete.length());\n std::vector std::string \nstd::vector<std::string> my_vector_of_strings; \n// insert strings into the vector\n/// … ///\n\nstd::string complete;\nfor(const auto& individual_string : my_vector_of_strings) {\n complete += individual_string;\n}\n\n\nauto* whole_cstring = reinterpret_cast<uint8_t*>(complete.c_str());\n\n// call your C-string-accepting function\nfunc(whole_cstring, complete.length());\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74560027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20590242/" ]
74,560,043
<p>I am using <code>dplyr</code> and <code>across</code> to summarise some data:</p> <pre><code>n &lt;- 500 durations &lt;- c(3, 5, 6, 8, 10) prop_fever_resolve &lt;- c(0.5, 0.6, 0.7, 0.8, 0.9) prop_urine_sterile &lt;- c(0.8, 0.85, 0.88, 0.9, 0.93) prop_additional_abx &lt;- c(0.2, 0.17, 0.14, 0.1, 0.05) duration_props &lt;- data.frame(duration = durations, prop_fever_resolve = prop_fever_resolve, prop_urine_sterile = prop_urine_sterile, prop_additional_abx = prop_additional_abx) set.seed(6942069) data &lt;- duration_props %&gt;% slice_sample(n = n, replace = TRUE) %&gt;% rowwise() %&gt;% mutate(fever_resolve = sample(c(FALSE, TRUE), 1, prob = c(1 - prop_fever_resolve, prop_fever_resolve)), urine_sterile = sample(c(FALSE, TRUE), 1, prob = c(1 - prop_urine_sterile, prop_urine_sterile)), additional_abx = sample(c(FALSE, TRUE), 1, prob = c(1 - prop_additional_abx, prop_additional_abx)), cured = fever_resolve &amp; urine_sterile &amp; !additional_abx) data %&gt;% group_by(across(&quot;duration&quot;)) %&gt;% summarize(n = n(), pos = across(&quot;cured&quot;, sum), prop = pos / n) duration n pos$cured prop$cured &lt;dbl&gt; &lt;int&gt; &lt;int&gt; &lt;dbl&gt; 1 3 95 37 0.389 2 5 106 38 0.358 3 6 98 59 0.602 4 8 105 69 0.657 5 10 96 82 0.854 </code></pre> <p>Why are my column names called <code>pos$cured</code> and <code>prop$cured</code>?</p>
[ { "answer_id": 74560163, "author": "harre", "author_id": 4786466, "author_profile": "https://Stackoverflow.com/users/4786466", "pm_score": 1, "selected": false, "text": "across across library(dplyr)\n\ndata %>%\n group_by(duration) %>%\n summarize(n = n(),\n pos = sum(cured),\n prop = pos / n)\n # A tibble: 5 × 4\n duration n pos prop\n <dbl> <int> <int> <dbl>\n1 3 95 37 0.389\n2 5 106 38 0.358\n3 6 98 59 0.602\n4 8 105 69 0.657\n5 10 96 82 0.854\n" }, { "answer_id": 74560188, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": false, "text": "across tibble pos cured str library(dplyr)\n\nfoo <- data %>%\n group_by(across(\"duration\")) %>%\n summarize(n = n(),\n pos = across(\"cured\", sum),\n prop = pos / n)\n\nstr(foo)\n#> tibble [5 × 4] (S3: tbl_df/tbl/data.frame)\n#> $ duration: num [1:5] 3 5 6 8 10\n#> $ n : int [1:5] 95 106 98 105 96\n#> $ pos : tibble [5 × 1] (S3: tbl_df/tbl/data.frame)\n#> ..$ cured: int [1:5] 37 38 59 69 82\n#> $ prop :'data.frame': 5 obs. of 1 variable:\n#> ..$ cured: num [1:5] 0.389 0.358 0.602 0.657 0.854\n across .names data %>%\n group_by(across(\"duration\")) %>%\n summarize(n = n(),\n across(\"cured\", sum, .names = \"pos\"),\n prop = pos / n)\n#> # A tibble: 5 × 4\n#> duration n pos prop\n#> <dbl> <int> <int> <dbl>\n#> 1 3 95 37 0.389\n#> 2 5 106 38 0.358\n#> 3 6 98 59 0.602\n#> 4 8 105 69 0.657\n#> 5 10 96 82 0.854\n" } ]
2022/11/24
[ "https://Stackoverflow.com/questions/74560043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19414769/" ]