qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,504,540
<p>I have a date in Pyspark dataframe in &quot;String&quot; format as &quot;dd-MMM-yyyy ( eg &quot;01-Jan-2022&quot;). I want to convert this to date with the same format so the Output should be</p> <pre><code>01-Jan-2022 </code></pre> <p>The code i am using for this is as below, but the format doesn't convert properly. It converts the date to &quot;dd-MM-yyyy&quot; format (ie 01-01-2022), whereas i want it in &quot;dd-MMM-yyyy&quot;(ie &quot;01-Jan-2022&quot;) format.</p> <p>My code is here:</p> <pre><code>df = df.withColumn(&quot;mydate&quot;,F.to_date(df.mydate,&quot;dd-MMM-yyyy&quot;)) </code></pre> <p>This results in date type converted to &quot;date&quot; from &quot;string&quot; but the format doesn't convert properly.</p>
[ { "answer_id": 74504599, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 3, "selected": true, "text": "yes useMemo useMemo useMemo tw App className useMemo tw className App useMemo export default function App() {\n const [_, s] = useState(0);\n\n return (\n <div className=\"App\">\n <div className={tw(false, 'w-full', 'h-full', 'bg-red-500')}>div1</div>\n <div\n className={useMemo(\n () => tw(true, 'w-full', 'h-full', 'bg-red-500'),\n [],\n )}\n >\n div2\n </div>\n\n <button onClick={() => s(Math.random())}>re-render</button>\n </div>\n );\n}\n" }, { "answer_id": 74504607, "author": "Tomer_Ra", "author_id": 11971765, "author_profile": "https://Stackoverflow.com/users/11971765", "pm_score": -1, "selected": false, "text": "const Example = () => {\n\n const onInputChange = (e) => {\n const text = e.target.value\n\n // do something with text\n }\n\n\n return (\n <div>\n <input onChange={(e: any) => onInputChange(e)} />\n <div\n className={useMemo(() => tw(\n 'w-full',\n 'h-full',\n 'bg-red-500'\n ), [])}\n >\n hello\n </div>\n </div>\n )\n}\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18627728/" ]
74,504,558
<p>I want to let the user to enter three different arguments without changing the order of the output</p> <blockquote> </blockquote> <pre><code>function check_status($a, $b, $c) { Some stuff } // Needed Output echo check_status(&quot;User&quot;, 38, true); // &quot;Hello User, Your Age Is 38, You Are Available For Hire&quot; echo check_status(38, &quot;User&quot;, true); // &quot;Hello User, Your Age Is 38, You Are Available For Hire&quot; echo check_status(true, 38, &quot;Osama&quot;); // &quot;Hello User, Your Age Is 38, You Are Available For Hire&quot; echo check_status(false, &quot;User&quot;, 38); // &quot;Hello User, Your Age Is 38, You Are Not Available For Hire&quot; </code></pre> <p>I have tried if statements didn't went well</p>
[ { "answer_id": 74504775, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 1, "selected": true, "text": "<?php\nfunction check_status($a, $b, $c) {\n $name = null;\n $age = null;\n $availability = null;\n if (is_string($a)) $name = $a;\n if (is_string($b)) $name = $b;\n if (is_string($c)) $name = $c;\n \n if (is_int($a)) $age = $a;\n if (is_int($b)) $age = $b;\n if (is_int($c)) $age = $c;\n \n if (is_bool($a)) $availability = $a;\n if (is_bool($b)) $availability = $b;\n if (is_bool($c)) $availability = $c;\n\n $availableString = $availability ? \"available\" : \"not available\";\n echo \"Hello $name, your age is $age, you are $availableString for hire \\n\";\n}\n\ncheck_status(\"John\", 26, true);\ncheck_status(26, \"John\", true);\ncheck_status(true, 26, \"John\");\ncheck_status(true, \"John\", 26);\ncheck_status(false, \"John\", 26);\n?>\n Hello John, your age is 26, you are available for hire \nHello John, your age is 26, you are available for hire \nHello John, your age is 26, you are available for hire \nHello John, your age is 26, you are available for hire \nHello John, your age is 26, you are not available for hire\n" }, { "answer_id": 74505344, "author": "Amir Shakya", "author_id": 19826432, "author_profile": "https://Stackoverflow.com/users/19826432", "pm_score": 1, "selected": false, "text": "function check_status($params) { \n $availability = $params['availability'] ?? false;\n $name = $params['name'] ?? '';\n $age = $params['age'] ?? 0;'enter code here'\n $availableString = $availability ? \"available\" : \"not available\";\n echo \"Hello $name, your age is $age, you are $availableString for hire\";\n }" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551041/" ]
74,504,560
<p>I have this dictionary, and when I code for it, I only have the answer for June, May, September. How would I code for the months that are not given in the dictionary? Obviously, I have zero for them.</p> <pre><code>{'account': 'Amazon', 'amount': 300, 'day': 3, 'month': 'June'} {'account': 'Facebook', 'amount': 550, 'day': 5, 'month': 'May'} {'account': 'Google', 'amount': -200, 'day': 21, 'month': 'June'} {'account': 'Amazon', 'amount': -300, 'day': 12, 'month': 'June'} {'account': 'Facebook', 'amount': 130, 'day': 7, 'month': 'September'} {'account': 'Google', 'amount': 250, 'day': 27, 'month': 'September'} {'account': 'Amazon', 'amount': 200, 'day': 5, 'month': 'May'} </code></pre> <p>The method I used for months mentioned in the dictionary:</p> <p><code>year_balance=sum(d[&quot;amount&quot;] for d in my_dict) print(f&quot;The total year balance is {year_balance} $.&quot;)</code></p>
[ { "answer_id": 74504604, "author": "Montreal", "author_id": 17696292, "author_profile": "https://Stackoverflow.com/users/17696292", "pm_score": -1, "selected": false, "text": "wages = {'01': 910.56, '02': 1298.68, '03': 1433.99, '04': 1050.14, '05': 877.67}\ntotal = sum(wages.values())\nprint('Total Wages: ${0:,.2f}'.format(total))\n" }, { "answer_id": 74504609, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "import calendar\n\nmonths = calendar.month_name[1:]\nresults = dict(zip(months, [0]*len(months)))\n\nfor d in data:\n results[d[\"month\"]] += d[\"amount\"]\n\n# then you have results dict with monthly amounts\n# sum everything to get yearly total\ntotal = sum(results.values())\n" }, { "answer_id": 74504612, "author": "kakben", "author_id": 5550697, "author_profile": "https://Stackoverflow.com/users/5550697", "pm_score": 0, "selected": false, "text": "from collections import defaultdict\nmydict = defaultdict(lambda: 0)\nprint(mydict[\"January\"])\n your_list_of_dicts = [\n {\"January\": 3, \"March\": 5},\n {\"January\": 3, \"April\": 5}\n]\n\nimport calendar\nmonths = calendar.month_name[1:]\n\nmonth_totals = dict()\nfor month in months:\n month_totals[month] = 0\n for d in your_list_of_dicts:\n month_totals[month] += d[month] if month in d else 0\n\nprint(month_totals)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544158/" ]
74,504,566
<p>From Windows 10 command line , Python 3.9.13, in directory:</p> <pre><code>C:\Users\foo.bar\wks\df\data </code></pre> <p>when trying to run :</p> <pre><code>python unilm\\layoutlm\\examples\\seq_labeling\\preprocess.py --data_dir FUNSD\\training_data\\annotations --data_split train --output_dir data --model_name_or_path microsoft/layoutlm-base-uncased --max_len 510 </code></pre> <p>I get this error:</p> <pre><code>python: can't open file 'C:\Users\foo.bar\wks\df\data\unilm\layoutlm\examples\seq_labeling\preprocess.py': [Errno 2] No such file or directory </code></pre> <p>Notwithstanding the path <code>C:\Users\foo.bar\wks\df\data\unilm\layoutlm\examples\seq_labeling\preprocess.py'</code> is correct, really exists.</p> <p>What's wrong?</p>
[ { "answer_id": 74504604, "author": "Montreal", "author_id": 17696292, "author_profile": "https://Stackoverflow.com/users/17696292", "pm_score": -1, "selected": false, "text": "wages = {'01': 910.56, '02': 1298.68, '03': 1433.99, '04': 1050.14, '05': 877.67}\ntotal = sum(wages.values())\nprint('Total Wages: ${0:,.2f}'.format(total))\n" }, { "answer_id": 74504609, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "import calendar\n\nmonths = calendar.month_name[1:]\nresults = dict(zip(months, [0]*len(months)))\n\nfor d in data:\n results[d[\"month\"]] += d[\"amount\"]\n\n# then you have results dict with monthly amounts\n# sum everything to get yearly total\ntotal = sum(results.values())\n" }, { "answer_id": 74504612, "author": "kakben", "author_id": 5550697, "author_profile": "https://Stackoverflow.com/users/5550697", "pm_score": 0, "selected": false, "text": "from collections import defaultdict\nmydict = defaultdict(lambda: 0)\nprint(mydict[\"January\"])\n your_list_of_dicts = [\n {\"January\": 3, \"March\": 5},\n {\"January\": 3, \"April\": 5}\n]\n\nimport calendar\nmonths = calendar.month_name[1:]\n\nmonth_totals = dict()\nfor month in months:\n month_totals[month] = 0\n for d in your_list_of_dicts:\n month_totals[month] += d[month] if month in d else 0\n\nprint(month_totals)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226649/" ]
74,504,574
<p><a href="https://i.stack.imgur.com/n8Wax.png" rel="nofollow noreferrer">enter image description here</a>I'm trying to populate the data in the html table with jquery and all columns get undefined error</p> <p>Html:</p> <pre><code>&lt;table id=&quot;example&quot; class=&quot;table table-striped&quot; style=&quot;width:100%&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;1&lt;/th&gt; &lt;th&gt;2&lt;/th&gt; &lt;th&gt;3&lt;/th&gt; &lt;th&gt;4&lt;/th&gt; &lt;th&gt;5&lt;/th&gt; &lt;th&gt;6&lt;/th&gt; &lt;th&gt;7&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>with the following instruction jquery</p> <pre><code>&lt;script&gt; $(document).ready(function () { // FETCHING DATA FROM JSON FILE $.getJSON(&quot;http://localhost:8089/projectw/ServletJSON&quot;, function (data) { var e= &quot;&quot;; // ITERATING THROUGH OBJECTS $.each(data, function (key, value) { //CONSTRUCTION OF ROWS HAVING // DATA FROM JSON OBJECT e += '&lt;tr&gt;'; e += '&lt;td&gt;' + value.ag + '&lt;/td&gt;'; e += '&lt;td&gt;' + value.pa + '&lt;/td&gt;'; e += '&lt;td&gt;' + value.ex + '&lt;/td&gt;'; e += '&lt;td&gt;' + value.em + '&lt;/td&gt;'; e += '&lt;td&gt;' + value.at + '&lt;/td&gt;'; e += '&lt;td&gt;' + value.ct + '&lt;/td&gt;'; e += '&lt;td&gt;' + value.num_ex + '&lt;/td&gt;'; e += '&lt;/tr&gt;'; }); //INSERTING ROWS INTO TABLE $('#example').append(e); }); }); &lt;/script&gt; </code></pre> <p>json example in servlet:</p> <pre><code>{ &quot;JsonTest&quot;: [ { &quot;ag&quot;: &quot;RAX&quot;, &quot;pa&quot;: &quot;pa 1&quot;, &quot;ex&quot;: &quot;RXTT&quot;, &quot;em&quot;: &quot;ME&quot;, &quot;at&quot;: 1, &quot;ct&quot;: 0, &quot;num_ex&quot;: &quot;1&quot; }, { &quot;ag&quot;: &quot;TOM&quot;, &quot;pa&quot;: &quot;pa 2&quot;, &quot;ex&quot;: &quot;TOCC&quot;, &quot;em&quot;: &quot;MB&quot;, &quot;at&quot;: 0, &quot;ct&quot;: 0, &quot;num_ex&quot;: &quot;2&quot; } ] } </code></pre> <p>Observation If I order to display the json text (</p> <pre><code> var req = new XMLHttpRequest(); req.open('GET', 'http://localhost:8089/projectw/ServletJSON', true); req.send(); req.onload = function(){ var json=JSON.parse(req.responseText); document.getElementsByClassName('message(class of table example)')[0].innerHTML = JSON.stringify(json) </code></pre> <p>), I get success but to populate the table no. how could i adjust this? thank you all !</p> <p>Expected lines to be filled with json values, no errors in console.</p>
[ { "answer_id": 74504604, "author": "Montreal", "author_id": 17696292, "author_profile": "https://Stackoverflow.com/users/17696292", "pm_score": -1, "selected": false, "text": "wages = {'01': 910.56, '02': 1298.68, '03': 1433.99, '04': 1050.14, '05': 877.67}\ntotal = sum(wages.values())\nprint('Total Wages: ${0:,.2f}'.format(total))\n" }, { "answer_id": 74504609, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "import calendar\n\nmonths = calendar.month_name[1:]\nresults = dict(zip(months, [0]*len(months)))\n\nfor d in data:\n results[d[\"month\"]] += d[\"amount\"]\n\n# then you have results dict with monthly amounts\n# sum everything to get yearly total\ntotal = sum(results.values())\n" }, { "answer_id": 74504612, "author": "kakben", "author_id": 5550697, "author_profile": "https://Stackoverflow.com/users/5550697", "pm_score": 0, "selected": false, "text": "from collections import defaultdict\nmydict = defaultdict(lambda: 0)\nprint(mydict[\"January\"])\n your_list_of_dicts = [\n {\"January\": 3, \"March\": 5},\n {\"January\": 3, \"April\": 5}\n]\n\nimport calendar\nmonths = calendar.month_name[1:]\n\nmonth_totals = dict()\nfor month in months:\n month_totals[month] = 0\n for d in your_list_of_dicts:\n month_totals[month] += d[month] if month in d else 0\n\nprint(month_totals)\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20499642/" ]
74,504,581
<p>I need to insert data in a binary file in a way that every insertion is a block of 100 positions, for example. Since I know where it starts, I could easily use fseek/seekg to access elements 0 * 100, 1 * 100, 2 * 100,... n * 100. So how could I guarantee that every insertion ends in a position k * 100?</p> <p>Or, alternatively, is it possible that I can add registers to an file in a way that I can iterate over them as if they were a array?</p>
[ { "answer_id": 74504675, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 1, "selected": false, "text": "i i for(int i=0;i<10;i++)\n{\n fwrite(&i,sizeof(i),1,fp);\n}\n for(int i=0;i<10;i++)\n{\n fwrite(&i,sizeof(int),1,fp);\n}\n 0 i" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20203803/" ]
74,504,583
<p>My mission is: SMS Code input separately and <strong>inputs have to be just one number.</strong></p> <p>My inputs jump from one line to the next, and while pressing backspace deletes them backwards, it also allows for multiple number entries, which I don't want.</p> <p>I have an SMS code section, like this: <a href="https://i.stack.imgur.com/vu7Bp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vu7Bp.png" alt="enter image description here" /></a></p> <p>and my HTML code like this:</p> <pre><code>&lt;form class=&quot;form__group form__pincode&quot;&gt; &lt;input class=&quot;pincode&quot; type=&quot;number&quot; placeholder=&quot;·&quot; tabindex=&quot;1&quot; name=&quot;pincode-1&quot; id=&quot;txt1&quot; max=&quot;1&quot; maxlength=&quot;1&quot; onkeydown=&quot;move(event, '', 'txt1', 'txt2')&quot; autocomplete=&quot;off&quot;&gt; &lt;input class=&quot;pincode&quot; type=&quot;number&quot; placeholder=&quot;·&quot; tabindex=&quot;2&quot; name=&quot;pincode-1&quot; id=&quot;txt2&quot; max=&quot;1&quot; maxlength=&quot;1&quot; onkeydown=&quot;move(event, 'txt1', 'txt2', 'txt3')&quot; autocomplete=&quot;off&quot;&gt; &lt;input class=&quot;pincode&quot; type=&quot;number&quot; placeholder=&quot;·&quot; tabindex=&quot;3&quot; name=&quot;pincode-1&quot; id=&quot;txt3&quot; max=&quot;1&quot; maxlength=&quot;1&quot; onkeydown=&quot;move(event, 'txt2', 'txt3', 'txt4')&quot; autocomplete=&quot;off&quot;&gt; &lt;input class=&quot;pincode&quot; type=&quot;number&quot; placeholder=&quot;·&quot; tabindex=&quot;4&quot; name=&quot;pincode-1&quot; id=&quot;txt4&quot; max=&quot;1&quot; maxlength=&quot;1&quot; onkeydown=&quot;move(event, 'txt3', 'txt4', 'txt5')&quot; autocomplete=&quot;off&quot;&gt; &lt;input class=&quot;pincode&quot; type=&quot;number&quot; placeholder=&quot;·&quot; tabindex=&quot;5&quot; name=&quot;pincode-1&quot; id=&quot;txt5&quot; max=&quot;1&quot; maxlength=&quot;1&quot; onkeydown=&quot;move(event, 'txt4', 'txt5', 'txt6')&quot; autocomplete=&quot;off&quot;&gt; &lt;input class=&quot;pincode&quot; type=&quot;number&quot; placeholder=&quot;·&quot; tabindex=&quot;6&quot; name=&quot;pincode-1&quot; id=&quot;txt6&quot; max=&quot;1&quot; maxlength=&quot;1&quot; onkeydown=&quot;move(event, 'txt5', 'txt6', '')&quot; autocomplete=&quot;off&quot;&gt; &lt;/form&gt; </code></pre> <p>and my function like this :</p> <pre><code>function move(e, p, c, n) { var length = document.getElementById(c).value.length; var maxlength = document.getElementById(c).getAttribute(&quot;maxlength&quot;); if (length == maxlength) { if (n !== &quot;&quot;) { document.getElementById(n).focus(); } } if (e.key === &quot;Backspace&quot;) { if (p !== &quot;&quot;) { document.getElementById(p).focus(); } } } </code></pre>
[ { "answer_id": 74504675, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 1, "selected": false, "text": "i i for(int i=0;i<10;i++)\n{\n fwrite(&i,sizeof(i),1,fp);\n}\n for(int i=0;i<10;i++)\n{\n fwrite(&i,sizeof(int),1,fp);\n}\n 0 i" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16296778/" ]
74,504,619
<p>My problem is that I want to take data from .json file, and initialize with it a list of objects.</p> <p>I have my .json file:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;Card1&quot;: { &quot;Name&quot;: &quot;Kyiv&quot;, &quot;price&quot;: 200, &quot;taxes&quot;: 150 }, &quot;Card2&quot;: { &quot;Name&quot;: &quot;Kamiyanske&quot;, &quot;price&quot;: 150, &quot;taxes&quot;: 100 }, &quot;Card3&quot;: { &quot;Name&quot;: &quot;Rivne&quot;, &quot;price&quot;: 150, &quot;taxes&quot;: 100 } } </code></pre> <p>I want to take this data and fill in objects, and create a list of them</p> <p>This is my try to do so</p> <pre><code>List&lt;Card&gt; LoadJson() { using (StreamReader r = new StreamReader(&quot;C:\\fileName.json&quot;)) { string json = r.ReadToEnd(); var items = JsonConvert.DeserializeObject&lt;List&lt;Card&gt;&gt;(json); return items; } } var Cards = LoadJson(); Console.WriteLine(Cards[0].Name); </code></pre> <p>But every time I get an exception:</p> <blockquote> <p>Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {&quot;name&quot;:&quot;value&quot;}) into type 'System.Collections.Generic.List`1[WpfApp1.Card]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3])</p> </blockquote>
[ { "answer_id": 74506313, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": " using (StreamReader r = new StreamReader(\"C:\\\\fileName.json\"))\n {\n string json = r.ReadToEnd();\n dynamic items = JsonConvert.DeserializeObject(json);\n\n List<Card> cards = new List<Card>();\n\n foreach(var item in items)\n {\n var jsonString = JsonConvert.SerializeObject(item.Value);\n Card card = JsonConvert.DeserializeObject<Card>(jsonString);\n cards.Add(card);\n }\n\n return cards;\n }\n" }, { "answer_id": 74508633, "author": "Serge", "author_id": 11392290, "author_profile": "https://Stackoverflow.com/users/11392290", "pm_score": 2, "selected": false, "text": "List<Card> items = JObject.Parse(json).Properties().Select(jo =>jo.Value.ToObject<Card>() ).ToList();\n" }, { "answer_id": 74518000, "author": "Peter Csala", "author_id": 13268855, "author_profile": "https://Stackoverflow.com/users/13268855", "pm_score": 1, "selected": false, "text": "JsonConverter class CardListConverter : JsonConverter\n{\n public override bool CanConvert(Type objectType)\n {\n return objectType == typeof(List<Card>);\n }\n\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n {\n return (from JProperty prop in JObject.Load(reader).Properties()\n select prop.Value.ToObject<Card>())\n .ToList();\n }\n\n public override bool CanWrite\n {\n get { return false; }\n }\n\n public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n {\n throw new NotImplementedException();\n }\n}\n var settings = new JsonSerializerSettings { Converters = { new CardListConverter() } };\nvar cards = JsonConvert.DeserializeObject<List<Card>>(json, settings);\n" } ]
2022/11/19
[ "https://Stackoverflow.com/questions/74504619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18286506/" ]
74,504,679
<p>I am trying to build a simple game and I would like Python to return a message when a player enters a negative number. My issue is that negative numbers are interpreted as strings when the player tries to enter them.</p> <p>Here is my script:</p> <pre><code>while True: user_guess = input(&quot;Guess a number: &quot;) if user_guess.isdigit(): user_guess = int(user_guess) if user_guess &lt; 0: print(&quot;Too low, guess a number between 0 and 10.&quot;) if user_guess &gt; 10: print(&quot;Too high, guess a number between 0 and 10.&quot;) else: print(&quot;It is not a number.&quot;) break </code></pre>
[ { "answer_id": 74504718, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": -1, "selected": false, "text": "def input_number(message):\n while True:\n user_guess = input(message)\n try:\n n = int(user_guess)\n if n < 0:\n print(\"Too low, guess a number between 0 and 10.\")\n elif n > 10:\n print(\"Too high, guess a number between 0 and 10.\")\n else:\n return n\n except ValueError:\n print(\"It is not a number. Try again\")\n continue\n\n\nif __name__ == '__main__':\n number = input_number(\"Guess a number.\")\n print(\"Your number\", number)\n" }, { "answer_id": 74504719, "author": "kakben", "author_id": 5550697, "author_profile": "https://Stackoverflow.com/users/5550697", "pm_score": -1, "selected": false, "text": "user_guess = None\nwhile user_guess is None:\n inp = input(\"Guess a number: \")\n\n try:\n nr_inp = int(inp)\n except ValueError:\n print(\"It is not a number.\")\n continue\n\n if nr_inp < 0:\n print(\"Too low, guess a number between 0 and 10.\")\n elif nr_inp > 10:\n print(\"Too high, guess a number between 0 and 10.\")\n else:\n user_guess = nr_inp\n\nprint(\"Done:\", user_guess)\n" }, { "answer_id": 74504733, "author": "Adam Smith", "author_id": 3058609, "author_profile": "https://Stackoverflow.com/users/3058609", "pm_score": 0, "selected": false, "text": "user_guess = input(\"Guess a number: \")\nif is_positive_or_negative_number(user_guess):\n user_guess = int(user_guess)\n# continue as before\n\ndef is_positive_or_negative_number(s: str) -> bool:\n \"\"\"Checks if a given string represents a positive or negative number\"\"\"\n if s.startswith('-'):\n s = s[1:] # strip off the optional leading unary negation\n return s.isdigit() # do not allow decimals, so no need to worry\n # about allowing a \".\"\n while True:\n user_guess = input(\"Guess a number: \")\n try:\n user_guess = int(user_guess)\n except ValueError:\n print(\"It is not a number.\")\n break\n # if we get here, user_guess is guaranteed to be an int\n # and int(user_guess) knows how to parse positive and\n # negative numbers\n if user_guess < 0:\n print(\"Too low, guess a number between 0 and 10.\")\n elif user_guess > 10:\n print(\"Too high, guess a number between 0 and 10.\")\n" }, { "answer_id": 74504779, "author": "Ayoife", "author_id": 17769960, "author_profile": "https://Stackoverflow.com/users/17769960", "pm_score": 0, "selected": false, "text": "user_guess.isdigit() while True:\n user_guess = input(\"Guess a number: \")\n try:\n user_guess = int(user_guess)\n if user_guess < 0:\n print(\"Too low, guess a number between 0 and 10.\")\n if user_guess > 10:\n print(\"Too high, guess a number between 0 and 10.\")\n except ValueError:\n print(\"It is not a number.\")\n break\n int() try-except ValueError int()" }, { "answer_id": 74504801, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 0, "selected": false, "text": "while True:\n try:\n user_guess = int( input( \"Guess a number: \"))\n except ValueError:\n print( \"It is not a number.\")\n break # exit loop\n # validate user entry\n if user_guess < 0:\n print(\"Too low...\")\n continue\n elif user_guess > 10:\n print(\"Too high...\")\n continue\n # do processing\n ...\n\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551136/" ]
74,504,697
<p>I'm new in bash scripting and I'm trying to make a script which split a large file in multiple files. I succeeded with case statement but how can I make it without case statement? For example If I have a file with 30 millions of lines (some database file). Thank you in advance!</p> <pre><code>echo File which one you want to split read pathOfFile echo countLines=`wc -l &lt; $pathOfFile` echo The file has $countLines lines echo echo In how many files do you want to split? echo -e &quot;a = 2 files\nb = 3 files\nc = 4 files\nd = 5 files\ne = 10 files\nf = 25 files&quot; read numberOfFiles echo echo The files name with should start: read nameForFiles echo #Split the file case $numberOfFiles in a) split -l $(($countLines / 2)) $pathOfFile $nameForFiles;; b) split -l $(($countLines / 3)) $pathOfFile $nameForFiles;; c) split -l $(($countLines / 4)) $pathOfFile $nameForFiles;; d) split -l $(($countLines / 5)) $pathOfFile $nameForFiles;; e) split -l $(($countLines / 10)) $pathOfFile $nameForFiles;; f) split -l $(($countLines / 25)) $pathOfFile $nameForFiles;; *) echo Invalid choice. esac </code></pre>
[ { "answer_id": 74505532, "author": "Maximilian Ballard", "author_id": 6060841, "author_profile": "https://Stackoverflow.com/users/6060841", "pm_score": 2, "selected": true, "text": "# ...\n\nz=('2' '3' '4' '5' '10' '25')\nx=$(( $(printf '%d' \"'$numberOfFiles\") -97 ))\n\nif [[ $x -lt \"${#z[@]}\" ]] && [[ $x -ge '0' ]] ; then\n split -l $(($countLines / ${z[x]})) $pathOfFile $nameForFiles\nelse\n echo \"Invalid choice\"\nfi\n z" }, { "answer_id": 74557645, "author": "CrazyCat", "author_id": 20550025, "author_profile": "https://Stackoverflow.com/users/20550025", "pm_score": 0, "selected": false, "text": "echo File which one you want to split\nread pathOfFile\necho\ncountLines=`wc -l < $pathOfFile`\necho The file has $countLines lines\necho\necho In how many files do you want to split?\nread numberOfFiles\necho\necho The files name with should start:\nread nameForFiles\necho\n\n#Split the file\nif [[ -n ${numberOfFiles//[0-9]/} ]];\n then\n echo You type something else than a number. - Bye\n exit 1\nelse\n split -l $(($countLines / $numberOfFiles)) -a 3 -d $pathOfFiles $nameForFiles\nfi\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550025/" ]
74,504,714
<p>GHC 9.2.4 gives a multiple declaration error for the following code:</p> <pre><code>data X = A | B | C data Y = A | B | C </code></pre> <p>There are so many new extensions in GHC nowadays. Is there one that allows me to do the above (since it is semantically appropriate for my problem domain) or is the common solution still to prefix, like <code>data X = XA | XB | XC</code> ?</p>
[ { "answer_id": 74505532, "author": "Maximilian Ballard", "author_id": 6060841, "author_profile": "https://Stackoverflow.com/users/6060841", "pm_score": 2, "selected": true, "text": "# ...\n\nz=('2' '3' '4' '5' '10' '25')\nx=$(( $(printf '%d' \"'$numberOfFiles\") -97 ))\n\nif [[ $x -lt \"${#z[@]}\" ]] && [[ $x -ge '0' ]] ; then\n split -l $(($countLines / ${z[x]})) $pathOfFile $nameForFiles\nelse\n echo \"Invalid choice\"\nfi\n z" }, { "answer_id": 74557645, "author": "CrazyCat", "author_id": 20550025, "author_profile": "https://Stackoverflow.com/users/20550025", "pm_score": 0, "selected": false, "text": "echo File which one you want to split\nread pathOfFile\necho\ncountLines=`wc -l < $pathOfFile`\necho The file has $countLines lines\necho\necho In how many files do you want to split?\nread numberOfFiles\necho\necho The files name with should start:\nread nameForFiles\necho\n\n#Split the file\nif [[ -n ${numberOfFiles//[0-9]/} ]];\n then\n echo You type something else than a number. - Bye\n exit 1\nelse\n split -l $(($countLines / $numberOfFiles)) -a 3 -d $pathOfFiles $nameForFiles\nfi\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002430/" ]
74,504,720
<p>I have one row of temperature data in a text file that I would like to convert to a single column and save as a CSV file using a PowerShell script. The temperatures are separated by commas and look like this:</p> <pre><code>21,22,22,22,22,22,22,20,19,18,17,16,15,14,13,12,11,10,9,9,9,8,8,9,8,8,8,9,9,8,8,8,9,9,9,8,8,8,8,8,9,10,12,14,15,17,19,20,21,21,21,21,21,21,21,21,21,21,21,20,20,20,20,20,22,24,25,26,27,27,27,28,28,28,29,29,29,28,28,28,28,28,28,27,27,27,27,27,29,30,32,32,32,32,33,34,35,35,34,33,32,32,31,31,30,30,29,29,28,28,27,28,29,31,33,34,35,35,35,36,36,36,36,36,36,36,36,36,37,37,37,37,37,37,38,39,40,42,43,43,43,43,43,42,42,42,41,41,41,41,40,39,37,36,35,34,33,32,31,31,31,31,31,31,31,31,31,31, </code></pre> <p>I have tried several methods based on searches in this forum I thought this might work but it returns an error: <a href="https://stackoverflow.com/questions/46212269/transpose-rows-to-columns-in-powershell">Transpose rows to columns in PowerShell</a></p> <p>This is the modified code I tried that returns: Error: &quot;Input string was not in a correct format.&quot;</p> <pre><code>$txt = Get-Content 'C:myfile.txt' | Out-String $txt -split '(?m)^,\r?\n' | ForEach-Object { # create empty array $row = @() $arr = $_ -split '\r?\n' $k = 0 for ($n = 0; $n -lt $arr.Count; $n += 2) { $i = [int]$arr[$n] # if index from record ($i) is greater than current index ($k) append # required number of empty fields for ($j = $k; $j -lt $i-1; $j++) { $row += $null } $row += $arr[$n+1] $k = $i } $row -join '|' } </code></pre> <p>This seems like it should be simple to do with only one row of data. Are there any suggestions on how to convert this single row of numbers to one column?</p>
[ { "answer_id": 74505532, "author": "Maximilian Ballard", "author_id": 6060841, "author_profile": "https://Stackoverflow.com/users/6060841", "pm_score": 2, "selected": true, "text": "# ...\n\nz=('2' '3' '4' '5' '10' '25')\nx=$(( $(printf '%d' \"'$numberOfFiles\") -97 ))\n\nif [[ $x -lt \"${#z[@]}\" ]] && [[ $x -ge '0' ]] ; then\n split -l $(($countLines / ${z[x]})) $pathOfFile $nameForFiles\nelse\n echo \"Invalid choice\"\nfi\n z" }, { "answer_id": 74557645, "author": "CrazyCat", "author_id": 20550025, "author_profile": "https://Stackoverflow.com/users/20550025", "pm_score": 0, "selected": false, "text": "echo File which one you want to split\nread pathOfFile\necho\ncountLines=`wc -l < $pathOfFile`\necho The file has $countLines lines\necho\necho In how many files do you want to split?\nread numberOfFiles\necho\necho The files name with should start:\nread nameForFiles\necho\n\n#Split the file\nif [[ -n ${numberOfFiles//[0-9]/} ]];\n then\n echo You type something else than a number. - Bye\n exit 1\nelse\n split -l $(($countLines / $numberOfFiles)) -a 3 -d $pathOfFiles $nameForFiles\nfi\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18365124/" ]
74,504,770
<p>My code I currently have is below, I want to put a filled in red circle where I have the plt.text below. How would I do that?</p> <pre><code>plt.plot('Month', 'Total Profit', data=fruit_sales_df, color='g', ls='--') plt.ylim(35000, 74999) plt.text(11, 70476, '70476') plt.title(&quot;Total Profit Trend by Month&quot;) plt.xlabel(&quot;Month&quot;) plt.ylabel(&quot;Total Profit&quot;) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.show() </code></pre>
[ { "answer_id": 74504852, "author": "BlacKow", "author_id": 1416371, "author_profile": "https://Stackoverflow.com/users/1416371", "pm_score": 2, "selected": false, "text": "import matplotlib.pyplot as plt\n\nplt.plot([1, 2], [3, 4], color='g', ls='--')\nplt.text(1.5, 3.7, '70476')\nplt.plot(1.5, 3.5, color='red', marker='o')\nplt.title(\"Total Profit Trend by Month\")\nplt.xlabel(\"Month\")\nplt.ylabel(\"Total Profit\")\nplt.show()\n" }, { "answer_id": 74504864, "author": "Mi.", "author_id": 4219498, "author_profile": "https://Stackoverflow.com/users/4219498", "pm_score": 0, "selected": false, "text": "import matplotlib.pyplot as plt\n\nplt.plot([1,2,3,4], [1,2,3,4]) \nplt.plot(5, 5, 'ro') # Additional point in red\nplt.plot(6, 6, 'go') # Additional point in green\nplt.text(5, 5, \"Text\")\nplt.axis([0, 8, 0, 8]) \nplt.title(\"Total Profit Trend by Month\")\nplt.xlabel(\"Month\")\nplt.ylabel(\"Total Profit\")\nplt.show()\n\n\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20496906/" ]
74,504,776
<p>I'm making a shopping cart list, where the products are added and identified by their codes.</p> <p>The system has to add, remove, show and checkout.</p> <p>Show and checkout commands are working fine.</p> <p>Add is working fine too, but it has a particularity: it´s mandatory to add with &quot;Add 15&quot;, &quot;Add 70&quot; (whatever other number). I can't input str and int separately (did before and was perfect, but not what they want).</p> <p>After I add, the remove command does not identify number inserted previously, because it is being added as a str.</p> <pre><code>cart = [] while True: command = str(input(&quot;Command: &quot;)).split() if &quot;add&quot; in command: cart.append(int(command[1])) elif &quot;remove&quot; in command: if command[1] in cart: cart.remove(int(command[1])) else: print(f'code {command[1]} not found') elif &quot;show&quot; in command: cart.sort() print(cart, end=&quot;\n&quot;) elif &quot;checkout&quot; in command: break cart.sort() print(cart, end=&quot;&quot;) </code></pre>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17038776/" ]
74,504,800
<p>I have a 2d array of values, and I want to add a 1d array to this 2d array element wise such that I would get a 3d array where each element is the original 2d array plus a respective element of the 1d array. For example:</p> <pre><code>A = np.array([ [10, 9, 8, 7, 6], [5, 4, 3, 2, 1] ]) B = np.array([1, 2, 3]) #What A + B should return: np.array([ [[11, 10, 9, 8, 7], [6, 5, 4, 3, 2]], [[12, 11, 10, 9, 8], [7, 6, 5, 4, 3]], [[13, 12, 11, 10, 9], [8, 7, 6, 5, 4]] ]) </code></pre> <p>I was able to do this pretty easily with a normal for loop but is this possible in pure numpy?</p>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12498477/" ]
74,504,821
<p>I am trying to build an isomorphic React app, but for now I will just limit my question to the server side rendering portion. I want to render some React JS components on the server side of my application. I am able to do so with the method <code>ReactDomServer.renderToString</code>. However I am unable to get the CSS (or my SASS/SCSS files) to work with these components.</p> <p>For the client side I can usually just use something like Webpack and the css-loader/style-loader and when I bundle the JS, the components will be correctly styled. However, I do not know how to do this on the server side. This is the error that I get when I run <code>ts-node</code> on my server file</p> <pre><code>body { ^ SyntaxError: Unexpected token '{' at Object.compileFunction (node:vm:360:18) at wrapSafe (node:internal/modules/cjs/loader:1088:15) at Module._compile (node:internal/modules/cjs/loader:1123:27) ... </code></pre> <p>The following are my relevant files.</p> <h3>src/components/App.tsx</h3> <pre><code>import React from &quot;react&quot;; import &quot;./App.scss&quot; class App extends React.Component { override render(): React.ReactNode { return (&lt;div&gt;THIS IS THE APP START&lt;/div&gt;); } } export default App; </code></pre> <h3>src/components/App.scss</h3> <pre><code>$mycolor: red; body { color: $mycolor; } </code></pre> <h3>src/server.tsx</h3> <pre><code>import express from &quot;express&quot;; import ReactDomServer from &quot;react-dom/server&quot;; import App from &quot;./Components/App&quot;; const app = express() const port = 3000 app.get('/', (req, res) =&gt; { const html = ReactDomServer.renderToString(&lt;App /&gt;); res.send(html); }); app.listen(port, () =&gt; { console.log(`Example app listening on port ${port}`) }); </code></pre> <h3>tsconfig.json</h3> <pre><code>{ &quot;include&quot;: [&quot;src/**/*&quot;], &quot;exclude&quot;: [&quot;node_modules&quot;], &quot;compilerOptions&quot;: { &quot;esModuleInterop&quot;: true, &quot;moduleResolution&quot;: &quot;Node16&quot;, &quot;jsx&quot;: &quot;react-jsx&quot; } } </code></pre> <h3>package.json</h3> <pre><code>{ &quot;name&quot;: &quot;really&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;scripts&quot;: { &quot;start&quot;: &quot;ts-node src/server.tsx&quot; }, &quot;dependencies&quot;: { &quot;@types/node-sass&quot;: &quot;^4.11.3&quot;, &quot;@types/react&quot;: &quot;^18.0.25&quot;, &quot;@types/react-dom&quot;: &quot;^18.0.9&quot;, &quot;express&quot;: &quot;^4.18.2&quot;, &quot;node-sass&quot;: &quot;^8.0.0&quot;, &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot;, &quot;sass&quot;: &quot;^1.56.1&quot;, &quot;ts-node&quot;: &quot;^10.9.1&quot; }, &quot;devDependencies&quot;: { &quot;typescript&quot;: &quot;^4.9.3&quot; } } </code></pre> <p>Not sure if it possible to load the CSS before express serves the components. Another possible way might be to use webpack to bundle the server side files and load the CSS but I do not know if this will work and it feels odd to me for server side parts. Is there a way to do this without webpack or not really?</p>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8929431/" ]
74,504,833
<p>New to Teams (and Blazer) dev and are stumped by a seemingly simple question using the Teams Toolkit.</p> <p>We have two Razer pages (ie. under the &quot;Pages&quot; folder in the project - as any asp.net core app has) and want to click from one page to the next from within our Teams Tab App (ideally using an tag) but happy for the navigation code to be executed from the @code block.</p> <p>I've read pretty much everything I can find on this, but like all fairly new tech, the documentation (to me) is confusing at this early stage eg. do we need the teams-js library in addition to the Teams Toolkit to use deep links, or can we just redirect by getting the URL info from the context (which we can't get also).</p> <p>We have tried (by way of an example):</p> <pre><code>@inject NavigationManager nav </code></pre> <p>and then in the @code block:</p> <pre><code>nav.NavigateTo({nav.BaseUri}/TermsOfUse); </code></pre> <p>but that just returns:</p> <p>&quot;Sorry, there's nothing at this address.&quot;</p> <p>Lots of confusion at the moment so just some pointers would help please.</p> <p>Thanks.</p>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1835301/" ]
74,504,869
<p>I have a row of 3 inputs. One of them has label text placed above its input. I do not want this label text to interfere with the alignment of the inputs. Right now I'm using flexbox in my example. My hack/approach is to use <code>position: absolute;</code> on my optional label text to remove it from the flex flow so the inputs stay align. However, this creates a bit of spacing inconsistency when wrapping on smaller viewports. I've tried CSS grid as well but had issues where I was stuck writing a media query for every time I needed to wrap, which seemed worse than this. I would also like the solution to have no fixed widths/heights. As the elements and text can be dynamic. What is the best way to achieve this functionality that allows for a cleaner wrapping?</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>.container { display: flex; flex-wrap: wrap; align-items: center; } .optionalContainer { position: relative; /*hack to container optional text*/ padding: 20px 0; } .optional { position: absolute; top: 0; margin: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form class="container"&gt; &lt;input required type="text"/&gt; &lt;div class="optionalContainer"&gt; &lt;p class="optional"&gt;Optional:&lt;/p&gt; &lt;input type="text"/&gt; &lt;/div&gt; &lt;input required type="text"/&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>Example of what I'm shooting for at different viewports:</p> <p><a href="https://i.stack.imgur.com/JdXbz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JdXbz.png" alt="large" /></a></p> <p><a href="https://i.stack.imgur.com/4q9aa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4q9aa.png" alt="medium" /></a></p> <p><a href="https://i.stack.imgur.com/ZqIg4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZqIg4.png" alt="small" /></a></p>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2368033/" ]
74,504,875
<p>Didn't think that I'll be asking for help on stackoverflow but yeah, I'm stuck... So after the updating of flutter_local_notifications , I've change the method to Darwin and after that I can't build the app because of an error 'The argument type 'Future Function(String)' can't be assigned to the parameter type 'void Function(NotificationResponse)'</p> <pre><code>static Future&lt;void&gt; initialize(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async { var androidInitialize = new AndroidInitializationSettings('notification_icon'); var iOSInitialize = new DarwinInitializationSettings(); var initializationsSettings = new InitializationSettings(android: androidInitialize, iOS: iOSInitialize); flutterLocalNotificationsPlugin.initialize (initializationsSettings, onDidReceiveNotificationResponse: (String payload) async { try{ NotificationBody _payload; if(payload != null &amp;&amp; payload.isNotEmpty) { _payload = NotificationBody.fromJson(jsonDecode(payload)); if(_payload.notificationType == NotificationType.order) { Get.toNamed(RouteHelper.getOrderDetailsRoute(int.parse(_payload.orderId.toString()))); } else if(_payload.notificationType == NotificationType.general) { Get.toNamed(RouteHelper.getNotificationRoute()); } else{ Get.toNamed(RouteHelper.getChatRoute(notificationBody: _payload, conversationID: _payload.conversationId)); } } }catch (e) {} return; }); </code></pre> <p>What I've do wrong? And what should I do to fix that error. Thanks a lot</p> <p>Upgraded the flutter_local_notifications, changed the method to Darwin. Some errors was fixed.</p>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551260/" ]
74,504,887
<p>I am having difficulty creating a a for while loop that allows the user to enter a number and that number determines how many times the loop will execute. I need to create this method and have it execute in Main() feeling lost and not sure why my current code isn't working.</p> <pre><code> public static int InputValue(int min, int max) { //determine number of search times int val; Console.WriteLine(&quot;Enter a number between 1-30:&quot;); val = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i &lt; val; i++) while (val &gt; max || val &lt; min) { Console.WriteLine(&quot;Please enter number within the range...&quot;); break; } return val; } </code></pre>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20527253/" ]
74,504,933
<p>After update an change some thing I have the error &quot;Unable to resolve moudle firebase/auth&quot;</p> <pre class="lang-js prettyprint-override"><code>&quot;@firebase/auth&quot;: &quot;^0.20.11&quot;, &quot;@firebase/firestore&quot;: &quot;^3.4.12&quot;, &quot;firebase&quot;: &quot;9.9.0&quot;, </code></pre> <p>I tried to change version and install the auth independitly but it don't works.</p> <p>The message erros say &quot;firebase/auth could not be found within the project or in these directories...&quot;</p> <p>package.json:</p> <pre class="lang-js prettyprint-override"><code>{ &quot;main&quot;: &quot;node_modules/expo/AppEntry.js&quot;, &quot;scripts&quot;: { &quot;start&quot;: &quot;expo start&quot;, &quot;android&quot;: &quot;expo start --android&quot;, &quot;ios&quot;: &quot;expo start --ios&quot;, &quot;web&quot;: &quot;expo start --web&quot;, &quot;eject&quot;: &quot;expo eject&quot; }, &quot;dependencies&quot;: { &quot;@babel/plugin-transform-runtime&quot;: &quot;^7.14.5&quot;, &quot;@callstack/react-theme-provider&quot;: &quot;^3.0.8&quot;, &quot;@expo/vector-icons&quot;: &quot;^13.0.0&quot;, &quot;@expo/webpack-config&quot;: &quot;^0.17.3&quot;, &quot;@react-native-aria/utils&quot;: &quot;^0.2.7&quot;, &quot;@react-native-community/datetimepicker&quot;: &quot;6.5.2&quot;, &quot;@react-native-community/masked-view&quot;: &quot;^0.1.10&quot;, &quot;@react-native-toolkit/triangle&quot;: &quot;^0.0.1&quot;, &quot;@react-navigation/bottom-tabs&quot;: &quot;^6.2.0&quot;, &quot;@react-navigation/drawer&quot;: &quot;^6.5.0&quot;, &quot;@react-navigation/native&quot;: &quot;6.0.13&quot;, &quot;@react-navigation/native-stack&quot;: &quot;^6.9.0&quot;, &quot;@react-navigation/stack&quot;: &quot;^6.3.4&quot;, &quot;@stream-io/flat-list-mvcp&quot;: &quot;^0.10.1&quot;, &quot;base-64&quot;: &quot;^1.0.0&quot;, &quot;eas-cli&quot;: &quot;^2.7.1&quot;, &quot;expo&quot;: &quot;^47.0.6&quot;, &quot;expo-ads-admob&quot;: &quot;~13.0.0&quot;, &quot;expo-asset&quot;: &quot;~8.6.2&quot;, &quot;expo-auth-session&quot;: &quot;~3.7.2&quot;, &quot;expo-av&quot;: &quot;~13.0.1&quot;, &quot;expo-camera&quot;: &quot;~13.0.0&quot;, &quot;expo-constants&quot;: &quot;~14.0.2&quot;, &quot;expo-dev-client&quot;: &quot;~2.0.0&quot;, &quot;expo-facebook&quot;: &quot;~12.2.0&quot;, &quot;expo-image-picker&quot;: &quot;~14.0.1&quot;, &quot;expo-location&quot;: &quot;~15.0.1&quot;, &quot;expo-media-library&quot;: &quot;~15.0.0&quot;, &quot;expo-permissions&quot;: &quot;~14.0.0&quot;, &quot;expo-random&quot;: &quot;~13.0.0&quot;, &quot;firebase&quot;: &quot;^9.14.0&quot;, &quot;firesql&quot;: &quot;~2.0.2&quot;, &quot;idb&quot;: &quot;^7.0.2&quot;, &quot;lodash&quot;: &quot;^4.17.21&quot;, &quot;material-ui&quot;: &quot;^0.15.0&quot;, &quot;mathjs&quot;: &quot;^11.4.0&quot;, &quot;native-base&quot;: &quot;^3.4.22&quot;, &quot;pkg&quot;: &quot;^5.8.0&quot;, &quot;prop-types&quot;: &quot;^15.7.2&quot;, &quot;proptypes&quot;: &quot;^1.1.0&quot;, &quot;random-uuid-v4&quot;: &quot;^0.0.9&quot;, &quot;react&quot;: &quot;18.1.0&quot;, &quot;react-dom&quot;: &quot;18.1.0&quot;, &quot;react-error-boundary&quot;: &quot;^3.1.3&quot;, &quot;react-native&quot;: &quot;0.70.5&quot;, &quot;react-native-action-button&quot;: &quot;^2.8.5&quot;, &quot;react-native-audio&quot;: &quot;^4.3.0&quot;, &quot;react-native-aws3&quot;: &quot;^0.0.9&quot;, &quot;react-native-bidirectional-infinite-scroll&quot;: &quot;^0.3.3&quot;, &quot;react-native-camera&quot;: &quot;^4.2.1&quot;, &quot;react-native-easy-toast&quot;: &quot;^2.0.0&quot;, &quot;react-native-elements&quot;: &quot;^4.0.0-rc.2&quot;, &quot;react-native-fbsdk-next&quot;: &quot;^11.1.0&quot;, &quot;react-native-gesture-handler&quot;: &quot;~2.8.0&quot;, &quot;react-native-gifted-chat&quot;: &quot;^1.0.4&quot;, &quot;react-native-google-mobile-ads&quot;: &quot;^8.1.0&quot;, &quot;react-native-image-crop-picker&quot;: &quot;^0.38.1&quot;, &quot;react-native-image-picker&quot;: &quot;^4.0.6&quot;, &quot;react-native-keyboard-aware-scroll-view&quot;: &quot;^0.9.4&quot;, &quot;react-native-mapbox-gl&quot;: &quot;^5.2.1-deprecated&quot;, &quot;react-native-maps&quot;: &quot;1.3.2&quot;, &quot;react-native-menu-list&quot;: &quot;^1.0.1&quot;, &quot;react-native-navbar&quot;: &quot;^2.1.0&quot;, &quot;react-native-open-maps&quot;: &quot;~0.4.0&quot;, &quot;react-native-paper&quot;: &quot;^4.12.5&quot;, &quot;react-native-reanimated&quot;: &quot;~2.12.0&quot;, &quot;react-native-router-flux&quot;: &quot;^4.3.1&quot;, &quot;react-native-safe-area-context&quot;: &quot;^4.4.1&quot;, &quot;react-native-screens&quot;: &quot;^3.17.0&quot;, &quot;react-native-snap-carousel&quot;: &quot;^1.3.1&quot;, &quot;react-native-sound&quot;: &quot;^0.11.0&quot;, &quot;react-native-swiper&quot;: &quot;^1.6.0&quot;, &quot;react-native-switch-selector&quot;: &quot;^2.1.4&quot;, &quot;react-native-video&quot;: &quot;^5.2.1&quot;, &quot;react-native-web&quot;: &quot;~0.18.9&quot;, &quot;react-navigation&quot;: &quot;^4.4.4&quot;, &quot;react-player&quot;: &quot;^2.11.0&quot;, &quot;react-scripts&quot;: &quot;^5.0.1&quot;, &quot;smartsocket&quot;: &quot;^1.1.22&quot;, &quot;styled-components&quot;: &quot;^5.3.0&quot;, &quot;use-debounce&quot;: &quot;^8.0.4&quot; }, &quot;devDependencies&quot;: { &quot;@babel/core&quot;: &quot;^7.12.9&quot;, &quot;@types/node&quot;: &quot;^18.11.9&quot;, &quot;babel-preset-expo&quot;: &quot;~9.2.2&quot; }, &quot;private&quot;: true } </code></pre> <p><img src="https://i.stack.imgur.com/onC1Q.jpg" alt="unable to resolve firebas/auth" /></p>
[ { "answer_id": 74504802, "author": "Veenz", "author_id": 7518737, "author_profile": "https://Stackoverflow.com/users/7518737", "pm_score": 2, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type\n cart.remove(int(command[1]))\n else:\n print(f'code {command[1]} not found')\n elif \"show\" in command:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" in command:\n break\ncart.sort()\nprint(cart, end=\"\")\n cart = []\nwhile True:\n raw = str(input(\"Command: \")).split()\n command = raw[0]\n amount = None\n if (len(raw) > 1):\n amount = int(raw[1])\n if command == \"add\":\n cart.append(amount)\n elif command == \"remove\":\n if amount in cart:\n cart.remove(amount)\n else:\n print(f'code {amount} not found')\n elif command == \"show\":\n cart.sort()\n print(cart, end=\"\\n\")\n elif command == \"checkout\":\n break\ncart.sort()\nprint(cart, end=\"\")\n" }, { "answer_id": 74504837, "author": "rada-dev", "author_id": 14840385, "author_profile": "https://Stackoverflow.com/users/14840385", "pm_score": 0, "selected": false, "text": "cart = []\nwhile True:\n command = str(input(\"Command: \")).lower().split()\n print(command)\n # I assume that add and remove will be 2-word commands\n if len(command) == 2:\n try:\n number = int(command[1])\n if \"add\" == command[0]:\n cart.append(number)\n elif \"remove\" == command[0]:\n if number in cart:\n cart.remove(number)\n else:\n print(f\"code {number} not found\")\n except ValueError:\n print(f\"code {command[1]} is not a number\")\n # I assume show and checkout will be 1-word commands\n elif len(command) == 1:\n if \"show\" == command[0]:\n cart.sort()\n print(cart, end=\"\\n\")\n elif \"checkout\" == command[0]:\n break\n else:\n print(\"invalid command\")\n else:\n print(\"invalid command\")\n\ncart.sort()\nprint(cart, end=\"\")\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16421641/" ]
74,504,971
<p>My question is basically the same as [1], but the challenge is to compare a nested <code>vector&lt;vector&lt;double&gt;&gt;</code>.</p> <p>As a background to the problem I'm facing: I have an n-way index based on std::set where items are sorted by time primarily, and secondarily by geometry. That is, equal polygons should have the same index, but the actual order of them does actually not matter. What matters though is that the less-comparator must in this context be stable, in the sense that an item must be considered equal when it's neither less than nor greater than.</p> <p>This <code>vector&lt;vector&lt;double&gt;&gt;</code> therefore represents polygons with optional holes (first vector is the outer ring, any subsequent vectors are holes).</p> <p>[1] <a href="https://stackoverflow.com/questions/53637613/how-to-define-a-comparison-operator-less-than-on-array-of-doubles">how to define a comparison operator (less than) on array of doubles?</a></p> <p>Edit: This question is NOT about asking how to implement a less-than operator, but as the title suggests, about how to compare given vectors of vectors of double with another by using a less-than comparison… This is a whole lot more challenging…</p> <p>The problem could be solved in different ways, but I specifically look for a solution which allows to use the object (geometry) as part of a set with multiple tied index properties.</p>
[ { "answer_id": 74505330, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": -1, "selected": false, "text": "operator< vector<vector<double>> const& bool operator< (const vector<vector<double>& l, const vector<vector<double>& r)\n{\n // your comparison logic here...\n}\n" }, { "answer_id": 74530320, "author": "Caleth", "author_id": 2610810, "author_profile": "https://Stackoverflow.com/users/2610810", "pm_score": 1, "selected": false, "text": "struct Point\n{\n double x;\n double y;\n double z; // ???\n};\n\nstruct BasicPolygon\n{\n std::vector<Point> shape;\n};\n\nstruct Polygon\n{\n BasicPolygon shell;\n std::vector<BasicPolygon> holes;\n};\n =default operator<=> void BasicPolygon::canonicalize()\n{\n auto it = std::min_element(shape.begin(), shape.end());\n std::rotate(shape.begin(), it, shape.end());\n}\n\nvoid Polygon::canonicalize()\n{\n shell.canonicalize();\n std::for_each(holes.begin(), holes.end(), std::mem_fn(&BasicPolygon::canonicalize));\n}\n std::lexicographic_compare bool operator<(const BasicPolygon & lhs, const BasicPolygon & rhs)\n{\n if (lhs.size() < rhs.size()) return true;\n if (rhs.size() < lhs.size()) return false;\n\n auto l_first = std::min_element(lhs.shape.begin(), lhs.shape.end());\n auto r_first = std::min_element(rhs.shape.begin(), rhs.shape.end());\n const auto l_last = l_first;\n const auto r_last = r_first;\n\n auto l_rem = std::distance(l_first, lhs.shape.end());\n auto r_rem = std::distance(r_first, rhs.shape.end());\n\n if (l_rem < r_rem)\n {\n if (std::lexicographic_compare(l_first, lhs.shape.end(), r_first, r_first + l_rem)) return true;\n if (std::lexicographic_compare(r_first, r_first + l_rem, l_first, lhs.shape.end()) return false;\n\n r_first += l_rem;\n r_rem -= l_rem;\n l_first = lhs.shape.begin();\n\n if (std::lexicographic_compare(l_first, l_first + r_rem, r_first, rhs.shape.end()) return true;\n if (std::lexicographic_compare(r_first, rhs.shape.end(), l_first, l_first + r_rem)) return false;\n\n l_first += r_rem;\n r_first = rhs.shape.begin();\n\n if (std::lexicographic_compare(l_first, l_last, r_first, r_last)) return true;\n if (std::lexicographic_compare(r_first, r_last, l_first, l_last) return false;\n } else {\n if (std::lexicographic_compare(l_first, l_first + r_rem, r_first, rhs.shape.end()) return true;\n if (std::lexicographic_compare(r_first, rhs.shape.end(), l_first, l_first + r_rem)) return false;\n\n l_first += r_rem;\n l_rem -= r_rem;\n r_first = rhs.shape.begin();\n\n if (std::lexicographic_compare(l_first, lhs.shape.end(), r_first, r_first + l_rem)) return true;\n if (std::lexicographic_compare(r_first, r_first + l_rem, l_first, lhs.shape.end()) return false;\n\n r_first += l_rem;\n l_first = lhs.shape.begin();\n\n if (std::lexicographic_compare(l_first, l_last, r_first, r_last)) return true;\n if (std::lexicographic_compare(r_first, r_last, l_first, l_last) return false;\n }\n return false;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1708349/" ]
74,504,977
<p>How to remove an object (element) based on the property from nested obj. For example, I need to remove all objects with type: 'green' from obj tree if obj has children it will be also removed.</p> <pre><code>const obj = { id: '01', children: [ { id: '02', type: 'green', children: [ { id: '03', type: 'black', children: [], }, { id: '04', type: 'green', children: [ { id: '05', type: 'white', children: [], } ], } ], }, { id: '06', type: 'black', children: [ { id: '07', type: 'green', children: [], }, { id: '08', type: 'white', children: [ { id: '09', type: 'green', children: [], } ], } ], }, ] } </code></pre> <p>// expected result (if remove type: &quot;green&quot;)</p> <pre><code>const expectedObj = { id: '01', type: 'orange', children: [ { id: '06', type: 'black', children: [ { id: '08', type: 'white', children: [], } ], }, ] } </code></pre> <p>What I am trying to do</p> <pre><code>let match = false const removeByType = (data, type) =&gt; { match = data.some(d =&gt; d.type == type) if (match) { data = data.filter(d =&gt; d.type !== type) } else { data.forEach(d =&gt; { d.children = removeByType(d.children, type) }) } return data } let data = obj.children console.dir(removeByType(data, 'black'), { depth: null }) </code></pre> <p>but { id: '03', type: 'black', children: [] } is still in the object tree</p>
[ { "answer_id": 74505037, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 3, "selected": true, "text": "map const removeByType = (data, type) => {\n data = data.filter(d => d.type !== type)\n data = data.map(d => {\n d.children = removeByType(d.children, type);\n return d;\n })\n return data\n}\n const removeByType = (data, type) => data.filter(d => d.type !== type)\n .map(d => ({...d, children: removeByType(d.children, type)}));\n const obj = {\n id: '01',\n children: [{\n id: '02',\n type: 'green',\n children: [{\n id: '03',\n type: 'black',\n children: [],\n },\n {\n id: '04',\n type: 'green',\n children: [{\n id: '05',\n type: 'white',\n children: [],\n }],\n }\n ],\n },\n {\n id: '06',\n type: 'black',\n children: [{\n id: '07',\n type: 'green',\n children: [],\n },\n {\n id: '08',\n type: 'white',\n children: [{\n id: '09',\n type: 'green',\n children: [],\n }],\n }\n ],\n },\n ]\n}\n\n\nconst removeByType = (data, type) => {\n data = data.filter(d => d.type !== type)\n data = data.map(d => {\n d.children = removeByType(d.children, type);\n return d;\n })\n return data\n}\n\nconsole.dir(removeByType(obj.children, 'black'), {\n depth: null\n})" }, { "answer_id": 74505169, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 2, "selected": false, "text": "const removeByType = (data, type) =>\n {\n for (let i=data.children.length;--i>=0;)\n {\n if ( data.children[i].type===type) data.children.splice(i,1)\n else removeByType (data.children[i], type)\n }\n return data // just for chaining ... ?\n }\n const my_obj = \n { id: '01', type: 'orange', children: // + stay\n [ { id: '02', type: 'green', children: // - green\n [ { id: '03', type: 'black', children: [] } // -\n , { id: '04', type: 'green', children: // -\n [ { id: '05', type: 'white', children: [] } // -\n ] \n } ] } \n , { id: '06', type: 'black', children: // + stay\n [ { id: '07', type: 'green', children: [] } // - green\n , { id: '08', type: 'white', children: // + stay\n [ { id: '09', type: 'green', children: [] } // - green\n ] \n } ] } ] } \n\nconst removeByType = (data, type) =>\n {\n for (let i=data.children.length;--i>=0;)\n {\n if ( data.children[i].type===type) data.children.splice(i,1)\n else removeByType (data.children[i], type)\n }\n return data\n }\n\nconsole.log( removeByType(my_obj, 'green') )\n // my_obj is now updated...\nconsole.log( my_obj ) .as-console-wrapper {max-height: 100% !important;top: 0;}\n.as-console-row::after {display: none !important;}" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11020843/" ]
74,504,999
<p>New to java here! I'm writing a Pizza program and am stuck on how to stop printing already selected items to the menu after each loop iteration. Can someone take a look at my code and help me out? We haven't covered user defined methods yet, which seems like it could simplify this whole project. Any tips on how to improve program functionality and readability would be appreciated, but my main concern is modifying the menu to only show items that have not been chosen, that way I can just update the quantity using the items index location and not have to define 100 variables.</p> <pre><code>public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println(&quot;---------------------&quot;); System.out.println(&quot;Create Your Own Pizza&quot;); System.out.println(&quot;---------------------&quot;); //\\//\\//\\//\\//\\//\\PRINT TOPPINGS//\\//\\//\\//\\//\\//\\ char userChar = 'y'; String[] toppings = {&quot;diced onion&quot;, &quot;green pepper&quot;, &quot;pepperoni&quot;, &quot;sliced mushrooms&quot;, &quot;jalapenos&quot;, &quot;pineapple&quot;, &quot;dry red pepper&quot;, &quot;basil&quot;}; String[] choices = { &quot;A. &quot;, &quot;B. &quot;, &quot;C. &quot;, &quot;D. &quot;, &quot;E. &quot;, &quot;F. &quot;, &quot;G. &quot;, &quot;H. &quot;}; //Enter topping menus loop while (userChar == 'y') { System.out.println(&quot;\nChoose your favorite toppings&quot;); for (int i=0; i&lt;choices.length; ++i) { System.out.println(choices[i] + toppings[i]); } //\\//\\//\\//\\//\\//\\CHOOSE TOPPINGS//\\//\\//\\//\\//\\//\\ System.out.println(&quot;\nEnter a choice: &quot;); String userToppings = sc.nextLine(); //Need help removing each topping array element and choice array element after user adds to pizze if (userToppings.equalsIgnoreCase(&quot;A&quot;)) { System.out.println(&quot;Please choose one amount: &quot;); System.out.println(&quot;a. 1/8 cup b. 1/4 cup&quot;); userToppings = sc.nextLine(); if (userToppings.equalsIgnoreCase(&quot;A&quot;)) { choices[0]=&quot;1/8 cup&quot;; } else { choices[0]=&quot;1/4 cup&quot;; } System.out.println(&quot;Would you like to add more toppings? Type Y for yes or any other key to submit your recipe.&quot;); userChar = sc.next().charAt(0); } else if (userToppings.equalsIgnoreCase(&quot;B&quot;)) { System.out.println(&quot;Please choose one amount: &quot;); System.out.println(&quot;a. 1/8 cup b. 1/4 cup&quot;); userToppings = sc.nextLine(); if (userToppings.equalsIgnoreCase(&quot;A&quot;)) { choices[1]=&quot;1/8 cup&quot;; } else { choices[1]=&quot;1/4 cup&quot;; } System.out.println(&quot;Would you like to add more toppings? Type Y for yes or any other key to submit your recipe.&quot;); userChar = sc.next().charAt(0); } else { System.out.println(&quot;You did not enter a valid topping choice&quot;); } } //\\//\\//\\//\\//\\//\\PRINT RECIPE//\\//\\//\\//\\//\\//\\ System.out.println(&quot;Your pizza recipe is: &quot;); System.out.println(crustType + &quot;\t1 &quot;); System.out.println(sauceType + &quot;\t&quot; + sauceAmount); System.out.println(cheese + &quot;\t\t&quot; + cheeseAmount); //still developing this part just needed it to print the recipe for (int i=0; i&lt;toppings.length; i++) { System.out.println(toppings[i] + &quot;\t\t&quot; + choices[i]); } } } </code></pre>
[ { "answer_id": 74505100, "author": "exoad", "author_id": 14501343, "author_profile": "https://Stackoverflow.com/users/14501343", "pm_score": 2, "selected": false, "text": "type[] ArrayList import java.util.ArrayList;\n\nArrayList<String> myArray = new ArrayList<>();\nmyArray.add(\"hello\"); // add an element to the end\nmyArray.get(0); // get the element at index 0; returns String\nmyArray.remove(0); // remove an element at an index\nmyArray.set(0, \"foo\"); // set the element at index 0 to foo\n public static String[] removeElement(String[] array, String element)\n{\n String[] temp = new String[array.length - 1];\n for(int i = 0, j = 0; i < array.length && j < temp.length; i++) {\n if(!array[i].equals(element)) {\n temp[j] = array[i];\n j++;\n }\n }\n return temp;\n}\n String[] temp = removeElement(new String[] { \"hello\", \"world\", \":)\" }, \"world\"); public static String[] removeElement(String[] array, int index) \n{\n String[] temp = new String[array.length - 1];\n for(int i = 0, j = 0; i < array.length && j < temp.length; i++) {\n if(i != index) \n temp[j++] = array[i];\n return temp;\n}\n String[] arr = removeElement(new String[] { \"hello\", \"world\", \":)\" }, 0); myArray[0] = null; for(int i = 0; i < myArray.length; i++) {\n if(myArray[i] != null) \n System.out.println(myArray[i]);\n}\n int size = 5;\nint[] elementsToHide = new int[size];\nint[] elements = new int[size];\n// ... add 5 elements to array:elements\n\n// print \nfor(int i = 0; i < size; i++) {\n boolean isRemoveable = false;\n for(int j = 0; j < size; j++) {\n if(i == j) {\n isRemoveable = true;\n }\n }\n if(!isRemoveable) {\n System.out.println(elements[i]);\n }\n}\n" }, { "answer_id": 74505213, "author": "Tyler Franklin", "author_id": 10475199, "author_profile": "https://Stackoverflow.com/users/10475199", "pm_score": -1, "selected": true, "text": "public static void main(String args[]) {\n displayMenu();\n}\nstatic void displayMenu() {\n String[] toppings = {\"diced onion\", \"green pepper\", \"pepperoni\", \"sliced mushrooms\", \"jalapenos\", \"pineapple\", \"dry red pepper\", \"basil\"};\n String[] choices = { \"A. \", \"B. \", \"C. \", \"D. \", \"E. \", \"F. \", \"G. \", \"H. \"};\n boolean[] toppingSelected = { false, false, false, false, false, false, false, true};\n //Enter topping menus loop\n System.out.println(\"\\nChoose your favorite toppings\");\n\n for (int i=0; i<choices.length; ++i) {\n if(toppingSelected[i] == false) {\n System.out.println(choices[i] + toppings[i]); \n }\n }\n //System.out.println(\"test\");\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74504999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400371/" ]
74,505,013
<p>I have an Ontology which have some SWRL rules (created using Protege). I am using OWL API to manipulate the ontology and using JENA API for SPARQL Queries. I need to reason this ontology using Pellet (As pellet supports SWRL and i have sed the reasoner inside protege). I saw some examples at <a href="https://github.com/ignazio1977/pellet/blob/master/examples/src/main/java/org/mindswap/pellet/examples/OWLAPIi" rel="nofollow noreferrer">https://github.com/ignazio1977/pellet/blob/master/examples/src/main/java/org/mindswap/pellet/examples/OWLAPIi</a> am using the following dependency</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.github.ansell.pellet&lt;/groupId&gt; &lt;artifactId&gt;pellet-owlapiv3&lt;/artifactId&gt; &lt;version&gt;2.3.6-ansell&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>The code is as follows</p> <pre><code>OWLOntologyManager man = OWLManager.createOWLOntologyManager(); File file = new File(&quot;C:\\Protege-5.5.0\\ContextModellingJAVA.owl&quot;); // Loading an Ontology from file OWLOntology o = man.loadOntologyFromOntologyDocument(file); PelletReasoner reasoner = PelletReasonerFactory.getInstance().createReasoner(o); System.out.println(&quot;done.&quot;); </code></pre> <p>When I run this I am getting the following error</p> <pre><code>Exception in thread &quot;main&quot; java.lang.NoSuchMethodError: 'org.semanticweb.owlapi.model.OWLPropertyExpression org.semanticweb.owlapi.model.OWLObjectPropertyDomainAxiom.getProperty()' at com.clarkparsia.pellet.owlapiv3.PelletVisitor.visit(PelletVisitor.java:945) at org.semanticweb.owlapi.model.OWLObjectPropertyDomainAxiom.accept(OWLObjectPropertyDomainAxiom.java:36) at com.clarkparsia.pellet.owlapiv3.PelletVisitor.visit(PelletVisitor.java:699) at org.semanticweb.owlapi.model.OWLOntology.accept(OWLOntology.java:519) at com.clarkparsia.pellet.owlapiv3.PelletReasoner.refresh(PelletReasoner.java:967) at com.clarkparsia.pellet.owlapiv3.PelletReasoner.&lt;init&gt;(PelletReasoner.java:345) at com.clarkparsia.pellet.owlapiv3.PelletReasoner.&lt;init&gt;(PelletReasoner.java:304) at com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory.createReasoner(PelletReasonerFactory.java:71) at ContextModelling.main(ContextModelling.java:166) Can anyone please help me solve the error. Thanks in advace </code></pre>
[ { "answer_id": 74507025, "author": "Ignazio", "author_id": 1197045, "author_profile": "https://Stackoverflow.com/users/1197045", "pm_score": 1, "selected": false, "text": "<dependency>\n<groupId>net.sourceforge.owlapi</groupId>\n<artifactId>pellet-owlapi-ignazio1977</artifactId>\n<version>2.4.0-ignazio1977</version>\n</dependency>\n" }, { "answer_id": 74553240, "author": "Anzal Harris", "author_id": 20194857, "author_profile": "https://Stackoverflow.com/users/20194857", "pm_score": 0, "selected": false, "text": "<dependency>\n <groupId>com.github.galigator.openllet</groupId>\n <artifactId>openllet-owlapi</artifactId>\n <version>2.6.5</version>\n</dependency>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20194857/" ]
74,505,019
<p>I have a df like this :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">PRODUCTNUMBER</th> <th style="text-align: center;">Jerarquía principal</th> <th style="text-align: right;">Jerarquía secundaria marcas</th> <th style="text-align: right;">COT</th> <th style="text-align: right;">Ecommerce</th> <th style="text-align: right;">dabra-catalog</th> <th style="text-align: right;">Dexter-ecommerce</th> <th style="text-align: right;">Stockcenter-ecommerce</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">AD802309</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">ADIDAS</td> <td style="text-align: right;">950699</td> <td style="text-align: right;">NaN</td> <td style="text-align: right;">NaN</td> <td style="text-align: right;">NaN</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: left;">AD481076</td> <td style="text-align: center;">NaN</td> <td style="text-align: right;">Adidas</td> <td style="text-align: right;">950699</td> <td style="text-align: right;">NaN</td> <td style="text-align: right;">NaN</td> <td style="text-align: right;">NaN</td> <td style="text-align: right;">NaN</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">Adidas</td> <td style="text-align: right;">950699</td> <td style="text-align: right;">Medias-Hombre</td> <td style="text-align: right;">Medias-Hombre</td> <td style="text-align: right;">Medias-Hombre</td> <td style="text-align: right;">Medias-Hombre</td> </tr> </tbody> </table> </div> <p>and I need to get this output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">PRODUCTNUMBER</th> <th style="text-align: center;">PRODUCTCATEGORYNAME</th> <th style="text-align: right;">PRODUCTCATEGORYHIERARCHYNAME</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">AD802309</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">Jerarquía principal</td> </tr> <tr> <td style="text-align: left;">AD802309</td> <td style="text-align: center;">ADIDAS</td> <td style="text-align: right;">Jerarquía secundaria marcas</td> </tr> <tr> <td style="text-align: left;">AD802309</td> <td style="text-align: center;">950699</td> <td style="text-align: right;">COT</td> </tr> <tr> <td style="text-align: left;">AD481076</td> <td style="text-align: center;">Adidas</td> <td style="text-align: right;">Jerarquía secundaria marcas</td> </tr> <tr> <td style="text-align: left;">AD481076</td> <td style="text-align: center;">950699</td> <td style="text-align: right;">COT</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">Jerarquía principal</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Adidas</td> <td style="text-align: right;">Jerarquía secundaria marcas</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">950699</td> <td style="text-align: right;">COT</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">Ecommerce</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">dabra-catalog</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">Dexter-ecommerce</td> </tr> <tr> <td style="text-align: left;">AD481137</td> <td style="text-align: center;">Medias-Hombre</td> <td style="text-align: right;">Stockcenter-ecommerce</td> </tr> </tbody> </table> </div> <p>is it possible? &quot;NaN&quot; values must not be transposed</p>
[ { "answer_id": 74505070, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "df = (\n df.set_index(\"PRODUCTNUMBER\")\n .stack()\n .reset_index()\n .rename(\n columns={\n 0: \"PRODUCTCATEGORYNAME\",\n \"level_1\": \"PRODUCTCATEGORYHIERARCHYNAME\",\n }\n )\n)\n\ndf = df[[\"PRODUCTNUMBER\", \"PRODUCTCATEGORYNAME\", \"PRODUCTCATEGORYHIERARCHYNAME\"]]\nprint(df)\n PRODUCTNUMBER PRODUCTCATEGORYNAME PRODUCTCATEGORYHIERARCHYNAME\n0 AD802309 Medias-Hombre Jerarquía principal\n1 AD802309 ADIDAS Jerarquía secundaria marcas\n2 AD802309 950699 COT\n3 AD481076 Adidas Jerarquía secundaria marcas\n4 AD481076 950699 COT\n5 AD481137 Medias-Hombre Jerarquía principal\n6 AD481137 Adidas Jerarquía secundaria marcas\n7 AD481137 950699 COT\n8 AD481137 Medias-Hombre Ecommerce\n9 AD481137 Medias-Hombre dabra-catalog\n10 AD481137 Medias-Hombre Dexter-ecommerce\n11 AD481137 Medias-Hombre Stockcenter-ecommerce\n" }, { "answer_id": 74505071, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "data = {'A': {'a': 'val1', 'b': 'val3'},\n 'B': {'a': None, 'b': 'val4'},\n 'C': {'a': 'val2', 'b': None}}\ndf = pd.DataFrame(data)\n df A B C\na val1 None val2\nb val3 val4 None\n stack df.stack().reset_index().set_axis(['col1', 'col2', 'col3'], axis=1)\n col1 col2 col3\n0 a A val1\n1 a C val2\n2 b A val3\n3 b B val4\n" }, { "answer_id": 74505359, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 3, "selected": true, "text": "melt out = df.melt('PRODUCTNUMBER',\n value_name='PRODUCTCATEGORYHIERARCHYNAME',\n var_name='PRODUCTCATEGORYNAME').dropna()\nOut[201]: \n PRODUCTNUMBER PRODUCTCATEGORYNAME PRODUCTCATEGORYHIERARCHYNAME\n0 AD802309 Jerarquía principal Medias-Hombre\n2 AD481137 Jerarquía principal Medias-Hombre\n3 AD802309 Jerarquía secundaria marcas ADIDAS\n4 AD481076 Jerarquía secundaria marcas Adidas\n5 AD481137 Jerarquía secundaria marcas Adidas\n6 AD802309 COT 950699\n7 AD481076 COT 950699\n8 AD481137 COT 950699\n11 AD481137 Ecommerce Medias-Hombre\n14 AD481137 dabra-catalog Medias-Hombre\n17 AD481137 Dexter-ecommerce Medias-Hombre\n20 AD481137 Stockcenter-ecommerce Medias-Hombre\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13737893/" ]
74,505,054
<p>i'm completely new to Kubernetes so forgive me if im asking some dumb questions :-0</p> <p>when you deploy apps to k8s, you usually write up some yaml files for the app right? how do you know which k8s objects you should make config file for?</p> <p>for example, im following a tutorial that deploys mysql on k8s and it says i would need deployment.yaml, secret.yaml, pv.yaml, pvc.yaml and service.yaml but how do you know in the first place you need these config files in order to successfully deploy mysql app?</p> <p>are there any guide or standard to follow on this matter? all the tutorials or documentations i been watching and reading dont tell me which objects to define for a particular app and why.</p> <p>i feel like i dont understand k8s at all or seriously missing some import points here</p> <p>thanks for the answer in advance!!</p> <p>i've been googling to find answers on the question but can't find any concrete one yet :(</p>
[ { "answer_id": 74507396, "author": "rok", "author_id": 1264304, "author_profile": "https://Stackoverflow.com/users/1264304", "pm_score": 0, "selected": false, "text": "yaml files" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551376/" ]
74,505,069
<p>For this assignment, I have to write a program that removes the odd numbers from an array and replaces them with even numbers. The array must have 10 elements and be initialized with the following numbers: 42, 9, 23, 101, 99, 22, 13, 5, 77, 28.</p> <p>These are the requirements:</p> <ol> <li>Must use the values provided in my array.</li> <li>Print the original array to the console.</li> <li>Identify any odd values in the array and replace them with even values.</li> <li>Display the updated array to the console.</li> </ol> <p>This is the output I am going for:</p> <pre><code>The original array is: 42 9 23 101 99 22 13 5 77 28 Your even number array is: 42 18 46 202 198 22 26 10 154 28 </code></pre> <ul> <li></li> </ul> <p>I'm super new to programming, so this concept is difficult for me to grasp, so if someone could give guidance that would mean the world.</p> <p>This is what I have so far</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int const size = 10; int values[size] = { 42, 9, 23, 101, 99, 22, 13, 5, 77, 28 }; for (int i = 0; i &lt; size; i++) { if (values[i] % 2 != 0) { cout &lt;&lt; (values[i] * 2) &lt;&lt; endl; } } return 0; } </code></pre> <p><a href="https://i.stack.imgur.com/5kcYS.png" rel="nofollow noreferrer">output</a></p> <p>It's multiplying the odd numbers, which is want I want, but not each one in their own line. Also the new even numbers need to be along with the original even numbers.</p>
[ { "answer_id": 74507396, "author": "rok", "author_id": 1264304, "author_profile": "https://Stackoverflow.com/users/1264304", "pm_score": 0, "selected": false, "text": "yaml files" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551408/" ]
74,505,077
<p>I've started to learn python about 4 days ago. To practice, I've decided to make a program that calculates combinations.</p> <p>Here is the code:</p> <pre><code>print('Insert values for your combination (Cp,n)') def combin(exemplo): print('insert p value') p = int(input()) print('insert n value') n = int(input()) exemplo = [p,n] #&quot;fator&quot; is a function defined earlier in the program. It basically calculates the factorial of a number res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1])) print(res) teste = [] combin(teste) </code></pre> <p>After running this, the following error has ocurred:</p> <pre><code>print(res) ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre> <p>However, I can't see what I'm doing wrong here. I figured that I probably would have problems with the math and the functions, but I can't figure out what's up with the syntax in this case.</p>
[ { "answer_id": 74505091, "author": "White Wizard", "author_id": 9366059, "author_profile": "https://Stackoverflow.com/users/9366059", "pm_score": 0, "selected": false, "text": "res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n" }, { "answer_id": 74505094, "author": "Kieran", "author_id": 20534032, "author_profile": "https://Stackoverflow.com/users/20534032", "pm_score": 0, "selected": false, "text": "res res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1]))*fator(exemplo[1]))\n" }, { "answer_id": 74505507, "author": "Prasad Shembekar", "author_id": 17991201, "author_profile": "https://Stackoverflow.com/users/17991201", "pm_score": 1, "selected": false, "text": "res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551441/" ]
74,505,088
<pre><code>Name Day 1 Day2 Day 3 John 3 2 John 2 1 4 </code></pre> <p>Using a double Xlookup, when I'm searching for John and Day 2, I cannot get the value 1 and I'm trying Index/Xmatch/xmatch to return me 1 but no luck. Any idea to go about it?</p> <p>@@@Updated example picture here@@@ <a href="https://i.stack.imgur.com/0zUOH.png" rel="nofollow noreferrer">enter image description here</a></p> <p>This is my current formula</p> <pre><code>=XLOOKUP(&quot;John&quot;,$A$2:$A$3,XLOOKUP(&quot;Day 2&quot;,$B$1:$D$1,$B$2:$D$3),,2) </code></pre>
[ { "answer_id": 74505091, "author": "White Wizard", "author_id": 9366059, "author_profile": "https://Stackoverflow.com/users/9366059", "pm_score": 0, "selected": false, "text": "res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n" }, { "answer_id": 74505094, "author": "Kieran", "author_id": 20534032, "author_profile": "https://Stackoverflow.com/users/20534032", "pm_score": 0, "selected": false, "text": "res res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1]))*fator(exemplo[1]))\n" }, { "answer_id": 74505507, "author": "Prasad Shembekar", "author_id": 17991201, "author_profile": "https://Stackoverflow.com/users/17991201", "pm_score": 1, "selected": false, "text": "res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551467/" ]
74,505,113
<p>I'm trying to get a list of Vendors' names where the name starts with a character between A and E. Is there a way to do that perhaps using LINQ?</p> <p>My current solution is just a very long if statement</p> <pre><code>var vendors = _context.Vendors.ToList(); var sortedVendors = new List&lt;Vendor&gt;(); foreach (Vendor vendor in vendors) { if (vendor.Name.StartsWith('A') || vendor.Name.StartsWith('B') || vendor.Name.StartsWith('C') || vendor.Name.StartsWith('D') || vendor.Name.StartsWith('E')) { sortedVendors.Add(vendor); } } </code></pre> <p>This works, but is hideous and I would love to know if there was a more elegant solution</p>
[ { "answer_id": 74505091, "author": "White Wizard", "author_id": 9366059, "author_profile": "https://Stackoverflow.com/users/9366059", "pm_score": 0, "selected": false, "text": "res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n" }, { "answer_id": 74505094, "author": "Kieran", "author_id": 20534032, "author_profile": "https://Stackoverflow.com/users/20534032", "pm_score": 0, "selected": false, "text": "res res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1]))*fator(exemplo[1]))\n" }, { "answer_id": 74505507, "author": "Prasad Shembekar", "author_id": 17991201, "author_profile": "https://Stackoverflow.com/users/17991201", "pm_score": 1, "selected": false, "text": "res = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10355675/" ]
74,505,123
<p>I've exported into a text file all of my text messages and they are formatted as such.</p> <pre><code>, NAME +18001112222, RECV, Text message contents. , NAME +18001112222, RECV, Text message contents that are run over to the line below it. , NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines! , NAME +18001112222, SENT, Text Message contents </code></pre> <p>I know how to remove the empty lines. How would one use awk, sed or grep to move all of these lines, that don't begin with a <code>,</code> to the end of the line above it?</p> <p>Or how would you reformat this to ensure each text message has all of its contents on a single line.</p> <p>I haven't tried anything yet, because Im unsure where to even begin, thats why I'm here asking for more practiced hands to hopefully provide some practical examples on how to going about solving this issue. Thanks in Advance!</p>
[ { "answer_id": 74505273, "author": "jhnc", "author_id": 10971581, "author_profile": "https://Stackoverflow.com/users/10971581", "pm_score": 2, "selected": false, "text": "awk -v ORS= '\n NR>1 && /^, / { print \"\\n\" }\n 1;\n END { print \"\\n\" }\n' inputfile\n , , " }, { "answer_id": 74506998, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "AWK file.txt , NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to \nthe line below it.\n, NAME +18001112222, SENT, Text message contents that have\n\nmultiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n awk 'BEGIN{RS=\"\\n,\"}{ORS=RT;gsub(/\\n/,\" \");print}' file.txt\n , NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to the line below it.\n, NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n AWK RS \\n , ORS RT \\n print" }, { "answer_id": 74507485, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 1, "selected": false, "text": "sed $ sed -E ':a;/^,/{N;s/ *\\n($|[a-z])/ \\1/;ba}' input_file\n, NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to the line below it.\n, NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n" }, { "answer_id": 74508118, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed ':a;N;/\\n$\\|\\n[^,]/s/\\n//;ta;P;D' file\n , D" }, { "answer_id": 74508916, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 0, "selected": false, "text": "perl -0777 -pe 's/\\n+(?!,)/ /g;' yourfile\n \\n (?!$|,)" }, { "answer_id": 74510131, "author": "Walter A", "author_id": 3220113, "author_profile": "https://Stackoverflow.com/users/3220113", "pm_score": 1, "selected": false, "text": "sed -z sed -rz ':a;s/\\n([^,])/\\1/g;ta' inputfile\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15079849/" ]
74,505,124
<p>When <code>setState</code> is called in a widget's state, the corresponding element in the element tree gets marked as dirty, and the widget gets rebuilt. However, how does it handle descendents? For example, the <code>Text</code> widget below gets rebuilt when its ancestor <code>SampleWidgetState</code> gets rebuilt.</p> <p>Why?</p> <pre><code>class SampleWidget extends StatefulWidget { @override SampleWidgetState createState() =&gt; SampleWidgetState(); } class SampleWidgetState extends State&lt;SampleWidget&gt; { String text = &quot;text1&quot;; @override Widget build(BuildContext context) { return Column( children: [ Text(text), ElevatedButton( child: Text('call SetState'), onPressed: () { setState(() { text = &quot;text2&quot;; }); }, ), ], ); } } </code></pre>
[ { "answer_id": 74505273, "author": "jhnc", "author_id": 10971581, "author_profile": "https://Stackoverflow.com/users/10971581", "pm_score": 2, "selected": false, "text": "awk -v ORS= '\n NR>1 && /^, / { print \"\\n\" }\n 1;\n END { print \"\\n\" }\n' inputfile\n , , " }, { "answer_id": 74506998, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "AWK file.txt , NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to \nthe line below it.\n, NAME +18001112222, SENT, Text message contents that have\n\nmultiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n awk 'BEGIN{RS=\"\\n,\"}{ORS=RT;gsub(/\\n/,\" \");print}' file.txt\n , NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to the line below it.\n, NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n AWK RS \\n , ORS RT \\n print" }, { "answer_id": 74507485, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 1, "selected": false, "text": "sed $ sed -E ':a;/^,/{N;s/ *\\n($|[a-z])/ \\1/;ba}' input_file\n, NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to the line below it.\n, NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n" }, { "answer_id": 74508118, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed ':a;N;/\\n$\\|\\n[^,]/s/\\n//;ta;P;D' file\n , D" }, { "answer_id": 74508916, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 0, "selected": false, "text": "perl -0777 -pe 's/\\n+(?!,)/ /g;' yourfile\n \\n (?!$|,)" }, { "answer_id": 74510131, "author": "Walter A", "author_id": 3220113, "author_profile": "https://Stackoverflow.com/users/3220113", "pm_score": 1, "selected": false, "text": "sed -z sed -rz ':a;s/\\n([^,])/\\1/g;ta' inputfile\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386132/" ]
74,505,133
<pre><code>method1('id','name') </code></pre> <p>This is the method I called.</p> <pre><code>Array.prototype.method1 = function (property) { console.log(property) //Expect ['id','name'] ) </code></pre> <p>I want to get result like ['id','name']</p> <pre><code>const property = property.split(&quot;,&quot;); console.log(property) //This shows only ['id'] </code></pre> <p>Can anyone help me to do this?</p>
[ { "answer_id": 74505273, "author": "jhnc", "author_id": 10971581, "author_profile": "https://Stackoverflow.com/users/10971581", "pm_score": 2, "selected": false, "text": "awk -v ORS= '\n NR>1 && /^, / { print \"\\n\" }\n 1;\n END { print \"\\n\" }\n' inputfile\n , , " }, { "answer_id": 74506998, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 1, "selected": false, "text": "AWK file.txt , NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to \nthe line below it.\n, NAME +18001112222, SENT, Text message contents that have\n\nmultiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n awk 'BEGIN{RS=\"\\n,\"}{ORS=RT;gsub(/\\n/,\" \");print}' file.txt\n , NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to the line below it.\n, NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n AWK RS \\n , ORS RT \\n print" }, { "answer_id": 74507485, "author": "HatLess", "author_id": 16372109, "author_profile": "https://Stackoverflow.com/users/16372109", "pm_score": 1, "selected": false, "text": "sed $ sed -E ':a;/^,/{N;s/ *\\n($|[a-z])/ \\1/;ba}' input_file\n, NAME +18001112222, RECV, Text message contents.\n, NAME +18001112222, RECV, Text message contents that are run over to the line below it.\n, NAME +18001112222, SENT, Text message contents that have multiple lines and empty lines!\n, NAME +18001112222, SENT, Text Message contents \n" }, { "answer_id": 74508118, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "sed ':a;N;/\\n$\\|\\n[^,]/s/\\n//;ta;P;D' file\n , D" }, { "answer_id": 74508916, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 0, "selected": false, "text": "perl -0777 -pe 's/\\n+(?!,)/ /g;' yourfile\n \\n (?!$|,)" }, { "answer_id": 74510131, "author": "Walter A", "author_id": 3220113, "author_profile": "https://Stackoverflow.com/users/3220113", "pm_score": 1, "selected": false, "text": "sed -z sed -rz ':a;s/\\n([^,])/\\1/g;ta' inputfile\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551517/" ]
74,505,134
<p>In a test function, there is a case where nested slices should be compared. Say I have two varibles like the following:</p> <pre><code>want := [][]string{{&quot;bat&quot;},{&quot;nat&quot;,&quot;tan&quot;},{&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;}} got := [][]string{{&quot;eat&quot;,&quot;tea&quot;,&quot;ate&quot;},{&quot;tan&quot;,&quot;nat&quot;},{&quot;bat&quot;}} </code></pre> <p>How can compare them?</p> <p>First, I used <code>reflect.DeepEqual</code> which was wrong, I also tried <code>go-cmp</code>:</p> <pre><code> t.Run(tt.name, func(t *testing.T) { opt := cmpopts.SortSlices(func (a, b []int) bool { // not sure what to write }) if got := groupAnagrams(tt.args.strs); !cmp.Equal(got, tt.want, opt) { t.Errorf(&quot;groupAnagrams() = %v, want %v&quot;, got, tt.want) } }) </code></pre>
[ { "answer_id": 74505325, "author": "2 Penny Worth", "author_id": 20551757, "author_profile": "https://Stackoverflow.com/users/20551757", "pm_score": 1, "selected": false, "text": "for _, s := range want { sort.Strings(s) }\nfor _, s := range got { sort.Strings(s) }\n sortOuter(want)\nsortOuter(got)\n func sortOuter(s [][]string) {\n sort.Slice(s, func(a, b int) bool {\n sa := s[a]\n sb := s[b]\n n := len(sa)\n if n > len(sb) {\n n = len(sb)\n }\n for i := 0; i < n; i++ {\n if sa[i] != sb[i] {\n return sa[i] < sb[i]\n }\n }\n return len(sa) < len(sb)\n })\n}\n fmt.Println(reflect.DeepEqual(got, want))\n" }, { "answer_id": 74528313, "author": "Arsham Arya", "author_id": 12972198, "author_profile": "https://Stackoverflow.com/users/12972198", "pm_score": 0, "selected": false, "text": "sort.Slice assert.ElementsMatch func TestXxx(t *testing.T) {\n // Slices\n want := [][]string{{\"bat\"}, {\"nat\", \"tan\"}, {\"ate\", \"eat\", \"tea\"}}\n got := [][]string{{\"eat\", \"tea\", \"ate\"}, {\"tan\", \"nat\"}, {\"bat\"}}\n\n // Running tests\n t.Run(\"test\", func(t *testing.T) {\n // Sorting got inners\n for _, inner := range got {\n sort.Slice(inner, func(i, j int) bool {\n return inner[i] < inner[j]\n })\n }\n\n // Sorting want inners\n for _, inner := range want {\n sort.Slice(inner, func(i, j int) bool {\n return inner[i] < inner[j]\n })\n }\n\n // Match\n assert.ElementsMatch(t, got, want)\n })\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11211262/" ]
74,505,160
<p>Im reading the firestore flutter sdk documentation. It shows how to use a serializable class to automatically convert documents to objects with this example:</p> <pre><code>class Movie { Movie({required this.title, required this.genre}); Movie.fromJson(Map&lt;String, Object?&gt; json) : this( title: json['title']! as String, genre: json['genre']! as String, ); final String title; final String genre; Map&lt;String, Object?&gt; toJson() { return { 'title': title, 'genre': genre, }; } } </code></pre> <p>and then create a new document using the add function:</p> <pre><code> await moviesRef.add( Movie( title: 'Star Wars: A New Hope (Episode IV)', genre: 'Sci-fi' ), ); </code></pre> <p>How would I get the documentId after adding a new document or when querying?</p>
[ { "answer_id": 74505325, "author": "2 Penny Worth", "author_id": 20551757, "author_profile": "https://Stackoverflow.com/users/20551757", "pm_score": 1, "selected": false, "text": "for _, s := range want { sort.Strings(s) }\nfor _, s := range got { sort.Strings(s) }\n sortOuter(want)\nsortOuter(got)\n func sortOuter(s [][]string) {\n sort.Slice(s, func(a, b int) bool {\n sa := s[a]\n sb := s[b]\n n := len(sa)\n if n > len(sb) {\n n = len(sb)\n }\n for i := 0; i < n; i++ {\n if sa[i] != sb[i] {\n return sa[i] < sb[i]\n }\n }\n return len(sa) < len(sb)\n })\n}\n fmt.Println(reflect.DeepEqual(got, want))\n" }, { "answer_id": 74528313, "author": "Arsham Arya", "author_id": 12972198, "author_profile": "https://Stackoverflow.com/users/12972198", "pm_score": 0, "selected": false, "text": "sort.Slice assert.ElementsMatch func TestXxx(t *testing.T) {\n // Slices\n want := [][]string{{\"bat\"}, {\"nat\", \"tan\"}, {\"ate\", \"eat\", \"tea\"}}\n got := [][]string{{\"eat\", \"tea\", \"ate\"}, {\"tan\", \"nat\"}, {\"bat\"}}\n\n // Running tests\n t.Run(\"test\", func(t *testing.T) {\n // Sorting got inners\n for _, inner := range got {\n sort.Slice(inner, func(i, j int) bool {\n return inner[i] < inner[j]\n })\n }\n\n // Sorting want inners\n for _, inner := range want {\n sort.Slice(inner, func(i, j int) bool {\n return inner[i] < inner[j]\n })\n }\n\n // Match\n assert.ElementsMatch(t, got, want)\n })\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9393761/" ]
74,505,200
<p>See the attached sample code. If I clear the state when changing tabs by using TabBar onTap, the updated state is not reflected in the TabBarViews.</p> <p>In my sample code, clicking on the buttons in the TabBarViews sets state which highlights the button. When changing tabs, the buttons in the tabs should no longer be highlighted, but they still are.</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(const TabBarDemo()); } class TabBarDemo extends StatefulWidget { const TabBarDemo({super.key}); @override State&lt;TabBarDemo&gt; createState() =&gt; _TabBarDemoState(); } class _TabBarDemoState extends State&lt;TabBarDemo&gt; { int state = 0; @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( bottom: TabBar( tabs: const [ Tab(text: 'One'), Tab(text: 'Two'), ], onTap: (value) { setState(() =&gt; state = 0); }, ), title: const Text('Tabs Demo'), ), body: TabBarView( children: [ Center( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: (state == 1) ? Colors.blue : Colors.grey, ), onPressed: () { setState(() =&gt; state = 1); }, child: const Text('One'), ), ), Center( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: (state == 2) ? Colors.blue : Colors.grey, ), onPressed: () { setState(() =&gt; state = 2); }, child: const Text('Two'), ), ), ], ), ), ), ); } } </code></pre>
[ { "answer_id": 74505736, "author": "baek", "author_id": 1049200, "author_profile": "https://Stackoverflow.com/users/1049200", "pm_score": 2, "selected": true, "text": "flutter channel master flutter run" }, { "answer_id": 74505760, "author": "Tasnuva Tavasum oshin", "author_id": 8480069, "author_profile": "https://Stackoverflow.com/users/8480069", "pm_score": 0, "selected": false, "text": " class _TabBarDemoState extends State<TabBarDemo>{\n \n }\n class _TabBarDemoState extends State<Products> with TickerProviderStateMixin {\n late TabController _tabController;\n\n void initState() {\n super.initState();\n\n _tabController = TabController(\n vsync: this,\n length: 0,\n initialIndex: 0,\n );\n }\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551578/" ]
74,505,215
<p>Trying to create a function X(df): replaces the values of the FIRST column of the dataframe as per the following criteria:</p> <ol> <li>If the value is a number between 0 and 0.5 (so 0 &lt;= value &lt;= 0.5), replace this value with the sum of the values of all columns in this row.</li> <li>If the value is between 1.0 and 2.0 (so 1.0 &lt;= value &lt;= 2.0), replace this value with -99. (if in part 1. the original value is 0.1 and the sum of all columns (in that row) is 1.5, this value will be then replaced by -99 in part 2.)</li> </ol> <pre><code>original df: |idx| |A| |B| |0| |0.4| 1.0 |1| |0.0| 0.5 |2| |10.0| 0.0 |3| |1.5| -100.0 |4| |0.1| 0.1 |5| |0.5| -10.0 I have this so far: def X(df): for i in df.iloc[:, 0]: if (i &gt;= 0) and (i &lt;= 0.5): df.iloc[:,0] = df.sum(axis=1) elif (i&gt;=1) and (i&lt;=2): df.iloc[:,0] = int(-99) else: continue return df ''' I got: A B idx 0 3.4 1.0 1 1.5 0.5 2 10.0 0.0 3 -298.5 -100.0 4 0.4 0.1 5 -29.5 -10.0 I was expecting: A B idx 0 0.5 1.0 1 0.5 0.5 2 10.0 0.0 3 -99 -100.0 4 0.2 0.1 5 -9.5 -10.0 </code></pre>
[ { "answer_id": 74505736, "author": "baek", "author_id": 1049200, "author_profile": "https://Stackoverflow.com/users/1049200", "pm_score": 2, "selected": true, "text": "flutter channel master flutter run" }, { "answer_id": 74505760, "author": "Tasnuva Tavasum oshin", "author_id": 8480069, "author_profile": "https://Stackoverflow.com/users/8480069", "pm_score": 0, "selected": false, "text": " class _TabBarDemoState extends State<TabBarDemo>{\n \n }\n class _TabBarDemoState extends State<Products> with TickerProviderStateMixin {\n late TabController _tabController;\n\n void initState() {\n super.initState();\n\n _tabController = TabController(\n vsync: this,\n length: 0,\n initialIndex: 0,\n );\n }\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20201498/" ]
74,505,234
<p>As the title says I would like to give my player a temporary 2x multiplier and then take it away after. So far I have a button they click that sets their current multiplier x2 and then after 10 seconds take it away, the issue is if they buy an increase to their multiplier during that time it messes things up and I am not sure how to handle it. GameManager.The multiplier is set to 1 at the start of the game and can be added to by purchasing an &quot;upgrade&quot;.</p> <p>Edit: I have two scripts one that keeps track of how much Iron you have and What your current click multiplier is it also handles displaying both to the screen with text it's called GameManager.</p> <p>My game has 3 buttons one takes 10 Iron and gives the player plus 1 to their click multiplier the other 2 do the same thing, but requires more Iron and gives a higher bump to the click multiplier.</p> <p>I then added a 4th button that when pressed will give the player a 2x to their multiplier for 30 sec (ex current click multiplier is 5 after button press it is now 10 after 30 sec it returns to 5)</p> <p>The issue is that if the player clicks the 2x button and then buys a 1x click multiplier upgrade they do not keep the one they purchased during the 2x button coroutine. (ex current click multiplier is 1 click the 2x button click multiplier is now 2 then buy a 1x upgrade so the click multiplier is now 3. After the 30 sec the multiplier should return to 2 but instead returns to 1 as if they never purchased the 1x upgrade)</p> <p>Hopefully, this is a bit better at explaining my issue. I tried adding a temp var of my original multiplier and then using mathf.ABS to figure out the difference and then do something with that, but it's honestly starting to confuse the crap out of me so I'm asking here for advice lol My code for it so far is:</p> <pre><code>using UnityEngine; using UnityEngine.UI; using System.Collections; public class TwoX: MonoBehaviour { [SerializeField] Button _TwoX; void Start () { Button btn = TwoX.GetComponent&lt;Button&gt;(); btn.onClick.AddListener(TaskOnClick); } void TaskOnClick(){ StartCoroutine(test()); } IEnumerator test() { GameManager.Multiplier = GameManager.Multiplier * 2; yield return new WaitForSeconds(10); GameManager.Multiplier = GameManager.Multiplier / 2; } } </code></pre>
[ { "answer_id": 74505282, "author": "LydiasPost", "author_id": 13393309, "author_profile": "https://Stackoverflow.com/users/13393309", "pm_score": 0, "selected": false, "text": "using UnityEngine;\nusing UnityEngine.UI;\nusing System.Collections;\npublic class TwoX: MonoBehaviour\n{\n [SerializeField] Button _TwoX;\n\n float upgradeTime = 0.0f;\n float delay = 10.0f\n bool isUpgraded = false;\n\n void Start ()\n {\n Button btn = TwoX.GetComponent<Button>();\n btn.onClick.AddListener(TaskOnClick);\n }\n\n void TaskOnClick()\n {\n if (!isUpgraded)\n {\n GameManager.Multiplier *= 2;\n upgradeTime = Time.time;\n isUpgraded = true;\n }\n }\n\n void Update()\n {\n if (Time.time >= upgradeTime + delay && isUpgraded)\n {\n GameManager.Multiplier /= 2;\n isUpgraded = false;\n }\n }\n}\n" }, { "answer_id": 74516061, "author": "derHugo", "author_id": 7111561, "author_profile": "https://Stackoverflow.com/users/7111561", "pm_score": 2, "selected": true, "text": "GameManager.Multiplier int 1 * 2 2 + 1 3 / 2 1 int float 1.5f * / + - private bool alreadyDoubled;\n\nIEnumerator test()\n{\n // avoid hat the routine is running multiple times if your player spams the button\n if(alreadyDoubled) yield break;\n\n // block other instances of this routine\n alreadyDoubled = true;\n\n // cache the original value!\n // the advantage of a Coroutine here is that you can simply keep\n // along a value within this Coroutines scope\n var addition = GameManager.Multiplier;\n\n // This basically equals doing * 2\n GameManager.Multiplier += addition; \n\n yield return new WaitForSeconds(10);\n\n // This only removes the addition, regardless of what happened to the value in the meantime\n GameManager.Multiplier -= addition; \n\n // allow the next instance of this routine to start\n alreaeyDoubled = false;\n}\n 1 * 2 + 1 2 + 1 3 / 2 - 1 2" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9005366/" ]
74,505,236
<p>I want to make a Discord interaction that sends a picture for as often as you say in 'howmany', but with my current code it send 1 embed with a picture and the rest without one. How to fix this?</p> <pre><code>@tree.command(name='embed', description='embed') async def embed(interaction: discord.Interaction, seeable: bool, howmany: typing.Optional[int]): embed = discord.Embed(title=&quot;Here is a title&quot;, color=0xff8c00) file = discord.File(f&quot;[file path]&quot;, filename=&quot;image.png&quot;) embed.set_image(url=&quot;attachment://image.png&quot;) if seeable == True: await interaction.response.send_message(file=file, embed=embed) if howmany &gt;= 2: for i in range(howmany-1): await interaction.followup.send(file=file, embed=embed) if seeable == False: await interaction.response.send_message(file=file, embed=embed, ephemeral=True) if howmany &gt;= 2: for i in range(howmany-1): await interaction.followup.send(file=file, embed=embed, ephemeral=True) </code></pre> <p>it already works perfectly fine without the interaction, just like the old prefix system. If you remove all the # it will upload the files from a file path. Otherwise it will show a Picture from a website:</p> <pre><code>if message.content.startswith('+image'): count = 0 args = message.content.split(' ') if len(args) &lt; 2: count = 1 else: if args[1].isdigit(): count = int(args[1]) else: await message.channel.send(&quot;How many should it be?&quot;) for i in range(count): random = random.randint(1,68) embed = discord.Embed(title=&quot;Title&quot;, color=0xff8c00) embed.set_image(url=f&quot;https://www.awebsite/pic{random}.png&quot;) #file = discord.File(f&quot;C:a/file/path/pic{random}.png&quot;, filename=&quot;image.png&quot;) #embed.set_image(url=&quot;attachment://image.png&quot;) #await message.channel.send(file=file, embed=embed) await message.channel.send(embed=embed) </code></pre>
[ { "answer_id": 74509324, "author": "lorenzfohl", "author_id": 20550433, "author_profile": "https://Stackoverflow.com/users/20550433", "pm_score": 0, "selected": false, "text": "@tree.command(name='embed', description='embed')\nasync def embed(interaction: discord.Interaction, seeable: bool, menge: typing.Optional[int]):\n if seeable == True:\n zufall = random.randint(1, 68)\n embed = discord.Embed(title=\"embed\", color=0xff8c00)\n file = discord.File(f\"C:/file/path/pic{zufall}.png\", filename=\"image.png\")\n embed.set_image(url=\"attachment://image.png\")\n await interaction.response.send_message(file=file, embed=embed)\n \n if menge >= 2:\n for i in range(menge - 1):\n zufall = random.randint(1, 68)\n embed = discord.Embed(title=\"embed\", color=0xff8c00)\n file = discord.File(f\"C:/file/path/pic{zufall}.png\", filename=\"image.png\")\n embed.set_image(url=\"attachment://image.png\")\n await interaction.response.send_message(file=file, embed=embed)\n\n if seeable == False:\n zufall = random.randint(1, 68)\n embed = discord.Embed(title=\"embed\", color=0xff8c00)\n file = discord.File(f\"C:/file/path/pic{zufall}.png\", filename=\"image.png\")\n embed.set_image(url=\"attachment://image.png\")\n await interaction.response.send_message(file=file, embed=embed, ephemeral=True)\n #await interaction.response.send_message(embed=embed)\n\n if menge >= 2:\n for i in range(menge - 1):\n zufall = random.randint(1, 68)\n embed = discord.Embed(title=\"embed\", color=0xff8c00)\n file = discord.File(f\"C:/file/path/pic{zufall}.png\", filename=\"image.png\")\n embed.set_image(url=\"attachment://image.png\")\n await interaction.response.send_message(file=file, embed=embed, ephemeral=True)\n" }, { "answer_id": 74511567, "author": "stijndcl", "author_id": 13568999, "author_profile": "https://Stackoverflow.com/users/13568999", "pm_score": 1, "selected": false, "text": "send_message embeds embed ...send_message(..., embeds=[embed1, embed2, embed3])\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550433/" ]
74,505,267
<p>I have the following entity:</p> <pre><code>@Entity @Data @NoArgsConstructor @AllArgsConstructor @Table(name = &quot;USER&quot;) public class User implements Serializable { @Id @Column(name = &quot;NAME&quot;, nullable = false) private String name; @Column(name = &quot;AGE&quot;, nullable = false) private int age; @Column(name = &quot;DETAILS&quot;, nullable = false, columnDefinition = &quot;json&quot; ) private String details; } </code></pre> <p>When I receive a new user object I will try to persist it in the database.</p> <pre><code>{ &quot;age&quot;: 5, &quot;name&quot;: &quot;MARIO&quot;, &quot;details&quot;: &quot;{\&quot;country\&quot;:\&quot;Indonesia\&quot;}&quot; } </code></pre> <p>For some reason I cant save with with the normal JpaRepository save,</p> <pre><code>@Autowired UserRepository userRepository; public saveNewUser(User newUser){ userRepository.save(newUser); } </code></pre> <p>Running the save user function throws me this error:</p> <pre><code>java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'age=5 where name='MARIO'' at line 1 </code></pre> <p>But if i define my own custom save method in the repository it saves just fine with no issues:</p> <pre><code>@Repository public interface UserRepository extends JpaRepository&lt;User, String&gt; { @Modifying @Transactional @Query(value = &quot;insert into USER (NAME, AGE, DETAILS) values (:name, :age, :details)&quot;, nativeQuery = true) void saveWithJson(String name, String details, int age); </code></pre> <p>}</p> <p>and I call it like so:</p> <pre><code>@Autowired UserRepository userRepository; public saveNewUser(User newUser){ userRepository.saveWithJson(newUser.getName, newUser.getDetails, newUser.getAge); } </code></pre> <p>Any idea why this is happening? I tested with the exact same JSON being received. I dont mind using my own save query, I just assumed that underneath the layer of abstraction JPA should be calling the same method as my native query?</p>
[ { "answer_id": 74509133, "author": "Subha Chandra", "author_id": 2236549, "author_profile": "https://Stackoverflow.com/users/2236549", "pm_score": 0, "selected": false, "text": "spring.jpa.show-sql: true\n" }, { "answer_id": 74528948, "author": "Pierre Demeestere", "author_id": 19868455, "author_profile": "https://Stackoverflow.com/users/19868455", "pm_score": 2, "selected": true, "text": "User @Table(name = \"USER\") user" }, { "answer_id": 74530518, "author": "Xianghua", "author_id": 17325694, "author_profile": "https://Stackoverflow.com/users/17325694", "pm_score": 0, "selected": false, "text": "@Entity\n@Data\n@Table(name = \"USER\")\npublic class User{\n\n @Id\n @Column(name = \"NAME\", columnDefinition = \"varchar(32) comment 'id:name'\")\n private String name;\n\n @Column(name = \"AGE\", columnDefinition = \"int(3) comment 'age'\")\n private Integer age;\n\n @Column(name = \"DETAILS\", columnDefinition = \"text comment 'details'\")\n private String details;\n}\n\n\n@Repository\npublic interface UserRepository extends JpaRepository<User, String>, JpaSpecificationExecutor<User> {\n \n}\n\npublic UserService {\n @Autowired\n UserRepository userRepository;\n\n public void saveNewUser(User newUser) {\n userRepository.save(newUser);\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15040818/" ]
74,505,270
<p>Does anyone know whether there's the equivalent of <code>dplyr::select()</code> for subsetting character vectors? Specifically, what I like about <code>dplyr::select()</code> is the how easy it is to select dataframe columns; one can input the names of the columns (with or without quotes) and similarly create ranges from those names. Is there any function where you could take a character vector, and without using any helper function(s), create a range for the purposes of subsetting.</p> <p>For example, let's create an aribitrary vector (but assume that this vector was the result of some other operation, like pulling sheet names from an Excel file):</p> <pre><code>char_vec &lt;- c(&quot;Exclude1&quot;, paste0(&quot;Include&quot;, 1:5), &quot;Exclude2&quot;) </code></pre> <p>Is there a function where a user could input: <code>someFunction(char_vec, Include1:Include5)</code> in order to get the result?</p> <p>I realize that there are a bunch of regex related solutions as well as good old base R -- <code>char_vec[which(char_vec == &quot;Include1&quot;):which(char_vec == &quot;Include5&quot;)]</code> -- but I was hoping for a function that resembled <code>dplyr::select()</code></p>
[ { "answer_id": 74509133, "author": "Subha Chandra", "author_id": 2236549, "author_profile": "https://Stackoverflow.com/users/2236549", "pm_score": 0, "selected": false, "text": "spring.jpa.show-sql: true\n" }, { "answer_id": 74528948, "author": "Pierre Demeestere", "author_id": 19868455, "author_profile": "https://Stackoverflow.com/users/19868455", "pm_score": 2, "selected": true, "text": "User @Table(name = \"USER\") user" }, { "answer_id": 74530518, "author": "Xianghua", "author_id": 17325694, "author_profile": "https://Stackoverflow.com/users/17325694", "pm_score": 0, "selected": false, "text": "@Entity\n@Data\n@Table(name = \"USER\")\npublic class User{\n\n @Id\n @Column(name = \"NAME\", columnDefinition = \"varchar(32) comment 'id:name'\")\n private String name;\n\n @Column(name = \"AGE\", columnDefinition = \"int(3) comment 'age'\")\n private Integer age;\n\n @Column(name = \"DETAILS\", columnDefinition = \"text comment 'details'\")\n private String details;\n}\n\n\n@Repository\npublic interface UserRepository extends JpaRepository<User, String>, JpaSpecificationExecutor<User> {\n \n}\n\npublic UserService {\n @Autowired\n UserRepository userRepository;\n\n public void saveNewUser(User newUser) {\n userRepository.save(newUser);\n }\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14893074/" ]
74,505,286
<p>Hi im a beginner in web development and i am trying to make this website where when u load it there will be a text centered in the middle that has a typing animation, eventually the words left in the div will be 'Nice Paws'. It will then have this animation that translates its Y position and goes to the top of the screen.</p> <p>Question is im not sure how to translate the Y position so that it will always end up on the top of the screen and not disappear when i resize the window.</p> <p>All help is appreciated! Thanks!</p> <p>HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- &lt;nav class=&quot;trans&quot;&gt;&lt;/nav&gt; --&gt; &lt;div class=&quot;slogan-container&quot; id=&quot;slogan-container&quot;&gt; &lt;div id=&quot;slogan&quot;&gt;&lt;/div&gt;&lt;div class=&quot;brand-name&quot; id=&quot;name-typed&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;div style=&quot;height: 100%; background-color: aliceblue;&quot;&gt;&lt;/div&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/typed.js@2.0.12&quot;&gt;&lt;/script&gt; &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code>html, body { height: 100%; background-color: antiquewhite !important; overflow: auto; } .slogan-container { font-family: 'Lexend Deca', sans-serif; font-size: 30px; font-weight: 400; height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; position: relative; } .brand-name { font-family: 'Lexend Deca', sans-serif; font-weight: 600; } .slogan { } </code></pre> <p>JS</p> <pre><code>var slogan = new Typed(&quot;#slogan&quot;, { strings: [&quot;Damn, those are some&amp;nbsp;&quot;, &quot;&quot;], typeSpeed: 25, backSpeed: 19, loop: false, showCursor: false, backDelay: 1500, onStringTyped: function(pos, slogan) { if(pos == 0) { var name = new Typed(&quot;#name-typed&quot;, { strings: [&quot;Nice Paws&quot;], typeSpeed: 25, loop: false, showCursor: false, }) } else if(pos == 1) { // height = document.getElementById(&quot;slogan-container&quot;).offsetHeight; // console.log(height); const move = [ { transform: 'translateY(-440px)' } // { transform: 'translateY(-20vh)' } ]; const moveTiming = { duration: 1500, delay: 500, fill: 'forwards', easing: 'ease-in-out' } var elem = document.getElementById(&quot;name-typed&quot;); elem.animate(move, moveTiming); elem.style.position = 'fixed'; console.log(elem.style.position) } } }) </code></pre> <p><a href="https://jsfiddle.net/fx487hrj/" rel="nofollow noreferrer">Fiddle: </a></p> <p>I tried using 'vh' instead of 'px' but when i resize the screen it just disappears as well.</p>
[ { "answer_id": 74505413, "author": "segFault", "author_id": 1514049, "author_profile": "https://Stackoverflow.com/users/1514049", "pm_score": 1, "selected": false, "text": "calc translateY(calc(-50vh + 22.5px)) 22.5px div.brand-name 45px const move = [\n { transform: 'translateY(calc(-50vh + 22.5px))' }\n];\n" }, { "answer_id": 74505466, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "translateY margin-top margin-top: calc(50vh - 30px) {marginTop: \"20px\"} brand-name var slogan = new Typed(\"#slogan\", {\n strings: [\"Damn, those are some&nbsp;\", \"\"],\n typeSpeed: 25,\n backSpeed: 19,\n loop: false,\n showCursor: false,\n backDelay: 1500,\n onStringTyped: function(pos, slogan) {\n if(pos == 0) {\n var name = new Typed(\"#name-typed\", {\n strings: [\"Nice Paws\"],\n typeSpeed: 25,\n loop: false,\n showCursor: false,\n })\n } else if(pos == 1) {\n\n const move = [\n {marginTop: \"20px\"}\n ];\n const moveTiming = {\n duration: 1500,\n delay: 500,\n fill: 'forwards',\n easing: 'ease-in-out'\n }\n var elem = document.getElementById(\"name-typed\");\n elem.animate(move, moveTiming);\n elem.style.position = 'fixed';\n console.log(elem.style.position)\n }\n }\n}) html, body {\n height: 100%;\n background-color: antiquewhite !important;\n overflow: auto;\n}\n\n.slogan-container {\n font-family: 'Lexend Deca', sans-serif;\n font-size: 30px;\n font-weight: 400;\n\n height: 100%;\n width: 100%;\n\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n position: relative;\n}\n\n.brand-name {\n font-family: 'Lexend Deca', sans-serif;\n font-weight: 600;\n}\n\n#slogan, .brand-name {\n margin-top: calc(50vh - 30px);\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link href=\"https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap\" rel=\"stylesheet\">\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n</head>\n<body>\n <!-- <nav class=\"trans\"></nav> -->\n <div class=\"slogan-container\" id=\"slogan-container\">\n <div id=\"slogan\"></div><div class=\"brand-name\" id=\"name-typed\"></div>\n </div>\n <div style=\"height: 100%; background-color: aliceblue;\"></div> \n <script src=\"https://cdn.jsdelivr.net/npm/typed.js@2.0.12\"></script>\n <script src=\"index.js\"></script>\n</body>\n</html>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13673381/" ]
74,505,299
<p>This might be pretty basic, but my code seems to have a few errors or expectations that might not work for me. Some background information: My code was created so that it asks the user for an integer. Then the user's input will be analyzed and will show the user an output of numbers that multiplied together will equal the user's input.</p> <p><strong>Expectation</strong></p> <p>Input: 7 Output(In console): (1,7)(7,1).</p> <p>But instead, my code also inputs the decimals that equal the user's input.</p> <p><strong>Reality</strong></p> <p>Input: 7 Output: (1.1666666666666667, 6), (1.4, 5), (1.75, 4), (2.3333333333333335, 3), (3.5, 2), (7, 1), (Infinity, 0).</p> <pre><code> var numInput= parseInt(prompt(&quot;Please enter a number larger than 1&quot;)); //This asks the user for the input var valueArray = [];//This is the empty array we are going to use in the further code. if(numInput &lt;= 0 || numInput &lt;= 1) { console.log(&quot;Goodbye!&quot;) }//This line is an if loop which if the user inputs 0 or 1 then the code will end. while(numInput &gt; 0) {// This while loop is there so that the user can input as many numbers he wants var valueArray = [];//Now the numbers are inside this empty array var numInput = parseInt(prompt(&quot;Please enter a number larger than 1&quot;)); for (var iterator = 0; iterator &lt; numInput; ++iterator) {//This for loop is the calculation, for when a = 1, the a has a greater value then var valueSubtracted = numInput / iterator //This is where the variable subtracts the orignal value n so that we have something along the lines of (1,6) instead (1,7) valueArray.unshift(valueSubtracted + &quot;, &quot; + iterator ); //This just moves the answers into a concantination, and moves into the array } console.log(&quot;The additive combinations are: &quot; + &quot;(&quot; + valueArray.join(&quot;), (&quot;) + &quot;). &quot;); } </code></pre> <p>All I really want is for the decimals to be removed and the number associated with it. For example:</p> <p>Input: 7 Output: <em><strong>(1.1666666666666667, 6)</strong></em>, <em><strong>(1.4, 5),</strong></em> <em><strong>(1.75, 4),</strong></em> <em><strong>(2.3333333333333335, 3)</strong></em>, <em><strong>(3.5, 2),</strong></em> (7, 1), <em><strong>(Infinity, 0).</strong></em></p> <p>Note that above: the bolded and italicized are supposed to be removed from the array. <a href="https://i.stack.imgur.com/LwbaB.png" rel="nofollow noreferrer">This is what it looks like in the console.</a></p>
[ { "answer_id": 74505413, "author": "segFault", "author_id": 1514049, "author_profile": "https://Stackoverflow.com/users/1514049", "pm_score": 1, "selected": false, "text": "calc translateY(calc(-50vh + 22.5px)) 22.5px div.brand-name 45px const move = [\n { transform: 'translateY(calc(-50vh + 22.5px))' }\n];\n" }, { "answer_id": 74505466, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "translateY margin-top margin-top: calc(50vh - 30px) {marginTop: \"20px\"} brand-name var slogan = new Typed(\"#slogan\", {\n strings: [\"Damn, those are some&nbsp;\", \"\"],\n typeSpeed: 25,\n backSpeed: 19,\n loop: false,\n showCursor: false,\n backDelay: 1500,\n onStringTyped: function(pos, slogan) {\n if(pos == 0) {\n var name = new Typed(\"#name-typed\", {\n strings: [\"Nice Paws\"],\n typeSpeed: 25,\n loop: false,\n showCursor: false,\n })\n } else if(pos == 1) {\n\n const move = [\n {marginTop: \"20px\"}\n ];\n const moveTiming = {\n duration: 1500,\n delay: 500,\n fill: 'forwards',\n easing: 'ease-in-out'\n }\n var elem = document.getElementById(\"name-typed\");\n elem.animate(move, moveTiming);\n elem.style.position = 'fixed';\n console.log(elem.style.position)\n }\n }\n}) html, body {\n height: 100%;\n background-color: antiquewhite !important;\n overflow: auto;\n}\n\n.slogan-container {\n font-family: 'Lexend Deca', sans-serif;\n font-size: 30px;\n font-weight: 400;\n\n height: 100%;\n width: 100%;\n\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n position: relative;\n}\n\n.brand-name {\n font-family: 'Lexend Deca', sans-serif;\n font-weight: 600;\n}\n\n#slogan, .brand-name {\n margin-top: calc(50vh - 30px);\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link href=\"https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap\" rel=\"stylesheet\">\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n</head>\n<body>\n <!-- <nav class=\"trans\"></nav> -->\n <div class=\"slogan-container\" id=\"slogan-container\">\n <div id=\"slogan\"></div><div class=\"brand-name\" id=\"name-typed\"></div>\n </div>\n <div style=\"height: 100%; background-color: aliceblue;\"></div> \n <script src=\"https://cdn.jsdelivr.net/npm/typed.js@2.0.12\"></script>\n <script src=\"index.js\"></script>\n</body>\n</html>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551674/" ]
74,505,314
<p>So I got a super weird problem here. I spun up a new server to restore a backup (tried taking a new snapshot and restoring a backup few times since original server is doing well).</p> <pre><code>create index on companies ((linkedin_name(company url))); </code></pre> <p>this works on the original server (pgsql 14). on the new server (pgsql 15) I get this error</p> <pre><code>could not execute query: ERROR: could not read block 0 in file &quot;base/16387/8646581&quot;: read only 0 of 8192 bytes </code></pre> <p>this is where it gets weird. if I do this, it works fine</p> <pre><code>create table companies2 as select * from companies; create index on companies2 ((linkedin_name(company url))); </code></pre> <p>this works just fine... THEN... and this is where it gets REALLY weird.</p> <pre><code>drop table companies; alter table companies2 rename to companies; </code></pre> <p>this shows the index but if I try to reindex I now get the same error!!</p> <p>... I don't even know where to begin to debug this. Thoughts?</p>
[ { "answer_id": 74505413, "author": "segFault", "author_id": 1514049, "author_profile": "https://Stackoverflow.com/users/1514049", "pm_score": 1, "selected": false, "text": "calc translateY(calc(-50vh + 22.5px)) 22.5px div.brand-name 45px const move = [\n { transform: 'translateY(calc(-50vh + 22.5px))' }\n];\n" }, { "answer_id": 74505466, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "translateY margin-top margin-top: calc(50vh - 30px) {marginTop: \"20px\"} brand-name var slogan = new Typed(\"#slogan\", {\n strings: [\"Damn, those are some&nbsp;\", \"\"],\n typeSpeed: 25,\n backSpeed: 19,\n loop: false,\n showCursor: false,\n backDelay: 1500,\n onStringTyped: function(pos, slogan) {\n if(pos == 0) {\n var name = new Typed(\"#name-typed\", {\n strings: [\"Nice Paws\"],\n typeSpeed: 25,\n loop: false,\n showCursor: false,\n })\n } else if(pos == 1) {\n\n const move = [\n {marginTop: \"20px\"}\n ];\n const moveTiming = {\n duration: 1500,\n delay: 500,\n fill: 'forwards',\n easing: 'ease-in-out'\n }\n var elem = document.getElementById(\"name-typed\");\n elem.animate(move, moveTiming);\n elem.style.position = 'fixed';\n console.log(elem.style.position)\n }\n }\n}) html, body {\n height: 100%;\n background-color: antiquewhite !important;\n overflow: auto;\n}\n\n.slogan-container {\n font-family: 'Lexend Deca', sans-serif;\n font-size: 30px;\n font-weight: 400;\n\n height: 100%;\n width: 100%;\n\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n position: relative;\n}\n\n.brand-name {\n font-family: 'Lexend Deca', sans-serif;\n font-weight: 600;\n}\n\n#slogan, .brand-name {\n margin-top: calc(50vh - 30px);\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link href=\"https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap\" rel=\"stylesheet\">\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n</head>\n<body>\n <!-- <nav class=\"trans\"></nav> -->\n <div class=\"slogan-container\" id=\"slogan-container\">\n <div id=\"slogan\"></div><div class=\"brand-name\" id=\"name-typed\"></div>\n </div>\n <div style=\"height: 100%; background-color: aliceblue;\"></div> \n <script src=\"https://cdn.jsdelivr.net/npm/typed.js@2.0.12\"></script>\n <script src=\"index.js\"></script>\n</body>\n</html>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5759219/" ]
74,505,322
<p>I have run into a horrible situation on one of my cassandra clusters. The version the cluster is on is 3.0.5. I am running a 2 DC setup with close 30 nodes, 18 in one DC and the rest in the other. I did everything possible with my knowledge, but still looking for answers.</p> <p>Of late we were having a few issues with respect to GC pauses, a few turnings were done on the jvm(MAX_HEAP_SIZE was changed) on all nodes and the cluster was ready for the rolling restart to take effect.</p> <p>The 1st node went through well with the rolling restart, but the 2nd node just did not comeback up after the shut down. And the error below.</p> <pre><code>INFO 07:45:34 Initializing system_schema.keyspaces INFO 07:45:34 Initializing system_schema.tables INFO 07:45:34 Initializing system_schema.columns INFO 07:45:34 Initializing system_schema.triggers INFO 07:45:34 Initializing system_schema.dropped_columns INFO 07:45:34 Initializing system_schema.views INFO 07:45:34 Initializing system_schema.types INFO 07:45:34 Initializing system_schema.functions INFO 07:45:34 Initializing system_schema.aggregates INFO 07:45:34 Initializing system_schema.indexes Exception (java.lang.IllegalStateException) encountered during startup: One row required, 2 found java.lang.IllegalStateException: One row required, 2 found at org.apache.cassandra.cql3.UntypedResultSet$FromResultSet.one(UntypedResultSet.java:84) at org.apache.cassandra.schema.SchemaKeyspace.fetchTable(SchemaKeyspace.java:948) at org.apache.cassandra.schema.SchemaKeyspace.fetchTables(SchemaKeyspace.java:938) at org.apache.cassandra.schema.SchemaKeyspace.fetchKeyspace(SchemaKeyspace.java:901) at org.apache.cassandra.schema.SchemaKeyspace.fetchKeyspacesWithout(SchemaKeyspace.java:878) at org.apache.cassandra.schema.SchemaKeyspace.fetchNonSystemKeyspaces(SchemaKeyspace.java:866) at org.apache.cassandra.config.Schema.loadFromDisk(Schema.java:134) at org.apache.cassandra.config.Schema.loadFromDisk(Schema.java:124) at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:229) at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:551) at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:679) </code></pre> <p>after running repairs on the cluster, and specifically on the system keyspaces, the error still persisted. When the node did not comeup eventually, i had it removed from the cluster, using the nodetool removenode command from a healthy node.</p> <p>Again, another node was taken up for restart in the same cluster and datacenter, again it did not come back up, with the same error.</p> <p>I was also unable to login to the cqlsh shell from a healthy node, with the below error</p> <pre><code>Connection error: ('Unable to connect to any servers', {'&lt;&lt;VM hostname&gt;&gt;': UnicodeDecodeError('utf8', '\x7f\x00\x00\x80C\x02', 3, 4, 'invalid start byte')}) </code></pre> <p>This error also was seen on a few other nodes</p> <pre><code>Connection error: ('Unable to connect to any servers', {'&lt;&lt;VM Hostname&gt;&gt;': ConnectionShutdown(&quot;'utf8' codec can't decode byte 0x80 in position 3: invalid start byte&quot;,)}) </code></pre> <p>Essentially, the cluster has nothing working except the nodetool commands.</p> <p>When i ran a nodetool describe cluster, i saw 5 different schema versions for various nodes and also saw some 9 nodes as unreachable, below is the output</p> <pre><code>./nodetool describecluster Cluster Information: Name: Dummy cluster Snitch: org.apache.cassandra.locator.DynamicEndpointSnitch Partitioner: org.apache.cassandra.dht.Murmur3Partitioner Schema versions: 1590ea6a-8c19-342a-8269-204c64a12176: [9 nodes here] 668d9efd-13c1-3fb3-9b89-7fc07d9ddf0b: [1 node here] d20dc0de-dd34-3183-b459-31e3feb8f118: [3 nodes here] 3ec9610c-d241-3215-84f2-2413b8cad7d2: [7 nodes here] 59adb24e-f3cd-3e02-97f0-5b395827453f: [1 node here] UNREACHABLE: [9 nodes unreachable] </code></pre> <p>Can someone pls help in understanding what the issue could be and also a way to bring the nodes back up? I also tried the ignore schema mismatch flag in cassandra-env.sh/jvm.options to bring the node up, but that did not help as well.</p>
[ { "answer_id": 74505413, "author": "segFault", "author_id": 1514049, "author_profile": "https://Stackoverflow.com/users/1514049", "pm_score": 1, "selected": false, "text": "calc translateY(calc(-50vh + 22.5px)) 22.5px div.brand-name 45px const move = [\n { transform: 'translateY(calc(-50vh + 22.5px))' }\n];\n" }, { "answer_id": 74505466, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "translateY margin-top margin-top: calc(50vh - 30px) {marginTop: \"20px\"} brand-name var slogan = new Typed(\"#slogan\", {\n strings: [\"Damn, those are some&nbsp;\", \"\"],\n typeSpeed: 25,\n backSpeed: 19,\n loop: false,\n showCursor: false,\n backDelay: 1500,\n onStringTyped: function(pos, slogan) {\n if(pos == 0) {\n var name = new Typed(\"#name-typed\", {\n strings: [\"Nice Paws\"],\n typeSpeed: 25,\n loop: false,\n showCursor: false,\n })\n } else if(pos == 1) {\n\n const move = [\n {marginTop: \"20px\"}\n ];\n const moveTiming = {\n duration: 1500,\n delay: 500,\n fill: 'forwards',\n easing: 'ease-in-out'\n }\n var elem = document.getElementById(\"name-typed\");\n elem.animate(move, moveTiming);\n elem.style.position = 'fixed';\n console.log(elem.style.position)\n }\n }\n}) html, body {\n height: 100%;\n background-color: antiquewhite !important;\n overflow: auto;\n}\n\n.slogan-container {\n font-family: 'Lexend Deca', sans-serif;\n font-size: 30px;\n font-weight: 400;\n\n height: 100%;\n width: 100%;\n\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n position: relative;\n}\n\n.brand-name {\n font-family: 'Lexend Deca', sans-serif;\n font-weight: 600;\n}\n\n#slogan, .brand-name {\n margin-top: calc(50vh - 30px);\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link href=\"https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap\" rel=\"stylesheet\">\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n</head>\n<body>\n <!-- <nav class=\"trans\"></nav> -->\n <div class=\"slogan-container\" id=\"slogan-container\">\n <div id=\"slogan\"></div><div class=\"brand-name\" id=\"name-typed\"></div>\n </div>\n <div style=\"height: 100%; background-color: aliceblue;\"></div> \n <script src=\"https://cdn.jsdelivr.net/npm/typed.js@2.0.12\"></script>\n <script src=\"index.js\"></script>\n</body>\n</html>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549586/" ]
74,505,323
<p>If a remote repo's branch is only maintained by me, I never have to do a git fetch, is that a correct statement?</p> <p>Just want to confirm my guess.</p>
[ { "answer_id": 74505413, "author": "segFault", "author_id": 1514049, "author_profile": "https://Stackoverflow.com/users/1514049", "pm_score": 1, "selected": false, "text": "calc translateY(calc(-50vh + 22.5px)) 22.5px div.brand-name 45px const move = [\n { transform: 'translateY(calc(-50vh + 22.5px))' }\n];\n" }, { "answer_id": 74505466, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 1, "selected": true, "text": "translateY margin-top margin-top: calc(50vh - 30px) {marginTop: \"20px\"} brand-name var slogan = new Typed(\"#slogan\", {\n strings: [\"Damn, those are some&nbsp;\", \"\"],\n typeSpeed: 25,\n backSpeed: 19,\n loop: false,\n showCursor: false,\n backDelay: 1500,\n onStringTyped: function(pos, slogan) {\n if(pos == 0) {\n var name = new Typed(\"#name-typed\", {\n strings: [\"Nice Paws\"],\n typeSpeed: 25,\n loop: false,\n showCursor: false,\n })\n } else if(pos == 1) {\n\n const move = [\n {marginTop: \"20px\"}\n ];\n const moveTiming = {\n duration: 1500,\n delay: 500,\n fill: 'forwards',\n easing: 'ease-in-out'\n }\n var elem = document.getElementById(\"name-typed\");\n elem.animate(move, moveTiming);\n elem.style.position = 'fixed';\n console.log(elem.style.position)\n }\n }\n}) html, body {\n height: 100%;\n background-color: antiquewhite !important;\n overflow: auto;\n}\n\n.slogan-container {\n font-family: 'Lexend Deca', sans-serif;\n font-size: 30px;\n font-weight: 400;\n\n height: 100%;\n width: 100%;\n\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n position: relative;\n}\n\n.brand-name {\n font-family: 'Lexend Deca', sans-serif;\n font-weight: 600;\n}\n\n#slogan, .brand-name {\n margin-top: calc(50vh - 30px);\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link href=\"https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap\" rel=\"stylesheet\">\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\">\n</head>\n<body>\n <!-- <nav class=\"trans\"></nav> -->\n <div class=\"slogan-container\" id=\"slogan-container\">\n <div id=\"slogan\"></div><div class=\"brand-name\" id=\"name-typed\"></div>\n </div>\n <div style=\"height: 100%; background-color: aliceblue;\"></div> \n <script src=\"https://cdn.jsdelivr.net/npm/typed.js@2.0.12\"></script>\n <script src=\"index.js\"></script>\n</body>\n</html>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551748/" ]
74,505,346
<p>how to know if there is a expiring product? like if you set the expiry date of certain product of 11-25-2022 so by the 11-22-2022 it is considered as expiring product and</p> <p>it will count the row of considered as expiring product.</p> <p>I know my query is wrong because I didn't specify the column field</p> <pre><code>&lt;?php include('../connect.php'); $result = $db-&gt;prepare(&quot;SELECT * FROM rawprod&quot;); $result-&gt;execute(); for($i=0; $row = $result-&gt;fetch(); $i++){ // code... $date = date($row['expiry_date']); $datenew=date_create(&quot;$date&quot;); date_sub($datenew,date_interval_create_from_date_string(&quot;3 days&quot;)); $expiringdate = date_format($datenew, &quot;Y-m-d&quot;); $date = date(&quot;Y-m-d&quot;); $result = $db-&gt;prepare(&quot;SELECT * FROM rawprod where '$date' &gt;= $expiringdate&quot;); $result-&gt;execute(); $rowcountEXP = $result-&gt;rowcount(); } ?&gt; &lt;div style=&quot;text-align:center;&quot;&gt; Expiring Raw Product: &lt;font style=&quot;color:green; font:bold 22px 'Aleo';&quot;&gt;[&lt;?php echo $rowcountEXP; ?&gt;]&lt;/font&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74506913, "author": "rauwitt", "author_id": 5458987, "author_profile": "https://Stackoverflow.com/users/5458987", "pm_score": 2, "selected": true, "text": "<?php\ninclude('../connect.php');\n$today = date('Y-m-d');\n$expiring_products = array();\n$stmt = $db->prepare(\"SELECT `product` FROM `rawprod` WHERE DATE_SUB(`expiry_date`,INTERVAL 3 DAY) <= ?\");\n$stmt->bind_param(\"s\", $today);\n$stmt->execute();\n$stmt -> bind_result($expiring_products);\nforeach ($stmt->get_result() as $row)\n{\n$expiring_products[] = $row['product'];\n}\nmysqli_close($db);\n?>\n<div style=\"text-align:center;\">\nExpiring Raw Product: <font style=\"color:green; font:bold 22px 'Aleo';\">\n<?php \nprint count($expiring_products);\n?>\n</font></div>\n" }, { "answer_id": 74514638, "author": "Toto Deleon", "author_id": 20517886, "author_profile": "https://Stackoverflow.com/users/20517886", "pm_score": 0, "selected": false, "text": "<?php\n include('../connect.php');\n $datetoday = date(\"Y-m-d\");\n $res = $db->prepare(\"SELECT * FROM rawprod WHERE '$datetoday' >= \n DATE_SUB(expiry_date,INTERVAL 3 DAY)\");\n $res->execute();\n $rowcount123 = $res->rowcount();\n?>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20517886/" ]
74,505,365
<pre><code>int peek() { if(top == -1) { printf(&quot;\n \t STACK UNDERFLOW&quot;); return -1; } else { if(x != -1) printf(&quot;\n The top most element is %d&quot;,x); return x[top]; } } </code></pre> <p>My Peek Operation is not printing the correct output. The Output should be the topmost element in an array of stack, it prints random numbers. The Peek operation should print the topmost element in an array of stack inputted by the user.</p> <p>For example:</p> <pre><code>---------------------------------------- ARRAY OF STACK ---------------------------------------- [1] PUSH [2] POP [3] PEEK [4] DISPLAY [5] EXIT ---------------------------------------- Enter you Choice: 1 ---------------------------------------- Enter element to add: Jennie ---------------------------------------- ARRAY OF STACK ---------------------------------------- [1] PUSH [2] POP [3] PEEK [4] DISPLAY [5] EXIT ---------------------------------------- Enter you Choice: 1 ---------------------------------------- Enter element to add: Lisa ---------------------------------------- ARRAY OF STACK ---------------------------------------- [1] PUSH [2] POP [3] PEEK [4] DISPLAY [5] EXIT ---------------------------------------- Enter you Choice: 3 The top most element is 4229504 </code></pre> <p>The output should be &quot;The topmost element is Lisa&quot; How to correct this? I need to print the topmost element in the stack inputted by the user. I also get &quot;Warning comparison between pointer and integer&quot; as a warning in &quot;if(x != -1)&quot; in peek operation.</p>
[ { "answer_id": 74505538, "author": "anna", "author_id": 20121266, "author_profile": "https://Stackoverflow.com/users/20121266", "pm_score": 0, "selected": false, "text": "printf(\"\\n The top most element is: \");\n strcpy(x,a[top]);\n printf(\"%s\",x);\n" }, { "answer_id": 74505559, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 3, "selected": true, "text": "a char *peek() {\n if(top == -1) {\n printf(\"\\n \\t STACK UNDERFLOW\");\n return NULL;\n }\n printf(\"\\n The top most element is %s\", a[top]);\n return a[top];\n}\n \n----------------------------------------\n ARRAY OF STACK \n----------------------------------------\n [1] PUSH\n [2] POP\n [3] PEEK\n [4] DISPLAY\n [5] EXIT\n----------------------------------------\n Enter you Choice: 1\n----------------------------------------\nEnter element to add: test\n\n----------------------------------------\n ARRAY OF STACK \n----------------------------------------\n [1] PUSH\n [2] POP\n [3] PEEK\n [4] DISPLAY\n [5] EXIT\n----------------------------------------\n Enter you Choice: 3\n\n The top most element is test\n x printf() main() char *data = peek(); if(data) top--; return data; scanf()" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20121266/" ]
74,505,392
<p>I am an excel novice, so I hope I am explaining my problem well enough:</p> <p><a href="https://i.stack.imgur.com/Zbrs1.png" rel="nofollow noreferrer">exceltable</a></p> <p>Field A is the District the candidate is running in, Field B is the candidate name, Field C is the percent of the vote the candidate received, and I need Field D to calculate the District winner's name.</p> <p>I am trying to calculate the name of the District winner into Field D until the District changes. I know there is probably a much better way to do what I am trying to do, but here is the formula I have pieced together so far: =IF(A2=&quot;&quot;,A1,A2 (INDEX(B2:B3,0,MATCH(MAX(C2:C3),C2:C3,0))))</p> <p>Any help is appreciated!</p>
[ { "answer_id": 74506087, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": true, "text": "E2 =LET(rng, A2:C19, dists, INDEX(rng,,1), names, INDEX(rng,,2), \n pcts, INDEX(rng,,3),\n distsUx, UNIQUE(dists),\n result, MAP(distsUx, LAMBDA(dist,\n TEXTJOIN(\",\",,FILTER(names, (dists=dist) \n * (pcts = MAX(FILTER(pcts, dists=dist)))))\n )),\n HSTACK(distsUx, result)\n)\n pct" }, { "answer_id": 74506246, "author": "Harun24hr", "author_id": 5514747, "author_profile": "https://Stackoverflow.com/users/5514747", "pm_score": 2, "selected": false, "text": "=CHOOSE({1,2},UNIQUE(A2:A19),BYROW(UNIQUE(A2:A19),LAMBDA(x,INDEX(SORT(FILTER(B2:C19,A2:A19=x),2,-1),1,1))))\n =LET(a,UNIQUE(A2:A19),b,BYROW(a,LAMBDA(x,INDEX(SORT(FILTER(B2:C19,A2:A19=x),2,-1),1,1))),VSTACK({\"Dist\",\"Candidate\"},HSTACK(a,b)))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20551727/" ]
74,505,405
<p>I know that unicode code point for <code>Á</code> is <code>U+00C1</code>. I read on internet and many forums and articles that I can also make an <code>Á</code> by combining characters <code>´</code> (unicode: <code>U+00B4</code>) and <code>A</code> (unicode: <code>U+0041</code>).</p> <p>My question is simple. How to do it? I tried something like this. <strong>I decided to try it in golang, but it's perfectly fine if someone knows how to do it in python (or some other programming language). It doesn't matter to me.</strong></p> <p>Okay, so I tried next.</p> <p><code>A</code> in binary is: <code>01000001</code></p> <p><code>´</code> in binary is: <code>10110100</code></p> <p>It together takes 15 bits, so I need UTF-8 3 bytes format (<code>1110xxxx 10xxxxxx 10xxxxxx</code>)</p> <p>By filling the bits from <code>A</code> and <code>´</code> (first A) in the places of x, the following is obtained: <code>11100100 10000110 10110100</code>.</p> <p>Then I converted the resulting three bytes back into hexadecimal values: <code>E4 86 B4</code>.</p> <p>However, when I tried to write it in code, I got a completely different character. In other words, my solution is not working as I expected.</p> <pre><code>package main import ( &quot;fmt&quot; ) func main() { r := &quot;\xE4\x86\xB4&quot; fmt.Println(r) // It wrote 䆴 instead of Á } </code></pre>
[ { "answer_id": 74505449, "author": "StardustGogeta", "author_id": 5732397, "author_profile": "https://Stackoverflow.com/users/5732397", "pm_score": 3, "selected": true, "text": "´ >>> \"A\\u00b4\"\n'A´'\n ◌́ A >>> \"A\\u0301\"\n'Á'\n" }, { "answer_id": 74505858, "author": "Erwin Bolwidt", "author_id": 981744, "author_profile": "https://Stackoverflow.com/users/981744", "pm_score": 1, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n\n \"golang.org/x/text/unicode/norm\"\n)\n\nfunc main() {\n combined := \"\\u00c1\"\n combining := \"A\\u0301\"\n fmt.Printf(\"combined = %s, combining = %s\\n\", combined, combining)\n fmt.Printf(\"combined == combining: %t\\n\", combined == combining)\n combiningNormalised := string(norm.NFC.Bytes([]byte(combining)))\n fmt.Printf(\"combined == combiningNormalised: %t\\n\", combined == combiningNormalised)\n}\n combined = Á, combining = Á\ncombined == combining: false\ncombined == combiningNormalised: true\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20502562/" ]
74,505,435
<p>After a pile of troubleshooting, I managed to get my gitlab CICD pipeline to connect to GCP without requiring my service account to use a JSON key. However, I'm unable to do anything with Terraform in my pipeline using a remote statefile because of the following error:</p> <pre><code>Error: Failed to get existing workspaces: querying Cloud Storage failed: googleapi: Error 403: Insufficient Permission, insufficientPermissions </code></pre> <p>My gitlab-ci.yml file is defined as follows:</p> <pre><code>stages: - auth - validate gcp-auth: stage: auth image: google/cloud-sdk:slim script: - echo ${CI_JOB_JWT_V2} &gt; .ci_job_jwt_file - gcloud iam workload-identity-pools create-cred-config ${GCP_WORKLOAD_IDENTITY_PROVIDER} --service-account=&quot;${GCP_SERVICE_ACCOUNT}&quot; --output-file=.gcp_temp_cred.json --credential-source-file=.ci_job_jwt_file - gcloud auth login --cred-file=`pwd`/.gcp_temp_cred.json - gcloud auth list tf-stuff: stage: validate image: name: hashicorp/terraform:light entrypoint: - '/usr/bin/env' - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' before_script: - export TF_LOG=DEBUG - cd terraform - rm -rf .terraform - terraform --version - terraform init script: - terraform validate </code></pre> <p>My <code>gcp-auth</code> job is running successfully from what I can see:</p> <pre><code>Authenticated with external account credentials for: [[MASKED]]. </code></pre> <p>I've also went as far as adding in a <code>gsutil cp</code> command inside the <code>gcp-auth</code> job to make sure I can access the desired bucket as expected, which I can. I can successfully edit the contents of the bucket where my terraform statefile is stored.</p> <p>I'm fairly new to gitlab CICD pipelines. Is there something I need to do to have the <code>gcp-auth</code> job tied to the <code>tf-stuff</code> job? It's like that job does not know the pipeline was previously authenticated using the service account.</p> <p>Thanks!</p>
[ { "answer_id": 74507230, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 0, "selected": false, "text": "Gitlab pod Kubernetes tf-stuff gcp-auth Shell Gitlab Shell gcp_authentication.sh echo ${CI_JOB_JWT_V2} > .ci_job_jwt_file\ngcloud iam workload-identity-pools create-cred-config ${GCP_WORKLOAD_IDENTITY_PROVIDER}\n --service-account=\"${GCP_SERVICE_ACCOUNT}\"\n --output-file=.gcp_temp_cred.json\n --credential-source-file=.ci_job_jwt_file\ngcloud auth login --cred-file=`pwd`/.gcp_temp_cred.json\ngcloud auth list\n\n# Check if you need to set GOOGLE_APPLICATION_CREDENTIALS env var on `pwd`/.gcp_temp_cred.json\n tf-stuff Docker gcloud Terraform hashicorp/terraform gcloud cli Docker Gitlab Gitlab yml stages:\n - auth\n - validate\n\ngcp-auth:\n stage: auth\n image: google/cloud-sdk:slim\n script:\n - . ./gcp_authentication.sh\n\ntf-stuff:\n stage: validate\n image:\n name: yourgitlabregistry/your-custom-image:1.0.0\n entrypoint:\n - '/usr/bin/env'\n - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'\n before_script:\n - . ./gcp_authentication.sh\n - export TF_LOG=DEBUG\n - cd terraform\n - rm -rf .terraform\n - terraform --version\n - terraform init\n script:\n - terraform validate\n Shell Gitlab gcp_authentication.sh Docker Terraform gcloud cli Terraform Gitlab Shell GOOGLE_APPLICATION_CREDENTIALS pwd roles/iam.workloadIdentityUser" }, { "answer_id": 74621352, "author": "Anders Elton", "author_id": 8579931, "author_profile": "https://Stackoverflow.com/users/8579931", "pm_score": 3, "selected": true, "text": ".gcp_auth_before: &gcp_auth_before\n - export GOOGLE_APPLICATION_CREDENTIALS=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\n - export CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\n - export GOOGLE_GHA_CREDS_PATH=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\n - export GOOGLE_CLOUD_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export CLOUDSDK_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export CLOUDSDK_CORE_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export GCP_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export GCLOUD_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n\n.gcp-auth:\n artifacts:\n paths:\n - _auth/\n before_script:\n *gcp_auth_before\n\nstages:\n - auth\n - debug\n\nauth:\n stage: auth\n image: \"google/cloud-sdk:slim\"\n variables:\n SERVICE_ACCOUNT_EMAIL: \"... service account email ...\"\n WORKLOAD_IDENTITY_PROVIDER: \"projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL/providers/PROVIDER\"\n GOOGLE_CLOUD_PROJECT: \"... project id ....\"\n artifacts:\n paths:\n - _auth/\n script:\n - |\n mkdir -p _auth \n echo \"$CI_JOB_JWT_V2\" > $CI_PROJECT_DIR/_auth/.ci_job_jwt_file\n echo \"$GOOGLE_CLOUD_PROJECT\" > $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT\n gcloud iam workload-identity-pools create-cred-config \\\n $WORKLOAD_IDENTITY_PROVIDER \\\n --service-account=$SERVICE_ACCOUNT_EMAIL \\\n --service-account-token-lifetime-seconds=600 \\\n --output-file=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json \\\n --credential-source-file=$CI_PROJECT_DIR/_auth/.ci_job_jwt_file\n gcloud config set project $GOOGLE_CLOUD_PROJECT\n - \"export GOOGLE_APPLICATION_CREDENTIALS=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\"\n - \"gcloud auth login --cred-file=$GOOGLE_APPLICATION_CREDENTIALS\"\n - gcloud auth list # DEBUG!!\n\ndebug:\n extends: .gcp-auth\n stage: debug\n image: \"google/cloud-sdk:slim\"\n script:\n - env\n - gcloud auth list\n - gcloud storage ls\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20536016/" ]
74,505,436
<p>Using Snowflake SQL, I need to convert the following transactional data into periodic (month-end) snapshots for time series analysis in Tableau.</p> <p>The data I have is transactional, showing the date they changed departments, and the new department they are in. I need to be able to show 36 months of snapshots (a list of which department each employee was in as of the end of each month). Employees can change departments on any date, and change departments multiple times (and so have multiple records), or not at all (they have a single record).</p> <p>Input (Transactional Data I have):</p> <pre><code>| emp_id | department_code | effective_date | | -------------------------------------------| | 1 | 100 | 7/15/2022 | | 1 | 200 | 10/2/2022 | | 1 | 100 | 11/10/2022 | | 2 | 300 | 8/31/2022 | | 2 | 500 | 10/15/2022 | | 2 | 400 | 10/31/2022 | | 3 | 100 | 1/1/2022 | | 4 | 200 | 5/3/2022 | </code></pre> <p>Desired Output (Format I need to import into Tableau - I need 36 monthly snapshots generated, but using 4 to illustrate the principle):</p> <pre><code>|emp_id | department_code | snapshot_date | | -----------------------------------------| |1 | 100 | 11/30/2022 | |2 | 400 | 11/30/2022 | |3 | 100 | 11/30/2022 | |4 | 200 | 11/30/2022 | |1 | 200 | 10/31/2022 | |2 | 400 | 10/31/2022 | |3 | 100 | 10/31/2022 | |4 | 200 | 10/31/2022 | |1 | 100 | 9/30/2022 | |2 | 300 | 9/30/2022 | |3 | 100 | 9/30/2022 | |4 | 200 | 9/30/2022 | |1 | 100 | 8/31/2022 | |2 | 300 | 8/31/2022 | |3 | 100 | 8/31/2022 | |4 | 200 | 8/31/2022 | </code></pre> <p>I'm able to do one monthly snapshot, or multiple by unioning one together with others, but I am sure there is a better way to write this recursively.</p>
[ { "answer_id": 74507230, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 0, "selected": false, "text": "Gitlab pod Kubernetes tf-stuff gcp-auth Shell Gitlab Shell gcp_authentication.sh echo ${CI_JOB_JWT_V2} > .ci_job_jwt_file\ngcloud iam workload-identity-pools create-cred-config ${GCP_WORKLOAD_IDENTITY_PROVIDER}\n --service-account=\"${GCP_SERVICE_ACCOUNT}\"\n --output-file=.gcp_temp_cred.json\n --credential-source-file=.ci_job_jwt_file\ngcloud auth login --cred-file=`pwd`/.gcp_temp_cred.json\ngcloud auth list\n\n# Check if you need to set GOOGLE_APPLICATION_CREDENTIALS env var on `pwd`/.gcp_temp_cred.json\n tf-stuff Docker gcloud Terraform hashicorp/terraform gcloud cli Docker Gitlab Gitlab yml stages:\n - auth\n - validate\n\ngcp-auth:\n stage: auth\n image: google/cloud-sdk:slim\n script:\n - . ./gcp_authentication.sh\n\ntf-stuff:\n stage: validate\n image:\n name: yourgitlabregistry/your-custom-image:1.0.0\n entrypoint:\n - '/usr/bin/env'\n - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'\n before_script:\n - . ./gcp_authentication.sh\n - export TF_LOG=DEBUG\n - cd terraform\n - rm -rf .terraform\n - terraform --version\n - terraform init\n script:\n - terraform validate\n Shell Gitlab gcp_authentication.sh Docker Terraform gcloud cli Terraform Gitlab Shell GOOGLE_APPLICATION_CREDENTIALS pwd roles/iam.workloadIdentityUser" }, { "answer_id": 74621352, "author": "Anders Elton", "author_id": 8579931, "author_profile": "https://Stackoverflow.com/users/8579931", "pm_score": 3, "selected": true, "text": ".gcp_auth_before: &gcp_auth_before\n - export GOOGLE_APPLICATION_CREDENTIALS=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\n - export CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\n - export GOOGLE_GHA_CREDS_PATH=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\n - export GOOGLE_CLOUD_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export CLOUDSDK_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export CLOUDSDK_CORE_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export GCP_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n - export GCLOUD_PROJECT=$(cat $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT)\n\n.gcp-auth:\n artifacts:\n paths:\n - _auth/\n before_script:\n *gcp_auth_before\n\nstages:\n - auth\n - debug\n\nauth:\n stage: auth\n image: \"google/cloud-sdk:slim\"\n variables:\n SERVICE_ACCOUNT_EMAIL: \"... service account email ...\"\n WORKLOAD_IDENTITY_PROVIDER: \"projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL/providers/PROVIDER\"\n GOOGLE_CLOUD_PROJECT: \"... project id ....\"\n artifacts:\n paths:\n - _auth/\n script:\n - |\n mkdir -p _auth \n echo \"$CI_JOB_JWT_V2\" > $CI_PROJECT_DIR/_auth/.ci_job_jwt_file\n echo \"$GOOGLE_CLOUD_PROJECT\" > $CI_PROJECT_DIR/_auth/.GOOGLE_CLOUD_PROJECT\n gcloud iam workload-identity-pools create-cred-config \\\n $WORKLOAD_IDENTITY_PROVIDER \\\n --service-account=$SERVICE_ACCOUNT_EMAIL \\\n --service-account-token-lifetime-seconds=600 \\\n --output-file=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json \\\n --credential-source-file=$CI_PROJECT_DIR/_auth/.ci_job_jwt_file\n gcloud config set project $GOOGLE_CLOUD_PROJECT\n - \"export GOOGLE_APPLICATION_CREDENTIALS=$CI_PROJECT_DIR/_auth/.gcp_temp_cred.json\"\n - \"gcloud auth login --cred-file=$GOOGLE_APPLICATION_CREDENTIALS\"\n - gcloud auth list # DEBUG!!\n\ndebug:\n extends: .gcp-auth\n stage: debug\n image: \"google/cloud-sdk:slim\"\n script:\n - env\n - gcloud auth list\n - gcloud storage ls\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10259871/" ]
74,505,455
<p>I have a dictionary like this:</p> <pre><code>{1: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], 2: [&quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;]} </code></pre> <p>that I want to turn into a dataframe like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>item</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>a</td> </tr> <tr> <td>1</td> <td>b</td> </tr> <tr> <td>1</td> <td>c</td> </tr> <tr> <td>2</td> <td>d</td> </tr> <tr> <td>2</td> <td>e</td> </tr> <tr> <td>2</td> <td>f</td> </tr> <tr> <td>2</td> <td>g</td> </tr> </tbody> </table> </div> <p>but when I try use <code>pandas.DataFrame.from_dict()</code> I get an error because my arrays aren't the same length. How can I accomplish what I'm trying to do here?</p>
[ { "answer_id": 74505502, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 3, "selected": true, "text": "data = {1: [\"a\", \"b\", \"c\"],\n 2: [\"d\", \"e\", \"f\", \"g\"]}\n pd.Series(data).explode()\n 1 a\n1 b\n1 c\n2 d\n2 e\n2 f\n2 g\ndtype: object\n pd.Series(data).explode().reset_index().set_axis(['id', 'item'], axis=1)\n id item\n0 1 a\n1 1 b\n2 1 c\n3 2 d\n4 2 e\n5 2 f\n6 2 g\n" }, { "answer_id": 74505568, "author": "G.G", "author_id": 20284103, "author_profile": "https://Stackoverflow.com/users/20284103", "pm_score": 0, "selected": false, "text": " pd.concat([pd.DataFrame(v,index=[i]*len(v),columns=['items']) for i,v in map1.items()])\\\n .rename_axis('id').reset_index()\n \n id items\n 0 1 a\n 1 1 b\n 2 1 c\n 3 2 d\n 4 2 e\n 5 2 f\n 6 2 g\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11370167/" ]
74,505,491
<p>I got two json objects that I need to combine together based on ID and do count and sort operations on it.</p> <p>Here is the first object comments:</p> <pre><code> [ { &quot;userId&quot;: 1, &quot;id&quot;: 1, &quot;title&quot;: &quot;sunt aut facere repellat provident occaecati excepturi optio reprehenderit&quot;, &quot;body&quot;: &quot;quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto&quot; }, { &quot;userId&quot;: 1, &quot;id&quot;: 2, &quot;title&quot;: &quot;qui est esse&quot;, &quot;body&quot;: &quot;est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla&quot; }, { &quot;userId&quot;: 1, &quot;id&quot;: 3, &quot;title&quot;: &quot;ea molestias quasi exercitationem repellat qui ipsa sit aut&quot;, &quot;body&quot;: &quot;et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut&quot; }, { &quot;userId&quot;: 1, &quot;id&quot;: 4, &quot;title&quot;: &quot;eum et est occaecati&quot;, &quot;body&quot;: &quot;ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit&quot; }, ] </code></pre> <p>This is second json object:</p> <pre><code>[ { &quot;postId&quot;: 1, &quot;id&quot;: 1, &quot;name&quot;: &quot;id labore ex et quam laborum&quot;, &quot;email&quot;: &quot;Eliseo@gardner.biz&quot;, &quot;body&quot;: &quot;laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium&quot; }, { &quot;postId&quot;: 1, &quot;id&quot;: 2, &quot;name&quot;: &quot;quo vero reiciendis velit similique earum&quot;, &quot;email&quot;: &quot;Jayne_Kuhic@sydney.com&quot;, &quot;body&quot;: &quot;est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et&quot; }, { &quot;postId&quot;: 1, &quot;id&quot;: 3, &quot;name&quot;: &quot;odio adipisci rerum aut animi&quot;, &quot;email&quot;: &quot;Nikita@garfield.biz&quot;, &quot;body&quot;: &quot;quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione&quot; }, { &quot;postId&quot;: 1, &quot;id&quot;: 4, &quot;name&quot;: &quot;alias odio sit&quot;, &quot;email&quot;: &quot;Lew@alysha.tv&quot;, &quot;body&quot;: &quot;non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati&quot; }, { &quot;postId&quot;: 2, &quot;id&quot;: 5, &quot;name&quot;: &quot;et fugit eligendi deleniti quidem qui sint nihil autem&quot;, &quot;email&quot;: &quot;Presley.Mueller@myrl.com&quot;, &quot;body&quot;: &quot;doloribus at sed quis culpa deserunt consectetur qui praesentium\naccusamus fugiat dicta\nvoluptatem rerum ut voluptate autem\nvoluptatem repellendus aspernatur dolorem in&quot; }, { &quot;postId&quot;: 2, &quot;id&quot;: 6, &quot;name&quot;: &quot;repellat consequatur praesentium vel minus molestias voluptatum&quot;, &quot;email&quot;: &quot;Dallas@ole.me&quot;, &quot;body&quot;: &quot;maiores sed dolores similique labore et inventore et\nquasi temporibus esse sunt id et\neos voluptatem aliquam\naliquid ratione corporis molestiae mollitia quia et magnam dolor&quot; }, ] </code></pre> <p>Object one is basically posts with poster details and object two is comments with commenter details.</p> <p>So expected that object one has one to many relationships with second object. For example one post has many comments. This relationship is based on <code>id</code> in object one is <code>postId</code> in object two. The ultimate objective is to <strong>count</strong> and <strong>sort</strong> post by number of comments.</p> <p>I attempt the problem with simple for loops and creating new json object, I managed to combine them together, but I dont know how to count and sort them properly.</p> <p>in the views:</p> <pre><code>for i in posts: if (id==postId): newobj.append(objtwo[i]) count+=1 else: newobj.append(count) count=0 </code></pre> <p>Normally I use django ORM to sort this but I dont have access to the database and model of the table. How to count and sort the new object so it can return list of posts with most comments counts and descend to lower comments counts?</p>
[ { "answer_id": 74505585, "author": "Byted", "author_id": 5032258, "author_profile": "https://Stackoverflow.com/users/5032258", "pm_score": 2, "selected": false, "text": "posts comments defaultdict posts.sort(key=...) key import json\nfrom collections import defaultdict\n\nposts = [ ... ]\ncomments = [ ... ]\n\n# data structure to count the to comments\n# automatically initializes to 0\ncomments_per_post = defaultdict(int)\n# iterate through the comments to increase the count for the posts\nfor comment in comments:\n comments_per_post[comment['postId']] += 1\n\n# add comment count to post\nfor post in posts:\n post['number_of_comments'] = comments_per_post[post['id']]\n\n# sort the posts based on the counts collected\nposts.sort(key=lambda post: post['number_of_comments'], reverse=True)\n\n# print them to verify\n# number of comments per Post will be in the `number_of_comments` key on the post dict.\nprint(json.dumps(posts, indent=2))\n posts sorted_posts = sorted(posts, key=..." }, { "answer_id": 74506262, "author": "cottontail", "author_id": 19123103, "author_profile": "https://Stackoverflow.com/users/19123103", "pm_score": 2, "selected": true, "text": "Counter collections postIds sorted() import json\nfrom collections import Counter\n\n# count the comments\ncounts = Counter([d['postId'] for d in objtwo])\n\n# add the counts to each post\nfor d in objone:\n d[\"number of comments\"] = counts[d['id']]\n\n# sort posts by number of comments in descending order\nobjone.sort(key=lambda x: -x['number of comments'])\n\n# convert to json\njson.dumps(objone, indent=4)\n print(counts)\n# Counter({1: 4, 2: 2})\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18489452/" ]
74,505,500
<p>I am using Node API with RENDER hosting, while I host the backend it works and when I try to connect the front end and send data I get an exception named Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' help me, please</p> <p>note: password is in string and number is an int data type</p> <pre><code>RoundedButton( colour: Colors.lightBlueAccent, title: 'Login', onPressed: () { AuthService().login(number, password).then((val) { if (val.data['success']) { var token = val.data['token']; Fluttertoast.showToast( msg: 'SUCCESS', toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, backgroundColor: Colors.green, textColor: Colors.white, fontSize: 16.0); } }); print('phone: $number &amp;&amp; password:$password'); }, ), </code></pre> <pre><code>class AuthService { Dio dio = Dio(); login(phone, password) async { try { return await dio.post('https://parkit-odj8.onrender.com/signin', data: {&quot;phone&quot;: phone, &quot;password&quot;: password}, options: Options(contentType: Headers.formUrlEncodedContentType)); } on DioError catch (e) { Fluttertoast.showToast( msg: e.response?.data['msg'], toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); } } } </code></pre> <p>This is my code I tried looking up everything and tried changing my data types but still no use</p>
[ { "answer_id": 74505585, "author": "Byted", "author_id": 5032258, "author_profile": "https://Stackoverflow.com/users/5032258", "pm_score": 2, "selected": false, "text": "posts comments defaultdict posts.sort(key=...) key import json\nfrom collections import defaultdict\n\nposts = [ ... ]\ncomments = [ ... ]\n\n# data structure to count the to comments\n# automatically initializes to 0\ncomments_per_post = defaultdict(int)\n# iterate through the comments to increase the count for the posts\nfor comment in comments:\n comments_per_post[comment['postId']] += 1\n\n# add comment count to post\nfor post in posts:\n post['number_of_comments'] = comments_per_post[post['id']]\n\n# sort the posts based on the counts collected\nposts.sort(key=lambda post: post['number_of_comments'], reverse=True)\n\n# print them to verify\n# number of comments per Post will be in the `number_of_comments` key on the post dict.\nprint(json.dumps(posts, indent=2))\n posts sorted_posts = sorted(posts, key=..." }, { "answer_id": 74506262, "author": "cottontail", "author_id": 19123103, "author_profile": "https://Stackoverflow.com/users/19123103", "pm_score": 2, "selected": true, "text": "Counter collections postIds sorted() import json\nfrom collections import Counter\n\n# count the comments\ncounts = Counter([d['postId'] for d in objtwo])\n\n# add the counts to each post\nfor d in objone:\n d[\"number of comments\"] = counts[d['id']]\n\n# sort posts by number of comments in descending order\nobjone.sort(key=lambda x: -x['number of comments'])\n\n# convert to json\njson.dumps(objone, indent=4)\n print(counts)\n# Counter({1: 4, 2: 2})\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17224820/" ]
74,505,505
<p>I'm a beginner at React.Js and I just made the following code in my App.js file:</p> <pre><code>import React, { useState } from 'react'; import {v4 as uuidv4} from &quot;uuid&quot;; import {BrowserRouter as Router, Route, Routes} from &quot;react-router-dom&quot; import &quot;./App.css&quot;; import Tasks_comp from &quot;./components/Tasks&quot;; import AddTask from './components/AddTask'; import Header from './components/Header'; const App = () =&gt; { const [tasks_var, setTasks] = useState([ { id: &quot;1&quot;, title: &quot;study&quot;, completed: false, }, { id: &quot;2&quot;, title: &quot;read&quot;, completed: true, } ]); const handleTaskClick = (taskId) =&gt; { const newTasks = tasks_var.map((cada_task) =&gt;{ if (cada_task.id === taskId){ return {...cada_task, completed: ! cada_task.completed} } else{ return cada_task; }; }); setTasks(newTasks); } const handleRemoveClick = (taskId) =&gt; { const newTasks = tasks_var.filter(function(obj) { return obj.id !== taskId }) //também possível fazer com método splice. pesquisar setTasks(newTasks); } const handleTaskAddition = (taskTitle) =&gt; { const newTasks = [...tasks_var, { //dica abaixo title: taskTitle, id: uuidv4(), //valor aleatório completed: false, }]; // equivalente ao push setTasks(newTasks); } return ( &lt;Router&gt; &lt;div id='my_div' className=&quot;container&quot;&gt; &lt;Header/&gt; &lt;Routes&gt; &lt;Route path='/' element={() =&gt; ( &lt;React.Fragment&gt; &lt;AddTask addTask_atr={handleTaskAddition}/&gt; &lt;Tasks_comp task_rmv_click={handleRemoveClick} tasks_atr={tasks_var} task_arg_click={handleTaskClick}/&gt; &lt;/React.Fragment&gt; )} /&gt; &lt;/Routes&gt; &lt;/div&gt; &lt;/Router&gt; ); } export default App; </code></pre> <p>There is no mistake. But my problem is that the components inside routes are not loading the moment I start the site.</p> <p>The component 'header' is being shown, but 'AddTask' and 'Tasks_comp' are not. Can anybody help me?</p> <p>I'm actually doing a react course, but the teacher is using an older version of react, and I want to learn the newer version.</p> <p>He does not need to use Routes. But nowadays I'm only able to use Route if I'm inside a Routes component, right?</p>
[ { "answer_id": 74505525, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "<BrowserRouter>\n <div id='my_div' className=\"container\">\n <Header/>\n <Routes>\n <Route path='/' element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition}/>\n <Tasks_comp task_rmv_click={handleRemoveClick} tasks_atr={tasks_var} \n task_arg_click={handleTaskClick}/>\n </React.Fragment>\n />\n </Routes>\n </div>\n</BrowserRouter>\n" }, { "answer_id": 74505558, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": true, "text": "Route ()=>{} element path Route <Router>\n <div id=\"my_div\" className=\"container\">\n <Header />\n <Routes>\n <Route\n path=\"/\"\n element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition} />\n <Tasks_comp\n task_rmv_click={handleRemoveClick}\n tasks_atr={tasks_var}\n task_arg_click={handleTaskClick}\n />\n </React.Fragment>\n }\n />\n </Routes>\n </div>\n</Router>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19642451/" ]
74,505,519
<p>I have a text {L U V B A G} that should appear under the image. I need the html and css for it. This is how it looks. <a href="https://i.stack.imgur.com/4NNTR.png" rel="nofollow noreferrer">enter image description here</a></p> <p>{L U V B A G} that should appear under the image.</p>
[ { "answer_id": 74505525, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "<BrowserRouter>\n <div id='my_div' className=\"container\">\n <Header/>\n <Routes>\n <Route path='/' element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition}/>\n <Tasks_comp task_rmv_click={handleRemoveClick} tasks_atr={tasks_var} \n task_arg_click={handleTaskClick}/>\n </React.Fragment>\n />\n </Routes>\n </div>\n</BrowserRouter>\n" }, { "answer_id": 74505558, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": true, "text": "Route ()=>{} element path Route <Router>\n <div id=\"my_div\" className=\"container\">\n <Header />\n <Routes>\n <Route\n path=\"/\"\n element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition} />\n <Tasks_comp\n task_rmv_click={handleRemoveClick}\n tasks_atr={tasks_var}\n task_arg_click={handleTaskClick}\n />\n </React.Fragment>\n }\n />\n </Routes>\n </div>\n</Router>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20526756/" ]
74,505,539
<p>I try to crawl data by bs4. For each page, I want to take all product id's, it's ok when I take data from first page, but starting with page 2 it always show product id's from first page. Here is my code (although I changed page = 5):</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://tiki.vn/lam-sach-da-mat/c11232?sort=top_seller%3Fpage%3D5&amp;page=5') bs = BeautifulSoup(html, 'html.parser') result =bs.find_all(lambda tag: tag.get('class') == ['product-item']) </code></pre> <p>Here is the <a href="https://i.stack.imgur.com/eEclc.png" rel="nofollow noreferrer">result of 5th page in my code</a></p> <p>I want to take product-id of 5th page as <a href="https://i.stack.imgur.com/0nS1Q.png" rel="nofollow noreferrer">this</a></p> <p>I want to get product-id of 5th page but don't understand why my code still show result of first page.</p>
[ { "answer_id": 74505525, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "<BrowserRouter>\n <div id='my_div' className=\"container\">\n <Header/>\n <Routes>\n <Route path='/' element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition}/>\n <Tasks_comp task_rmv_click={handleRemoveClick} tasks_atr={tasks_var} \n task_arg_click={handleTaskClick}/>\n </React.Fragment>\n />\n </Routes>\n </div>\n</BrowserRouter>\n" }, { "answer_id": 74505558, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": true, "text": "Route ()=>{} element path Route <Router>\n <div id=\"my_div\" className=\"container\">\n <Header />\n <Routes>\n <Route\n path=\"/\"\n element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition} />\n <Tasks_comp\n task_rmv_click={handleRemoveClick}\n tasks_atr={tasks_var}\n task_arg_click={handleTaskClick}\n />\n </React.Fragment>\n }\n />\n </Routes>\n </div>\n</Router>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13126111/" ]
74,505,575
<p>I have this coding assignment where I have to use pure pointer notation only. I am pretty much finished with it but I just realized that I used an array. I am not allowed to do so, unless I change it into a pointer somehow. That's where I am slightly stuck.</p> <p>This is my code.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* Function Prototypes */ int main(); void s1(char *random); void s2(char *s2_input, int index); void strfilter(char *random, char *s2_input, char replacement); int main() { for(;;) { int s1_index = 41; char s1_random[s1_index]; s1(s1_random); printf(&quot;\ns1 = &quot;); puts(s1_random); printf(&quot;s2 = &quot;); int s2_index = 21; char s2_input[s2_index]; s2(s2_input, s2_index); if(s2_input[1] == '\0') { printf(&quot;Size too small&quot;); exit(0); } if(s2_input[21] != '\0' ) { printf(&quot;Size too big&quot;); exit(0); } printf(&quot;ch = &quot;); int replacement = getchar(); if(replacement == EOF) break; while(getchar() != '\n'); printf(&quot;\n&quot;); strfilter(s1_random, s2_input, replacement); printf(&quot;\ns1 filtered = &quot;); puts(s1_random); printf(&quot;Do you wish to run again? Yes(Y), No(N) &quot;); int run = getchar(); // or include ctype.h and do: // run == EOF || toupper(run) == 'N' if(run == EOF || run == 'N' || run == 'n') break; while(getchar() != '\n'); } } void s1(char *random) { int limit = 0; char characters; while((characters = (('A' + (rand() % 26))))) /* random generator */ { if(limit == 41) { *(random + 41 - 1) = '\0'; break; } *(random + limit) = characters; limit++; } } void s2(char *s2_input, int index) { char array[21] = &quot;123456789012345678901&quot;; /* populated array to make sure no random memory is made */ char input; int count = 0; int check = 0; while((input = getchar() )) { if(input == '\n') { *(s2_input + count) = '\0'; break; } else if(input &lt; 65 || input &gt; 90) { printf(&quot;invalid input&quot;); exit(0); } *(s2_input + count) = input; count++; } index = count; } void strfilter(char *random, char *s2_input, char replacement) /* replacement function */ { while(*s2_input) { char *temp = random; while(*temp) { if(*temp == *s2_input) *temp = replacement; temp++; } s2_input++; } } </code></pre> <p>My issue is this part I am not sure how to edit this to not include an array, and still have it output the program in the same way.</p> <pre><code> if(s2_input[1] == '\0') { printf(&quot;Size too small&quot;); exit(0); } if(s2_input[21] != '\0' ) { printf(&quot;Size too big&quot;); exit(0); } </code></pre> <p>I tried to take the address of the array at a certain point, and then dereference it with a pointer, however that is still using a array. Which is what I am trying to avoid. Any help would be greatly appreciated!</p>
[ { "answer_id": 74505525, "author": "Ankit", "author_id": 19757319, "author_profile": "https://Stackoverflow.com/users/19757319", "pm_score": 0, "selected": false, "text": "<BrowserRouter>\n <div id='my_div' className=\"container\">\n <Header/>\n <Routes>\n <Route path='/' element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition}/>\n <Tasks_comp task_rmv_click={handleRemoveClick} tasks_atr={tasks_var} \n task_arg_click={handleTaskClick}/>\n </React.Fragment>\n />\n </Routes>\n </div>\n</BrowserRouter>\n" }, { "answer_id": 74505558, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": true, "text": "Route ()=>{} element path Route <Router>\n <div id=\"my_div\" className=\"container\">\n <Header />\n <Routes>\n <Route\n path=\"/\"\n element={\n <React.Fragment>\n <AddTask addTask_atr={handleTaskAddition} />\n <Tasks_comp\n task_rmv_click={handleRemoveClick}\n tasks_atr={tasks_var}\n task_arg_click={handleTaskClick}\n />\n </React.Fragment>\n }\n />\n </Routes>\n </div>\n</Router>\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20544996/" ]
74,505,581
<p>I get the message : 'pygame.Surface' object has no attribute 'update'. But as you can see, i have an update function in the code. wha did i wrong? I looked around but i didn't fina a simular question.</p> <pre><code>class Createparticle: def __init__(self, xx, yy,img): self.x = xx self.y = yy self.img = img self.particlelist = [] self.verzoegerung = 0 self.scale_k = 0.1 self.img = scale(img, self.scale_k) self.alpha = 255 self.alpha_rate = 3 self.alive = True self.vx = 0 self.vy = 4 + random.randint(-10, 10) / 10 self.k = 0.01 * random.random() * random.choice([-1, 1]) def update(self): self.x += self.vx self.vx += self.k self.y -= self.vy self.vy *= 0.99 self.scale_k += 0.005 self.alpha -= self.alpha_rate self.img = scale(self.img, self.scale_k) self.img.set_alpha(self.alpha) self.particlelist = [i for i in self.particlelist if i.alive] self.verzoegerung += 1 if self.verzoegerung % 2 == 0: self.verzoegerung = 0 self.particlelist.append(self.img) for i in self.particlelist: i.update() def draw(self): for i in self.particlelist: screen.blit(self.img, self.img.get_rect(center=(self.x, self.y))) createparticle = Createparticle(500,300,basisbild) while True: screen.fill((0, 0, 0)) createparticle.update() createparticle.draw() pygame.display.update() clock.tick(FPS) </code></pre>
[ { "answer_id": 74506701, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 2, "selected": true, "text": "i.update() i self.particlelist self.particlelist pygame.Surface pygame.Surface method i pygame.Surface pygame.Surface self.particlelist.append(self.img)\n Particle self.particlelist.append(Particle(self.img))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5132064/" ]
74,505,586
<p>is there a way to change the default hover background color of light blue for options for react select <a href="https://www.npmjs.com/package/react-select" rel="nofollow noreferrer">https://www.npmjs.com/package/react-select</a>? Or is it also not possible for the reasons described in this other thread <a href="https://stackoverflow.com/questions/10484053/change-select-list-option-background-colour-on-hover">Change Select List Option background colour on hover</a></p> <p><a href="https://i.stack.imgur.com/KMJ0R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KMJ0R.png" alt="react select options hover" /></a></p> <pre><code> const styles = { control: (base: {}, state: {}) =&gt; ({ ...base, background: &quot;#1b1d25&quot; }), menu: (base: {}) =&gt; ({ ...base, borderRadius: 0, marginTop: 0, background: &quot;#1b1d25&quot;, &quot;&amp;:hover&quot;: { backgroundColor: &quot;red&quot;, }, }), menuList: (base: {}) =&gt; ({ ...base, padding: 0, backgroundColor: &quot;#1b1d25&quot;, &quot;&amp;:hover&quot;: { backgroundColor: &quot;#1b1d25&quot; }, }), }; &lt;Select options={options} value={{ label: currentAnswer, value: currentAnswer }} onChange={(e) =&gt; handleChange(e.value)} styles={styles} theme={(theme) =&gt; ({ ...theme, borderRadius: 0, colors: { ...theme.colors, }, })} /&gt; </code></pre>
[ { "answer_id": 74506701, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 2, "selected": true, "text": "i.update() i self.particlelist self.particlelist pygame.Surface pygame.Surface method i pygame.Surface pygame.Surface self.particlelist.append(self.img)\n Particle self.particlelist.append(Particle(self.img))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3226932/" ]
74,505,592
<p>How do I write a program that will remove all the items that are in between two duplicates in a list and it will also remove the second duplicate.</p> <p>For example, a = [ (0,0) , (1,0) , (2,0) , (3,0) , (1,0) ]<br /> In the list a, we see that (1,0) occurs more than once in the list. Thus I want to remove all the items in between the 2 duplicates and I want to remove the second occurrence of (1,0). Thus, in this example, I want to remove (2,0),(3,0) and the second occurrence of (1,0).<br /> now my list would look like this : a = [(0,0),(1,0)]<br /> I was able to do this however the problem occurs when I have more than 1 duplicates in my list. For example,<br /> b = [ (0,0) , (1,0) , (2,0) , (3,0) , (1,0) , (5,0) , (6,0) , (7,0) , (8,0) , (5,0), (9,0) , (10,0) ]<br /> In this example, we see that that I have 2 items that are duplicates. I have (1,0) and I have (5,0). Thus, I want to remove all the items between (1,0) and the second occurrence of (1,0) including its second occurrence and I want to remove all the items between (5,0) and the second occurrence of (5,0). In the end, my list should look like this :<br /> b = [ (0,0) , (1,0) ,(5,0) , (9,0) ]</p> <p>This is what I have thus far:</p> <pre><code> a = [ (0,0) , (1,0) , (2,0) , (3,0) , (1,0) ] indexes_of_duplicates = [] for i,j in enumerate(a): if a.count(j) &gt; 1 : indexes_of_duplicates.append(i) for k in range(indexes_of_duplicates[0]+1,indexes_of_duplicates[1]+1): a.pop(indexes_of_duplicates[0]+1) print(a) </code></pre> <p>Output : <code>[(0, 0), (1, 0)]</code><br /> as you can see, this code would only work if I have only 1 duplicate in my list, but I have no idea how to do it if I have more than one duplicate.<br /> PS : I can't obtain a list with overlaps like this [(1, 0), (2, 0), (3, 0), (1, 0), (2, 0)]. thus, you can ignore lists of this kind</p>
[ { "answer_id": 74505747, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 3, "selected": true, "text": "index lst = [(0,0), (1,0), (2,0), (3,0), (1,0), (5,0), (6,0), (7,0), (8,0), (5,0), (9,0), (10,0)]\n\noutput = []\n\nwhile lst: # while `lst` is non-empty\n x, *lst = lst # if lst = [1,2,3], for example, now x = 1 and lst = [2,3]\n output.append(x)\n try: # try finding the x in lst\n lst = lst[lst.index(x)+1:] # if found, reduce the lst (i.e., skip the first lst.index(x)+1 elememts\n except ValueError: # if not found\n pass # do nothing\n\nprint(output) # [(0, 0), (1, 0), (5, 0), (9, 0), (10, 0)]\n lst" }, { "answer_id": 74505750, "author": "Bill", "author_id": 1609514, "author_profile": "https://Stackoverflow.com/users/1609514", "pm_score": 0, "selected": false, "text": "from collections import Counter\n\na = [0, 'x', 2, 3, 'x', 4, 'y', 'y', 6]\n\n# Count the number of occurrence of each unique value\ncounts = Counter(a)\n\nremoving = None\nnew_list = []\nfor item in a:\n if removing: \n if item == removing:\n removing = None\n continue\n if counts[item] > 1:\n removing = item\n new_list.append(item)\n\nprint(new_list)\n [0, 'x', 4, 'y', 6]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20194358/" ]
74,505,607
<p>I try to create a table with moving current three month by using subquery for only selecting current 3 months.</p> <p>I have</p> <pre><code>`select * from dataTable where month in (select max(month),max(month)-1,max(month)-2 from month_table);` </code></pre> <p>snowflake returns me this error msg <strong>SQL compilation error: error line 4 at position 26 Invalid argument types for function '=': (NUMBER(6,0), ROW(NUMBER(6,0), NUMBER(7,0), NUMBER(7,0)))</strong></p> <p>not sure what I miss. when I ran a query for that 3 current months by</p> <pre><code>select max(month),max(month)-1,max(month)-2 from month_table </code></pre> <p>it does return three months <a href="https://i.stack.imgur.com/ACv27.png" rel="nofollow noreferrer">enter image description here</a></p> <p>any idea? or any alternative approach for getting data with moving three months is appreciated.</p> <p>thanks</p> <p>btw, subquery works only in one month eg: select xxxx from (select max(month) from xxx) so I am now using a clumsy union for 3 queries select xxx from max(month) union select xxx from max(month)-1 union select xxx from max(month)-2...</p> <p>so any better efficient approach is appreciated.</p>
[ { "answer_id": 74505747, "author": "j1-lee", "author_id": 11450820, "author_profile": "https://Stackoverflow.com/users/11450820", "pm_score": 3, "selected": true, "text": "index lst = [(0,0), (1,0), (2,0), (3,0), (1,0), (5,0), (6,0), (7,0), (8,0), (5,0), (9,0), (10,0)]\n\noutput = []\n\nwhile lst: # while `lst` is non-empty\n x, *lst = lst # if lst = [1,2,3], for example, now x = 1 and lst = [2,3]\n output.append(x)\n try: # try finding the x in lst\n lst = lst[lst.index(x)+1:] # if found, reduce the lst (i.e., skip the first lst.index(x)+1 elememts\n except ValueError: # if not found\n pass # do nothing\n\nprint(output) # [(0, 0), (1, 0), (5, 0), (9, 0), (10, 0)]\n lst" }, { "answer_id": 74505750, "author": "Bill", "author_id": 1609514, "author_profile": "https://Stackoverflow.com/users/1609514", "pm_score": 0, "selected": false, "text": "from collections import Counter\n\na = [0, 'x', 2, 3, 'x', 4, 'y', 'y', 6]\n\n# Count the number of occurrence of each unique value\ncounts = Counter(a)\n\nremoving = None\nnew_list = []\nfor item in a:\n if removing: \n if item == removing:\n removing = None\n continue\n if counts[item] > 1:\n removing = item\n new_list.append(item)\n\nprint(new_list)\n [0, 'x', 4, 'y', 6]\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14356969/" ]
74,505,627
<p>I have a Google sheet which has columns with the same name and there are different values under each column. I want to count the same value that appear under the same column name.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> <th>1</th> <th>2</th> </tr> </thead> <tbody> <tr> <td>R</td> <td>B</td> <td>C</td> <td>R</td> <td>D</td> </tr> <tr> <td>D</td> <td>C</td> <td>R</td> <td>B</td> <td>D</td> </tr> </tbody> </table> </div> <p>For example, I would like to get the number &quot;R&quot; that appear under column &quot;1&quot;, so I would expect a count of 2 for &quot;R&quot; appearing under columns 1.</p> <p>Here is a <a href="https://docs.google.com/spreadsheets/d/1B1E4L8mT9e3eAClfUN3WYtDOjZCWJfFxke-OvKKOLDU/edit?usp=sharing" rel="nofollow noreferrer">link</a> to Google Sheet with actual data.</p> <p>I have tried countif and countifs in Google Sheets, but can't figure out how to get the count right based on column name.</p>
[ { "answer_id": 74506175, "author": "Nabnub", "author_id": 9538684, "author_profile": "https://Stackoverflow.com/users/9538684", "pm_score": 0, "selected": false, "text": "= ARRAYFORMULA(\n query(\n query(\n SPLIT(TRANSPOSE(SPLIT(\n QUERY(\n TRANSPOSE(\n QUERY(\n TRANSPOSE(\n IF(Original!A2:AE18<>\"\",\n \"\"&Original!A1:AE1&\"♥\"&Original!A2:AE18, )\n ),,999^99)\n ),,999^99),\n \"\")),\n \"♥\"),\n \"Select Col1,Col2,count(Col2) group by Col1,Col2\"),\n \"Select max(Col2),Col3 group by Col2,Col3 pivot Col1\")\n)\n" }, { "answer_id": 74506335, "author": "Ping", "author_id": 20288037, "author_profile": "https://Stackoverflow.com/users/20288037", "pm_score": 1, "selected": false, "text": "=LAMBDA(NUMBERS,LETTERS,\n LAMBDA(UNUM,ULET,\n {\n {\"\",TRANSPOSE(UNUM)};\n {ULET,\n MAKEARRAY(COUNTA(ULET),COUNTA(UNUM),LAMBDA(ROW,COL,\n COUNTIF(FILTER(LETTERS,NUMBERS=INDEX(UNUM,COL)),INDEX(ULET,ROW))\n ))\n }\n }\n )(UNIQUE(FLATTEN(NUMBERS)),UNIQUE(FLATTEN(LETTERS)))\n)($A$1:$AE$1,$A$2:$AE$18)\n A1:AE18 UNIQUE() FLATTEN() A1:AE1 UNIQUE() FLATTEN() A2:AE18 LAMBDA() NUMBERS =A1:AE1 LETTERS =A2:AE18 UNUM =UNIQUE(FLATTEN(NUMBERS)) ULET =UNIQUE(FLATTEN(LETTERS)) {} TRANSPOSE(UNUM) ULET MAKEARRAY() MAKEARRAY() ROW COL COUNTA(ULET) COUNTA(UNUM) MAKEARRAY() LAMBDA() CELL CELL ROW COL ULET UNUM CELL ULET UNUM COUNTIF() FILTER()" }, { "answer_id": 74507407, "author": "The God of Biscuits", "author_id": 18645332, "author_profile": "https://Stackoverflow.com/users/18645332", "pm_score": 0, "selected": false, "text": "=arrayformula(query(split(flatten(A1:AE1&\"|\"&A2:AE18),\"|\"),\"select Col2,count(Col2) group by Col2 pivot Col1\"))\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16166428/" ]
74,505,643
<p>Below is my dataframe:</p> <pre><code>df = pd.DataFrame({&quot;ID&quot; : [1, 1, 2, 2, 2, 3, 3], &quot;length&quot; : [0.7, 0.7, 0.8, 0.6, 0.6, 0.9, 0.9], &quot;comment&quot; : [&quot;typed&quot;, &quot;handwritten&quot;, &quot;typed&quot;, &quot;typed&quot;, &quot;handwritten&quot;, &quot;handwritten&quot;, &quot;handwritten&quot;]}) df ID length comment 0 1 0.7 typed 1 1 0.7 handwritten 2 2 0.8 typed 3 2 0.6 typed 4 2 0.6 handwritten 5 3 0.9 handwritten 6 3 0.9 handwritten </code></pre> <p>I want to be able to do the following:</p> <p>For any group of ID, if the length are the same but the comments are different, use the &quot;typed&quot; formula (5 x length) for the calculated length of that group of ID, otherwise use the formula that apply to each comment to get the calculated length. typed = 5 x length, handwritten = 7*length.</p> <p>Required Output will be as below:</p> <pre><code> ID length comment Calculated Length 0 1 0.7 typed 5*length 1 1 0.7 handwritten 5*length 2 2 0.8 typed 5*length 3 2 0.6 typed 5*length 4 2 0.6 handwritten 7*length 5 3 0.9 handwritten 7*length 6 3 0.9 handwritten 7*length </code></pre> <p>Thank you.</p>
[ { "answer_id": 74505678, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": -1, "selected": false, "text": "np.where import numpy as np\ncond1 = df['comment'] == 'typed'\ndf.assign(Calculated_Length=np.where(cond1, df['length'] * 5, df['length'] * 7))\n ID length comment Calculated_Length\n0 1 0.7 typed 3.5\n1 1 0.7 handwritten 4.9\n2 2 0.8 typed 4.0\n3 2 0.6 typed 3.0\n4 2 0.6 handwritten 4.2\n5 3 0.9 handwritten 6.3\n6 3 0.9 handwritten 6.3\n cond1 = df['comment'] == 'typed'\ncond2 = df.groupby('ID')['length'].transform(lambda x: (x.max() == x.min()) & (df.loc[x.index, 'comment'].eq('typed').sum() > 0))\ndf.assign(Caculated_Length=np.where((cond1 | cond2), df['length']*5, df['length']*7))\n ID length comment Caculated_Length\n0 1 0.7 typed 3.5\n1 1 0.7 handwritten 3.5\n2 2 0.8 typed 4.0\n3 2 0.6 typed 3.0\n4 2 0.6 handwritten 4.2\n5 3 0.9 handwritten 6.3\n6 3 0.9 handwritten 6.3\n" }, { "answer_id": 74505763, "author": "skillsmuggler", "author_id": 11523400, "author_profile": "https://Stackoverflow.com/users/11523400", "pm_score": 1, "selected": true, "text": "IDs groupby IDs comment Calculated length np.where >>> grp_ids = df.groupby(\"ID\")[[\"length\", \"comment\"]].nunique()\n>>> grp_ids\n length comment\nID\n1 1 2\n2 2 2\n3 1 1\n>>> idx = grp_ids.index[(grp_ids[\"length\"] == 1) & (grp_ids[\"comment\"] != 1)]\n>>> idx\nInt64Index([1], dtype='int64', name='ID')\n>>> df[\"Calculated length\"] = np.where(\n df[\"ID\"].isin(idx) | (df[\"comment\"] == \"typed\"),\n df[\"length\"] * 5,\n df[\"length\"] * 7\n )\n>>> df\n ID length comment Calculated length\n0 1 0.7 typed 3.5\n1 1 0.7 handwritten 3.5\n2 2 0.8 typed 4.0\n3 2 0.6 typed 3.0\n4 2 0.6 handwritten 4.2\n5 3 0.9 handwritten 6.3\n6 3 0.9 handwritten 6.3\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19702840/" ]
74,505,644
<p>Is PHP able to determine if a Monday or Thursday comes next and what the date ('YYYY-MM-DD') will be if I provide it with a date to start from?</p>
[ { "answer_id": 74505712, "author": "Ron Piggott", "author_id": 3123313, "author_profile": "https://Stackoverflow.com/users/3123313", "pm_score": 2, "selected": false, "text": "$start = new DateTimeImmutable('2023-01-08');\n$monday = $start->modify(\"next monday\");\n$thursday = $start->modify(\"next thursday\");\n diff if if ( ($start->diff($monday)->days < $start->diff($thursday)->days ) ) {\n echo \"monday\";\n} else {\n echo \"thursday\";\n}\n" }, { "answer_id": 74506254, "author": "jspit", "author_id": 7271221, "author_profile": "https://Stackoverflow.com/users/7271221", "pm_score": 2, "selected": true, "text": "$start = new DateTime('2022-11-19');\n$nextMondayOrThursday = Min(\n (clone $start)->modify(\"next monday\"),\n (clone $start)->modify(\"next thursday\")\n);\n\necho $nextMondayOrThursday->format('l, d F Y');\n//Monday, 21 November 2022\n $start = date_create('2022-11-20');\n$next = ['Mon','Thu','Fri'];\n\nwhile(!in_array($start->modify('+1 Day')->format('D'),$next));\n\necho $start->format('l, d F Y');\n '0 0 * * 1,4'\n use Jspit\\Dt;\n\n$cron = '0 0 * * 1,4'; \n$date = Dt::create('2022-11-21')->NextCron($cron);\n//\"2022-11-24 00:00:00.000000\"\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123313/" ]
74,505,645
<p>I am an R user and have recently been learning how to use Python!</p> <p>In R, I normally import CSV files like this:</p> <pre><code>&gt; getwd() [1] &quot;C:/Users/me/OneDrive/Documents&quot; my_file = read.csv(&quot;my_file.csv&quot;) </code></pre> <p>Now, I am trying to learn how to do this in Python.</p> <p>I first tried this code and got the following error:</p> <pre><code>import pandas as pd df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv') File &quot;&lt;ipython-input-17-45a11fa3e8b1&gt;&quot;, line 1 df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv') ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape </code></pre> <p>I then tried this alternate method, but still got an error:</p> <pre><code>df = pandas.read_csv(r&quot;C:\Users\me\OneDrive\Documents\my_file.csv&quot;) --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-20-c0ac0d536b37&gt; in &lt;module&gt; ----&gt; 1 df = pandas.read_csv(r&quot;C:\Users\me\OneDrive\Documents\my_file.csv&quot;) NameError: name 'pandas' is not defined </code></pre> <p>Can someone please show me what I am doing wrong and how to fix this?</p> <p>Thank you!</p> <p>Note: I am using Jupyter Notebooks within Anaconda</p>
[ { "answer_id": 74505671, "author": "vignesh kanakavalli", "author_id": 19092053, "author_profile": "https://Stackoverflow.com/users/19092053", "pm_score": 1, "selected": false, "text": "pandas pip install pandas -U\n \\somealphabet \\\\somealphabet \\ / df = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n" }, { "answer_id": 74512201, "author": "stats_noob", "author_id": 13203841, "author_profile": "https://Stackoverflow.com/users/13203841", "pm_score": 0, "selected": false, "text": "df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,505,648
<p>I want to create a variable called containing a 2D (nested) list of 2 rows and 3 columns literal containing the values like this:</p> <pre><code>3 14 67 13 24 19 </code></pre> <p>the code I have now is sth like this but the outcome doesn't give me the outcome I want:</p> <pre class="lang-py prettyprint-override"><code>for row in range(2): new_list = [] for col in range(3): new_list.append(a_list) print(new_list) </code></pre>
[ { "answer_id": 74505671, "author": "vignesh kanakavalli", "author_id": 19092053, "author_profile": "https://Stackoverflow.com/users/19092053", "pm_score": 1, "selected": false, "text": "pandas pip install pandas -U\n \\somealphabet \\\\somealphabet \\ / df = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n" }, { "answer_id": 74512201, "author": "stats_noob", "author_id": 13203841, "author_profile": "https://Stackoverflow.com/users/13203841", "pm_score": 0, "selected": false, "text": "df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533197/" ]
74,505,654
<p>I am trying to access the array soc+ out the for loop. Outside of the for loop, it gives me only last value. How to access whole soc array out of the for loop?</p> <p>If I used append method it gives follow error &quot; 'numpy.ndarray' object has no attribute 'append' &quot;</p> <p>Thank you.</p> <p>Here is part of my code</p> <pre><code>for k in range(1,len(t)): soc+=i[k]*(t[k]-t[k-1])/3600*1/(cell_capacity) soc = soc.append(k) </code></pre> <p>I tried using append method but it give the error &quot; 'numpy.ndarray' object has no attribute 'append' &quot;</p>
[ { "answer_id": 74505671, "author": "vignesh kanakavalli", "author_id": 19092053, "author_profile": "https://Stackoverflow.com/users/19092053", "pm_score": 1, "selected": false, "text": "pandas pip install pandas -U\n \\somealphabet \\\\somealphabet \\ / df = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n" }, { "answer_id": 74512201, "author": "stats_noob", "author_id": 13203841, "author_profile": "https://Stackoverflow.com/users/13203841", "pm_score": 0, "selected": false, "text": "df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20552109/" ]
74,505,669
<p><img src="https://i.stack.imgur.com/58D8K.png" alt="" /></p> <pre><code>df = pd.read_csv('1410001701eng.csv') df.head() df['date'] = pd.to_datetime(df['Age group']) df['year'] = pd.DatetimeIndex(df['date']).year monthly_year_avg = df.groupby('year')['VALUE'].mean() print(monthly_year_avg) </code></pre> <p>This is my code. Could you please tell me or give me a hint or show me the website has similar questions. I have monthly data from Jan-1978 to November-2022. How can I convert all these monthly data from different age groups to annually by taking average?</p> <p>or do you think I should calculate it one by one is Excel? Cause it only 44 years.</p> <p>Thank you very much! Much appreciated</p> <p>I tried search similar questions in reddit forum and Stack overflow, they all used rsample and get the result.</p> <p>I have monthly data from Jan-1978 to November-2022. How can I convert all these monthly data from different age groups to annually by taking average?</p>
[ { "answer_id": 74505671, "author": "vignesh kanakavalli", "author_id": 19092053, "author_profile": "https://Stackoverflow.com/users/19092053", "pm_score": 1, "selected": false, "text": "pandas pip install pandas -U\n \\somealphabet \\\\somealphabet \\ / df = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n" }, { "answer_id": 74512201, "author": "stats_noob", "author_id": 13203841, "author_profile": "https://Stackoverflow.com/users/13203841", "pm_score": 0, "selected": false, "text": "df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20550604/" ]
74,505,681
<p>I'm creating a recursive function that creates n lines of asterisk. I do not have problems on writing code, but just am wondering why <code>None</code> appears in my output.</p> <p>Here is my code:</p> <pre><code>def recursive_lines(n): for n in range(0,n): print ('*' + ('*'*n)) # Print asterisk print(recursive_lines(5)) # Enter an integer here </code></pre> <p>And this is the result:</p> <pre><code>* ** *** **** ***** None </code></pre> <p>I don't think I used any <code>int(print())</code> kind of statement here.. Then why does this error keep appearing?</p>
[ { "answer_id": 74505671, "author": "vignesh kanakavalli", "author_id": 19092053, "author_profile": "https://Stackoverflow.com/users/19092053", "pm_score": 1, "selected": false, "text": "pandas pip install pandas -U\n \\somealphabet \\\\somealphabet \\ / df = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n" }, { "answer_id": 74512201, "author": "stats_noob", "author_id": 13203841, "author_profile": "https://Stackoverflow.com/users/13203841", "pm_score": 0, "selected": false, "text": "df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16863576/" ]
74,505,696
<p>This is the flat object I'm working with, it has many more results, ~6800. I've been trying to convert it to a nested tree (like the one listed below) for about 13 hours now &amp; I'm truly lost.</p> <pre><code>[ { &quot;make&quot;: &quot;Acura&quot;, &quot;classification&quot;: &quot;Mid SUV&quot;, &quot;segment&quot;: &quot;Competitive Trucks&quot;, &quot;model&quot;: &quot;RDX&quot;, &quot;catalogDetail&quot;: &quot;RDX_SUV_4_Gasoline_2013_Base w/Tech_FWD_3.5_6_105.7_Automatic&quot; }, { &quot;make&quot;: &quot;Acura&quot;, &quot;classification&quot;: &quot;Midsize Car&quot;, &quot;segment&quot;: &quot;Competitive Cars&quot;, &quot;model&quot;: &quot;TSX&quot;, &quot;catalogDetail&quot;: &quot;TSX_Sedan_4_Gasoline_2012_Base w/Tech_FWD_2.4_4_106.4_Automatic&quot; }, { &quot;make&quot;: &quot;Aston Martin&quot;, &quot;classification&quot;: &quot;Compact Car&quot;, &quot;segment&quot;: &quot;Competitive Cars&quot;, &quot;model&quot;: &quot;DB11&quot;, &quot;catalogDetail&quot;: &quot;DB11_Convertible_2_Gasoline_2019_Volante_RWD_4.0_8_110.4_Automatic&quot; } ] </code></pre> <p>What I'm trying to do is build this flat object into a nested structure like this:</p> <pre><code>[ { &quot;make&quot;: [ { &quot;Acura&quot;, &quot;classification&quot;: [{ &quot;Mid SUV&quot;, &quot;segment&quot;: [{ &quot;Competitive Trucks&quot;, &quot;model&quot;: [{ &quot;RDX&quot;, &quot;catalogDetail&quot;: [{ &quot;RDX_SUV_4_Gasoline_2013_Base w/Tech_FWD_3.5_6_105.7_Automatic&quot; }] }] }], &quot;Midsize Car&quot;, &quot;segment&quot;: [{ &quot;Competitive Cars&quot;, &quot;model&quot;: [{ &quot;TSX&quot;, &quot;catalogDetail&quot;: [{ &quot;TSX_Sedan_4_Gasoline_2012_Base w/Tech_FWD_2.4_4_106.4_Automatic&quot; }] }] }] }], } ] }, { &quot;make&quot;: [ { &quot;Aston Martin&quot;, &quot;classification&quot;: [{ &quot;Compact Car&quot;, &quot;segment&quot;: [{ &quot;Competitive Cars&quot;, &quot;model&quot;: [{ &quot;DB11&quot;, &quot;catalogDetail&quot;: [{ &quot;DB11_Convertible_2_Gasoline_2019_Volante_RWD_4.0_8_110.4_Automatic&quot; }] }] }] }] } ] } ] </code></pre> <p>Where the structure falls into a nested structure like: make --&gt; classification --&gt; segment --&gt; model --&gt; catalogdetail. So there would be multiple car makes, ford, Cadillac, etc. Multiple classifications, multiple different segments under each make.</p> <p>This is what I've tried:</p> <pre><code> this._servicesService.getHierarchy().subscribe(data =&gt; { console.log(data) /* this.data = data;*/ /* this.dataStore = data;*/ let distinctSeg = [...new Set(data.map(x =&gt; x.segment))]; let distinctClass = [...new Set(data.map(x =&gt; x.classification))]; let distinctMod = [...new Set(data.map(x =&gt; x.model))]; let distinctCd = [...new Set(data.map(x =&gt; x.catalogDetail))]; const newData = []; data.forEach(e =&gt; { if (newData.length == 0) { newData.push({ make: e.make, segment: e.segment, classification: e.classification, model: [e.model], catalogDetail: [e.catalogDetail] }); } else { let foundIndex = newData.findIndex(fi =&gt; fi.make === e.make, fi =&gt; fi.segment = e.segment); if (foundIndex &gt;= 0) { /* newData[foundIndex].make.push(e.make),*/ /* newData[foundIndex].segment.push(e.segment),*/ /* newData[foundIndex].classification.push(e.classification),*/ newData[foundIndex].model.push(e.model); newData[foundIndex].catalogDetail.push(e.catalogDetail); } else { newData.push({ make: e.make, segment: distinctSeg, classification: distinctClass, model: [e.model], catalogDetail: [e.catalogDetail] }); } } }); console.log(newData); }) </code></pre> <p>This give me distinct values for model, segment and class, (not model or catalogDetail for some reason) but the nested structure isn't there &amp; i'm truly lost on how to proceed. I've looked at a number of examples on here &amp; I really haven't been successful applying any of the previously listed routes. Any insight or tips would be greatly appreciated. I attached a picture to better visualize the final desired output in case I have the wrong syntax. <a href="https://i.stack.imgur.com/izjoc.png" rel="nofollow noreferrer">tree</a></p>
[ { "answer_id": 74505671, "author": "vignesh kanakavalli", "author_id": 19092053, "author_profile": "https://Stackoverflow.com/users/19092053", "pm_score": 1, "selected": false, "text": "pandas pip install pandas -U\n \\somealphabet \\\\somealphabet \\ / df = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n" }, { "answer_id": 74512201, "author": "stats_noob", "author_id": 13203841, "author_profile": "https://Stackoverflow.com/users/13203841", "pm_score": 0, "selected": false, "text": "df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20489309/" ]
74,505,697
<p>When the function is passed with a parameter an error is returned that a is not a function while without parameter it executes and gives output <code>3</code></p> <pre><code>function one(d) { return 1; } function two() { return 2; } function invokeAdd(a, b) { return a() + b(); } console.log(invokeAdd(one(8), two)); </code></pre>
[ { "answer_id": 74505732, "author": "Ramsudharsan Manoharan", "author_id": 8889782, "author_profile": "https://Stackoverflow.com/users/8889782", "pm_score": 0, "selected": false, "text": "function one(d) {\n return 1;\n}\nfunction two() {\n return 2;\n}\nfunction invokeAdd(a, b) {\n return a() + b();\n}\nconsole.log(invokeAdd(() => one(8), two));\n" }, { "answer_id": 74505733, "author": "Mohammed Shahed", "author_id": 19067773, "author_profile": "https://Stackoverflow.com/users/19067773", "pm_score": 0, "selected": false, "text": "function invokeAdd(a, b) {\nreturn a() + b();\n}\n console.log(invokeAdd(()=>one(8), two));\n" }, { "answer_id": 74505735, "author": "MrDiamond", "author_id": 15364728, "author_profile": "https://Stackoverflow.com/users/15364728", "pm_score": 1, "selected": false, "text": "invokeAdd(() => one(8), two))" }, { "answer_id": 74505744, "author": "M. G.", "author_id": 14013535, "author_profile": "https://Stackoverflow.com/users/14013535", "pm_score": 1, "selected": false, "text": "function invokeAdd(param) {\n return param;\n} function invokeAdd(param) {\n return param; \n}\n\nconsole.log(invokeAdd) invokeAdd function invokeAdd(param) {\n return param;\n}\nconsole.log(invokeAdd(\"test\")) return value argument console.log(invokeAdd(one(8), two)); one(8)" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15204422/" ]
74,505,753
<p>I'm developing a chatbot project for college, and in the following code block, the first if is always going as a true value, no matter what. I really need help and don't know what to do, cause this project is due on monday.</p> <pre><code>def registeredClient(): print('Olá, bem-vindo a WE-RJ Telecom!') userInputString = str(input('O que você precisa?\nCaso queira contratar ou trocar de plano escreva “Quero contratar” ou “Quero trocar de plano”.\nCaso esteja com problemas de conexão, escreva &quot;suporte&quot;.\nCaso queira seu boleto, digite &quot;boleto&quot;:\n')) userInputString = userInputString.lower() if 'contratar' or 'trocar plano' or 'aumentar velocidade' or 'mudar plano' or 'velocidade' or 'plano' in userInputString: newPlanOption() elif 'suporte' or 'lenta' or 'internet lenta' or 'internet esta lenta' or 'problema' or 'velocidade' in userInputString: supportOption() elif 'boleto' or 'segunda via' or '2ª via' or 'fatura' in userInputString: billingOption() else: print('Não foi posível entender a sua mensagem, seu atendimento será encerrado.') return False </code></pre>
[ { "answer_id": 74505780, "author": "Arkistarvh Kltzuonstev", "author_id": 5770501, "author_profile": "https://Stackoverflow.com/users/5770501", "pm_score": 0, "selected": false, "text": "(if 'contratar') or ('trocar plano') or ('aumentar velocidade') or ('mudar plano') or ('velocidade') or ('plano' in userInputString): \n True if any(i in userInputString for i in ['contratar', 'trocar plano', 'aumentar velocidade', 'mudar plano', 'velocidade', 'plano']):\n elif def registeredClient():\n print('Olá, bem-vindo a WE-RJ Telecom!')\n\n userInputString = str(input('O que você precisa?\\nCaso queira contratar ou trocar de plano escreva “Quero contratar” ou “Quero trocar de plano”.\\nCaso esteja com problemas de conexão, escreva \"suporte\".\\nCaso queira seu boleto, digite \"boleto\":\\n'))\n\n userInputString = userInputString.lower()\n checkString = lambda l: any(i in userInputString for i in l)\n\n if checkString(['contratar', 'trocar plano', 'aumentar velocidade', 'mudar plano', 'velocidade', 'plano']):\n newPlanOption()\n elif checkString(['suporte', 'lenta', 'internet lenta', 'internet esta lenta', 'problema', 'velocidade']):\n supportOption()\n elif checkString(['boleto', 'segunda via', '2ª via', 'fatura']):\n billingOption()\n else:\n print('Não foi posível entender a sua mensagem, seu atendimento será encerrado.')\n return False\n" }, { "answer_id": 74505788, "author": "M. G.", "author_id": 14013535, "author_profile": "https://Stackoverflow.com/users/14013535", "pm_score": 1, "selected": false, "text": "true def registeredClient():\n print('Olá, bem-vindo a WE-RJ Telecom!')\n\n userInputString = str(input('O que você precisa?\\nCaso queira contratar ou trocar de plano escreva “Quero contratar” ou “Quero trocar de plano”.\\nCaso esteja com problemas de conexão, escreva \"suporte\".\\nCaso queira seu boleto, digite \"boleto\":\\n'))\n\n userInputString = userInputString.lower()\n\n\n if any(x in userInputString for x in ['contratar', 'trocar plano' , 'aumentar velocidade' , 'mudar plano' , 'velocidade' , 'plano']):\n print(\"Case A\")\n elif any(x in userInputString for x in ['suporte', 'lenta' , 'internet lenta' , 'internet esta lenta' , 'problema' , 'velocidade']):\n print(\"Case B\")\n elif any(x in userInputString for x in ['boleto' , 'segunda via' , '2ª via' , 'fatura']):\n print(\"Case C\")\n else:\n print('Não foi posível entender a sua mensagem, seu atendimento será encerrado.')\n return False\n \nregisteredClient();" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15206222/" ]
74,505,791
<p>I have a JObject that I am trying to add fields to in a way like this:</p> <pre class="lang-cs prettyprint-override"><code>JObject dataObject = new JObject(); dataObject[currentSection][key] = val; </code></pre> <p><code>currentSection</code>, <code>key</code> and <code>val</code> are all strings, I want it so when its all serialized at the end that it looks something like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;currentSection&quot;: { &quot;key&quot;: &quot;value&quot; } } </code></pre> <p>How would I go about doing this?</p>
[ { "answer_id": 74505780, "author": "Arkistarvh Kltzuonstev", "author_id": 5770501, "author_profile": "https://Stackoverflow.com/users/5770501", "pm_score": 0, "selected": false, "text": "(if 'contratar') or ('trocar plano') or ('aumentar velocidade') or ('mudar plano') or ('velocidade') or ('plano' in userInputString): \n True if any(i in userInputString for i in ['contratar', 'trocar plano', 'aumentar velocidade', 'mudar plano', 'velocidade', 'plano']):\n elif def registeredClient():\n print('Olá, bem-vindo a WE-RJ Telecom!')\n\n userInputString = str(input('O que você precisa?\\nCaso queira contratar ou trocar de plano escreva “Quero contratar” ou “Quero trocar de plano”.\\nCaso esteja com problemas de conexão, escreva \"suporte\".\\nCaso queira seu boleto, digite \"boleto\":\\n'))\n\n userInputString = userInputString.lower()\n checkString = lambda l: any(i in userInputString for i in l)\n\n if checkString(['contratar', 'trocar plano', 'aumentar velocidade', 'mudar plano', 'velocidade', 'plano']):\n newPlanOption()\n elif checkString(['suporte', 'lenta', 'internet lenta', 'internet esta lenta', 'problema', 'velocidade']):\n supportOption()\n elif checkString(['boleto', 'segunda via', '2ª via', 'fatura']):\n billingOption()\n else:\n print('Não foi posível entender a sua mensagem, seu atendimento será encerrado.')\n return False\n" }, { "answer_id": 74505788, "author": "M. G.", "author_id": 14013535, "author_profile": "https://Stackoverflow.com/users/14013535", "pm_score": 1, "selected": false, "text": "true def registeredClient():\n print('Olá, bem-vindo a WE-RJ Telecom!')\n\n userInputString = str(input('O que você precisa?\\nCaso queira contratar ou trocar de plano escreva “Quero contratar” ou “Quero trocar de plano”.\\nCaso esteja com problemas de conexão, escreva \"suporte\".\\nCaso queira seu boleto, digite \"boleto\":\\n'))\n\n userInputString = userInputString.lower()\n\n\n if any(x in userInputString for x in ['contratar', 'trocar plano' , 'aumentar velocidade' , 'mudar plano' , 'velocidade' , 'plano']):\n print(\"Case A\")\n elif any(x in userInputString for x in ['suporte', 'lenta' , 'internet lenta' , 'internet esta lenta' , 'problema' , 'velocidade']):\n print(\"Case B\")\n elif any(x in userInputString for x in ['boleto' , 'segunda via' , '2ª via' , 'fatura']):\n print(\"Case C\")\n else:\n print('Não foi posível entender a sua mensagem, seu atendimento será encerrado.')\n return False\n \nregisteredClient();" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708473/" ]
74,505,797
<p>I would like to set the attributes of one triple nested list to the attributes of another triple nested list.</p> <p>Here is a triple nested list:</p> <pre><code>list.A &lt;- list(a = c(1,2,5,6), b = c(2,4,6,5), c = c(2,4,2,5)) list.B &lt;- list(a = c(7,7,7,7), b = c(8,8,8,8), c = c(9,9,9,9)) weights &lt;- list(list.A, list.B) names(weights) &lt;- c(&quot;list.A&quot;, &quot;list.B&quot;) list.A &lt;- list(a = c(2,2,2,2), b = c(3,3,3,3), c = c(4,4,4,4)) list.B &lt;- list(a = c(5,5,5,5), b = c(6,6,6,6), c = c(7,7,7,7)) scores &lt;- list(list.A, list.B) names(scores) &lt;- c(&quot;list.A&quot;, &quot;list.B&quot;) megalist &lt;- list(weights, scores) names(megalist) &lt;- c(&quot;weights&quot;, &quot;scores&quot;) megalist &gt; megalist $weights $weights$list.A $weights$list.A$a [1] 1 2 5 6 $weights$list.A$b [1] 2 4 6 5 $weights$list.A$c [1] 2 4 2 5 $weights$list.B $weights$list.B$a [1] 7 7 7 7 $weights$list.B$b [1] 8 8 8 8 $weights$list.B$c [1] 9 9 9 9 $scores $scores$list.A $scores$list.A$a [1] 2 2 2 2 $scores$list.A$b [1] 3 3 3 3 $scores$list.A$c [1] 4 4 4 4 $scores$list.B $scores$list.B$a [1] 5 5 5 5 $scores$list.B$b [1] 6 6 6 6 $scores$list.B$c [1] 7 7 7 7 </code></pre> <p>Here are the attributes for <code>megalist[[&quot;weights&quot;]]$list.A</code>, and they are the same for <code>megalist[[&quot;scores&quot;]]$list.A</code>.</p> <pre><code>attributes(megalist[[&quot;weights&quot;]]$list.A) $names [1] &quot;a&quot; &quot;b&quot; &quot;c&quot; </code></pre> <p>Here is the triple nested list <code>microlist</code> whose attributes of <code>list.A</code> I want to assign to <code>megalist</code> <code>list.A</code>:</p> <pre><code>list.A &lt;- list(a = c(3,3,3,3), b = c(4,4,4,4), c = c(5,5,5,5)) list.B &lt;- list(a = c(1,1,1,1), b = c(2,2,2,2), c = c(8,8,8,8)) weights &lt;- list(list.A, list.B) names(weights) &lt;- c(&quot;list.A&quot;, &quot;list.B&quot;) list.A &lt;- list(a = c(9,9,9,9), b = c(7,7,7,7), c = c(2,2,2,2)) list.B &lt;- list(a = c(4,4,4,4), b = c(2,2,2,2), c = c(6,6,6,6)) scores &lt;- list(list.A, list.B) names(scores) &lt;- c(&quot;list.A&quot;, &quot;list.B&quot;) microlist &lt;- list(weights, scores) names(microlist) &lt;- c(&quot;weights&quot;, &quot;scores&quot;) microlist &gt; microlist $weights $weights$list.A $weights$list.A$a [1] 3 3 3 3 $weights$list.A$b [1] 4 4 4 4 $weights$list.A$c [1] 5 5 5 5 $weights$list.B $weights$list.B$a [1] 1 1 1 1 $weights$list.B$b [1] 2 2 2 2 $weights$list.B$c [1] 8 8 8 8 $scores $scores$list.A $scores$list.A$a [1] 9 9 9 9 $scores$list.A$b [1] 7 7 7 7 $scores$list.A$c [1] 2 2 2 2 $scores$list.B $scores$list.B$a [1] 4 4 4 4 $scores$list.B$b [1] 2 2 2 2 $scores$list.B$c [1] 6 6 6 6 </code></pre> <p>Here are the attributes of <code>microlist</code> <code>list.A</code> that I want to set for <code>megalist</code> <code>list.A</code>:</p> <pre><code>attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;class&quot;] &lt;- &quot;nb&quot; attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;class&quot;] &lt;- &quot;nb&quot; attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;region.id&quot;] &lt;- list(c(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;)) attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;region.id&quot;] &lt;- list(c(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;)) attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;call&quot;] &lt;- &quot;dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * lowlim)&quot; attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;call&quot;] &lt;- &quot;dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * lowlim)&quot; attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;dnn&quot;] &lt;- list(c(0.0000, 137.4062)) attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;dnn&quot;] &lt;- list(c(0.0000, 137.4062)) attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;bounds&quot;] &lt;- list(c(&quot;GE&quot;,&quot;LE&quot;)) attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;bounds&quot;] &lt;- list(c(&quot;GE&quot;,&quot;LE&quot;)) attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;nbtype&quot;] &lt;- &quot;distance&quot; attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;nbtype&quot;] &lt;- &quot;distance&quot; attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;sym&quot;] &lt;- TRUE attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;sym&quot;] &lt;- TRUE attributes(microlist[[&quot;weights&quot;]]$list.A)[&quot;names&quot;] &lt;- list(c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;)) attributes(microlist[[&quot;scores&quot;]]$list.A)[&quot;names&quot;] &lt;- list(c(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;)) attributes(microlist[[&quot;weights&quot;]]$list.A) attributes(microlist[[&quot;scores&quot;]]$list.A) ##the attributes for weights and scores list.A are the same &gt; attributes(microlist[[&quot;scores&quot;]]$list.A) $names [1] &quot;a&quot; &quot;b&quot; &quot;c&quot; $class [1] &quot;nb&quot; $region.id [1] &quot;1&quot; &quot;2&quot; &quot;3&quot; $call [1] &quot;dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \n lowlim)&quot; $dnn [1] 0.0000 137.4062 $bounds [1] &quot;GE&quot; &quot;LE&quot; $nbtype [1] &quot;distance&quot; $sym [1] TRUE </code></pre> <p>I have tried this:</p> <pre><code>megalist.attrib &lt;- lapply(megalist, function(x, new) { attributes(x[[&quot;list.A&quot;]]) &lt;- new x }, new = lapply(microlist, function(y) { attributes(y[[&quot;list.A&quot;]]) y})) </code></pre> <p>but it returns a summary of the attributes for each nested list rather than the same attributes as <code>microlist</code> <code>list.A</code>:</p> <pre><code>&gt; attributes(megalist.attrib[[&quot;weights&quot;]]$list.A) $weights Characteristics of weights list object: Neighbour list object: Number of regions: 3 Number of nonzero links: 2 Percentage nonzero weights: 66 Average number of links: 1 $scores Characteristics of scores list object: Neighbour list object: Number of regions: 3 Number of nonzero links: 1 Percentage nonzero weights: 33 Average number of links: 1 </code></pre> <p>In my real problem, the attribute types and values change across lists so I am hoping to find a way that is less about hard coding the text and more about changing the attributes of <code>megalist</code> to be those of <code>microlist</code>, so above is just an example.</p>
[ { "answer_id": 74506522, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 0, "selected": false, "text": "mapply(\\(x, y) {\n attributes(x[[\"list.A\"]]) <- attributes(y[[\"list.A\"]])\n x\n}, megalist, microlist)\n" }, { "answer_id": 74551589, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 2, "selected": true, "text": "for for (i in seq_along(microlist)) {\n attributes(megalist[[i]]$list.A) <- attributes(microlist[[i]]$list.A)\n}\n purrr::map2() library(purrr)\n\nmegalist <- map2(megalist, microlist, ~ { \n attributes(.x$list.A) <- attributes(.y$list.A) \n .x\n})\n #> megalist\n$weights\n$weights$list.A\n$a\n[1] 1 2 5 6\n\n$b\n[1] 2 4 6 5\n\n$c\n[1] 2 4 2 5\n\nattr(,\"class\")\n[1] \"nb\"\nattr(,\"region.id\")\n[1] \"1\" \"2\" \"3\"\nattr(,\"call\")\n[1] \"dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \\n lowlim)\"\nattr(,\"dnn\")\n[1] 0.0000 137.4062\nattr(,\"bounds\")\n[1] \"GE\" \"LE\"\nattr(,\"nbtype\")\n[1] \"distance\"\nattr(,\"sym\")\n[1] TRUE\n\n$weights$list.B\n$weights$list.B$a\n[1] 7 7 7 7\n\n$weights$list.B$b\n[1] 8 8 8 8\n\n$weights$list.B$c\n[1] 9 9 9 9\n\n\n\n$scores\n$scores$list.A\n$a\n[1] 2 2 2 2\n\n$b\n[1] 3 3 3 3\n\n$c\n[1] 4 4 4 4\n\nattr(,\"class\")\n[1] \"nb\"\nattr(,\"region.id\")\n[1] \"1\" \"2\" \"3\"\nattr(,\"call\")\n[1] \"dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \\n lowlim)\"\nattr(,\"dnn\")\n[1] 0.0000 137.4062\nattr(,\"bounds\")\n[1] \"GE\" \"LE\"\nattr(,\"nbtype\")\n[1] \"distance\"\nattr(,\"sym\")\n[1] TRUE\n\n$scores$list.B\n$scores$list.B$a\n[1] 5 5 5 5\n\n$scores$list.B$b\n[1] 6 6 6 6\n\n$scores$list.B$c\n[1] 7 7 7 7\n" }, { "answer_id": 74575423, "author": "moodymudskipper", "author_id": 2270475, "author_profile": "https://Stackoverflow.com/users/2270475", "pm_score": 1, "selected": false, "text": "modifyList(microlist, megalist) microlist <- list(\n weights = list(\n list.A = list(a = c(3, 3, 3, 3), b = c(4, 4, 4, 4), c = c(5, 5, 5, 5)) |>\n structure(\n class = \"nb\",\n region.id = c(\"1\", \"2\", \"3\"),\n call = \"dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \\n lowlim)\",\n dnn = c(0, 137.4062),\n bounds = c(\"GE\", \"LE\"),\n nbtype = \"distance\",\n sym = TRUE\n ),\n list.B = list(a = c(1, 1, 1, 1), b = c(2, 2, 2, 2), c = c(8, 8, 8, 8))\n ),\n scores = list(\n list.A = list(a = c(9, 9, 9, 9), b = c(7, 7, 7, 7), c = c(2, 2, 2, 2)) |>\n structure(\n class = \"nb\",\n region.id = c(\"1\", \"2\", \"3\"),\n call = \"dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \\n lowlim)\",\n dnn = c(0, 137.4062),\n bounds = c(\"GE\", \"LE\"),\n nbtype = \"distance\",\n sym = TRUE\n ),\n list.B = list(a = c(4, 4, 4, 4), b = c(2, 2, 2, 2), c = c(6, 6, 6, 6))\n )\n)\n\nmegalist <- list(\n weights = list(\n list.A = list(a = c(1, 2, 5, 6), b = c(2, 4, 6, 5), c = c(2, 4, 2, 5)),\n list.B = list(a = c(7, 7, 7, 7), b = c(8, 8, 8, 8), c = c(9, 9, 9, 9))\n ),\n scores = list(\n list.A = list(a = c(2, 2, 2, 2), b = c(3, 3, 3, 3), c = c(4, 4, 4, 4)),\n list.B = list(a = c(5, 5, 5, 5), b = c(6, 6, 6, 6), c = c(7, 7, 7, 7))\n )\n)\n\nwish <- list(\n weights = list(\n list.A = list(a = c(1, 2, 5, 6), b = c(2, 4, 6, 5), c = c(2, 4, 2, 5)) |>\n structure(\n class = \"nb\",\n region.id = c(\"1\", \"2\", \"3\"),\n call = \"dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \\n lowlim)\",\n dnn = c(0, 137.4062),\n bounds = c(\"GE\", \"LE\"),\n nbtype = \"distance\",\n sym = TRUE\n ),\n list.B = list(a = c(7, 7, 7, 7), b = c(8, 8, 8, 8), c = c(9, 9, 9, 9))\n ),\n scores = list(\n list.A = list(a = c(2, 2, 2, 2), b = c(3, 3, 3, 3), c = c(4, 4, 4, 4)) |>\n structure(\n class = \"nb\",\n region.id = c(\"1\", \"2\", \"3\"),\n call = \"dnearneigh(x = coord.mat, d1 = 0, d2 = (1 + sqrt(.Machine$double.eps)) * \\n lowlim)\",\n dnn = c(0, 137.4062),\n bounds = c(\"GE\", \"LE\"),\n nbtype = \"distance\",\n sym = TRUE\n ),\n list.B = list(a = c(5, 5, 5, 5), b = c(6, 6, 6, 6), c = c(7, 7, 7, 7))\n )\n)\n\n\nnew_mega_list <- modifyList(microlist, megalist)\n\nidentical(new_mega_list, wish)\n#> [1] TRUE\n sessioninfo::session_info()\n#> ─ Session info ────────────────────────────────────────────────────\n#> setting value\n#> version R version 4.2.1 (2022-06-23)\n#> os macOS Monterey 12.0.1\n#> system aarch64, darwin20\n#> ui X11\n#> language (EN)\n#> collate en_US.UTF-8\n#> ctype en_US.UTF-8\n#> tz Europe/Zurich\n#> date 2022-11-30\n#> ───────────────────────────────────────────────────────────────────\n" }, { "answer_id": 74586085, "author": "thus__", "author_id": 5880757, "author_profile": "https://Stackoverflow.com/users/5880757", "pm_score": 0, "selected": false, "text": "listw {spdep} library(spdep)\n#> Loading required package: sp\n#> Loading required package: spData\n#> To access larger datasets in this package, install the spDataLarge\n#> package with: `install.packages('spDataLarge',\n#> repos='https://nowosad.github.io/drat/', type='source')`\n#> Loading required package: sf\n#> Linking to GEOS 3.9.1, GDAL 3.2.3, PROJ 7.2.1; sf_use_s2() is TRUE\n\ncolumbus <- st_read(\n system.file(\"shapes/columbus.shp\", package=\"spData\")[1],\n quiet=TRUE\n)\n\n\nnb1 <- poly2nb(columbus)\nnb2 <- knn2nb(knearneigh(st_centroid(columbus), k = 3))\n#> Warning in st_centroid.sf(columbus): st_centroid assumes attributes are constant\n#> over geometries of x\n\n\n# If you want to overwrite attributes to be exactly that from the other list\nattributes(nb1) <- attributes(nb2)\n\nidentical(attributes(nb1), attributes(nb2))\n#> [1] TRUE\n\nattributes(nb1)\n#> $region.id\n#> [1] \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\" \"9\" \"10\" \"11\" \"12\" \"13\" \"14\" \"15\"\n#> [16] \"16\" \"17\" \"18\" \"19\" \"20\" \"21\" \"22\" \"23\" \"24\" \"25\" \"26\" \"27\" \"28\" \"29\" \"30\"\n#> [31] \"31\" \"32\" \"33\" \"34\" \"35\" \"36\" \"37\" \"38\" \"39\" \"40\" \"41\" \"42\" \"43\" \"44\" \"45\"\n#> [46] \"46\" \"47\" \"48\" \"49\"\n#> \n#> $call\n#> knearneigh(x = st_centroid(columbus), k = 3)\n#> \n#> $sym\n#> [1] FALSE\n#> \n#> $type\n#> [1] \"knn\"\n#> \n#> $`knn-k`\n#> [1] 3\n#> \n#> $class\n#> [1] \"nb\"\nattributes(nb2)\n#> $region.id\n#> [1] \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\" \"9\" \"10\" \"11\" \"12\" \"13\" \"14\" \"15\"\n#> [16] \"16\" \"17\" \"18\" \"19\" \"20\" \"21\" \"22\" \"23\" \"24\" \"25\" \"26\" \"27\" \"28\" \"29\" \"30\"\n#> [31] \"31\" \"32\" \"33\" \"34\" \"35\" \"36\" \"37\" \"38\" \"39\" \"40\" \"41\" \"42\" \"43\" \"44\" \"45\"\n#> [46] \"46\" \"47\" \"48\" \"49\"\n#> \n#> $call\n#> knearneigh(x = st_centroid(columbus), k = 3)\n#> \n#> $sym\n#> [1] FALSE\n#> \n#> $type\n#> [1] \"knn\"\n#> \n#> $`knn-k`\n#> [1] 3\n#> \n#> $class\n#> [1] \"nb\"\n\n# If you want all of nb1 attributes AND nb2 attributes\n# where you overwrite matches from nb1 and nb2 with values from nb2\nnb1 <- poly2nb(columbus)\n\nnb2_attr_names <- names(attributes(nb2))\n\nattributes(nb1)[nb2_attr_names] <- attributes(nb2)\n\nattributes(nb1)\n#> $class\n#> [1] \"nb\"\n#> \n#> $region.id\n#> [1] \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\" \"9\" \"10\" \"11\" \"12\" \"13\" \"14\" \"15\"\n#> [16] \"16\" \"17\" \"18\" \"19\" \"20\" \"21\" \"22\" \"23\" \"24\" \"25\" \"26\" \"27\" \"28\" \"29\" \"30\"\n#> [31] \"31\" \"32\" \"33\" \"34\" \"35\" \"36\" \"37\" \"38\" \"39\" \"40\" \"41\" \"42\" \"43\" \"44\" \"45\"\n#> [46] \"46\" \"47\" \"48\" \"49\"\n#> \n#> $call\n#> knearneigh(x = st_centroid(columbus), k = 3)\n#> \n#> $type\n#> [1] \"knn\"\n#> \n#> $sym\n#> [1] FALSE\n#> \n#> $`knn-k`\n#> [1] 3\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14538020/" ]
74,505,813
<p>I came across this solution on Leetcode for group anagrams that doesn't use sorting. I have two questions for this solution. 1. What are we trying to do in the step where we convert sArr to string in this line - <code>String test = Arrays.toString(sArr);</code>I debugged and see the test string is an array of ints with value 1 for each occurence of alphabet in my input string. For eg, if my input string is eat, test prints - <code>[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]</code>, which makes sense. But we are further also checking if this exists as a key in the map. It's really hard to follow this code. 2. What's the time complexity? Is it O(m*n) - n being the length of each string in the inner for loop?</p> <pre><code>public List&lt;List&lt;String&gt;&gt; groupAnagrams(String[] strs) { List&lt;List&lt;String&gt;&gt; output = new ArrayList(); if(strs == null) { return output; } Map&lt;String,List&lt;String&gt;&gt; outputMap = new HashMap(); for(String str : strs) { int[] input = new int[26]; for(int i = 0; i &lt; str.length(); i++) { input[str.charAt(i) - 'a']++; } String inputStr = Arrays.toString(input); if(outputMap.containsKey(inputStr)) { outputMap.get(inputStr).add(str); } else { List&lt;String&gt; outputLst = new ArrayList(); outputLst.add(str); outputMap.put(inputStr, outputLst); } } output.addAll(outputMap.values()); return output; } </code></pre>
[ { "answer_id": 74505868, "author": "Jacob Malland", "author_id": 17160379, "author_profile": "https://Stackoverflow.com/users/17160379", "pm_score": 0, "selected": false, "text": "What are we trying to do in the step where we convert sArr to string in this line - String test = Arrays.toString(sArr); input inputStr input Arrays.toString(input) \"abc\" [1, 1, 1,...] \"abc\", \"cba\", \"cab\", \"bca\", \"bac\" What's the time complexity?" }, { "answer_id": 74505920, "author": "kuriboh", "author_id": 14485623, "author_profile": "https://Stackoverflow.com/users/14485623", "pm_score": 1, "selected": false, "text": "Arrays.toString() OutputMap OutputMap" }, { "answer_id": 74505940, "author": "aatwork", "author_id": 14263933, "author_profile": "https://Stackoverflow.com/users/14263933", "pm_score": 3, "selected": true, "text": "Map<String,List<String>> outputMap = new HashMap();\n loop: (m * n)\nmap.containsKey() m times: m * O(1) = m\nlist.add() m times: m * O(1) = m\nmap.put() m times: m * O(1) = m\n\n(m * n ) + m + m + m = (m * n) + 3m = m (n + 3)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2624866/" ]
74,505,822
<p>Difference between package and plugin? Easy and Basic??</p> <p>Easy Answer which we can say in the interview . If someone ask!</p>
[ { "answer_id": 74505868, "author": "Jacob Malland", "author_id": 17160379, "author_profile": "https://Stackoverflow.com/users/17160379", "pm_score": 0, "selected": false, "text": "What are we trying to do in the step where we convert sArr to string in this line - String test = Arrays.toString(sArr); input inputStr input Arrays.toString(input) \"abc\" [1, 1, 1,...] \"abc\", \"cba\", \"cab\", \"bca\", \"bac\" What's the time complexity?" }, { "answer_id": 74505920, "author": "kuriboh", "author_id": 14485623, "author_profile": "https://Stackoverflow.com/users/14485623", "pm_score": 1, "selected": false, "text": "Arrays.toString() OutputMap OutputMap" }, { "answer_id": 74505940, "author": "aatwork", "author_id": 14263933, "author_profile": "https://Stackoverflow.com/users/14263933", "pm_score": 3, "selected": true, "text": "Map<String,List<String>> outputMap = new HashMap();\n loop: (m * n)\nmap.containsKey() m times: m * O(1) = m\nlist.add() m times: m * O(1) = m\nmap.put() m times: m * O(1) = m\n\n(m * n ) + m + m + m = (m * n) + 3m = m (n + 3)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16470351/" ]
74,505,823
<p><a href="https://i.stack.imgur.com/kNzNH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kNzNH.png" alt="enter image description here" /></a></p> <p>Is there a way to implement this kind of horizontal Month selector in flutter? For This I need to show the month and year and when clicked on the buttons on the side to go to the next month and when clicked on the Month to open a calendar.</p>
[ { "answer_id": 74506138, "author": "Sayyid J", "author_id": 15366030, "author_profile": "https://Stackoverflow.com/users/15366030", "pm_score": 0, "selected": false, "text": "import 'package:flutter/material.dart';\n\ntypedef OnHorizontalDatePickerSelected = void Function(DateTime dateTime);\ntypedef OnHorizontalDatePickerSubmitted = void Function(DateTime dateTime);\nclass HorizontalDatePicker extends StatefulWidget {\n final DateTime? initial;\n final OnHorizontalDatePickerSelected onSelected;\n final OnHorizontalDatePickerSubmitted? onSubmitted;\n const HorizontalDatePicker({Key? key, this.initial, required this.onSelected, this.onSubmitted}) : super(key: key);\n\n @override\n State<HorizontalDatePicker> createState() => _HorizontalDatePickerState();\n}\n\nclass _HorizontalDatePickerState extends State<HorizontalDatePicker> {\n static const Map<int, String> _monthList =\n {DateTime.january: 'Jan',\n DateTime.february: 'Feb',\n DateTime.march: 'Mar',\n DateTime.april: 'Apr',\n DateTime.may: 'May',\n DateTime.june: 'Jun',\n DateTime.july: 'Jul',\n DateTime.august: 'Aug',\n DateTime.september: 'Sep',\n DateTime.october: 'Okt',\n DateTime.november: 'Nov',\n DateTime.december: 'Des'};\n\n\n late DateTime _current;\n\n @override\n void initState() {\n super.initState();\n _current = widget.initial ?? DateTime.now();\n }\n\n @override\n Widget build(BuildContext context) {\n return Row(\n mainAxisAlignment: MainAxisAlignment.spaceAround,\n children: [\n _previous(),\n _month(),\n _year(),\n _next(),\n widget.onSubmitted !=null? _button() : const SizedBox()\n ],\n );\n }\n\n Widget _previous() {\n return IconButton(\n onPressed: () {\n setState(() {\n _current = DateTime(_current.year, _current.month - 1);\n });\n widget.onSelected(_current);\n },\n icon: const Icon(Icons.arrow_back_ios_sharp));\n }\n\n Widget _next() {\n return IconButton(\n onPressed: () {\n setState(() {\n _current = DateTime(_current.year, _current.month + 1);\n });\n widget.onSelected(_current);\n },\n icon: const Icon(Icons.arrow_forward_ios_sharp));\n }\n\n Widget _month() {\n return Padding(\n padding: const EdgeInsets.all(10.0),\n child: Text('${_monthList[_current.month]}'),\n );\n }\n\n Widget _year() {\n return Padding(\n padding: const EdgeInsets.all(10.0),\n child: Text('${_current.year}'),\n );\n }\n\n Widget _button(){\n return Row(\n children: [\n TextButton(onPressed: (){\n widget.onSubmitted!(_current);\n }, child: const Text(\"Select\"))\n ],\n );\n }\n}\n Scaffold(\n body: HorizontalDatePicker(\n onSelected: (DateTime time){\n print(time);\n },\n onSubmitted: (DateTime time){\n print(time);\n },\n ),\n ),\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17237271/" ]
74,505,825
<p>Say I have a command I'm running in my script whose first line in <code>stderr</code> is something I need. I'm using <code>stderr</code> because <code>stdout</code> is already being used for transferring some other data. I still need the rest of <code>stderr</code> for user feedback, so I still want to display everything after the first line.</p> <pre class="lang-bash prettyprint-override"><code>cmd() { ssh usr@remote.machine.com ' printf &quot;stderr data line 1 (important)\n&quot; 1&gt;&amp;2 printf &quot;stdout data line 1\n&quot; printf &quot;stderr data line 2\n&quot; 1&gt;&amp;2 printf &quot;stdout data line 2\n&quot; printf &quot;stdout data line 3\n&quot; printf &quot;stderr data line 3\n&quot; 1&gt;&amp;2' } # What sort of shell magic would I need to extract # only the 1st line of stderr? cmd &gt; store_stdout_to_this_file ??? read -a first_line_of_stderr echo &quot;$first_line_of_stderr&quot; </code></pre> <p>I can't use a pipe, as pipes only pipe stdout, and even if I were to rearrange them, then the other end of the pipe is in a different process space.</p>
[ { "answer_id": 74505911, "author": "Gordon Davisson", "author_id": 89817, "author_profile": "https://Stackoverflow.com/users/89817", "pm_score": 3, "selected": true, "text": "read cat cmd >outputfile 2> >(read firstline; echo \"First line is: '$firstline'\"; cat -u)\n read cat { read firstline; cat -u; } < <(cmd 2>&1 >outputfile)\necho \"First line is: '$firstline'\"\n cmd read cat 2>&1" }, { "answer_id": 74505913, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 1, "selected": false, "text": "line=\nwhile read -r; do\n [[ -z $line ]] && line=\"$REPLY\" || echo \"$REPLY\"\ndone < <(cmd 2>&1 >out.log)\n\nstderr data line 2\nstderr data line 3\n\n# check $line\necho \"$line\"\n\nstderr data line 1 (important)\n out.log head -n 1" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366368/" ]
74,505,829
<p>I have a Oracle container DB SID orcl and pluggabel DB named pdb1. pdb1 has a table named customers. I am able to make the connection to database but I want to connect to a database table.</p> <p>Below is the jdbc url string I am able to construct:</p> <pre><code>jdbc:oracle:thin:@localhost:1521/pdb1 </code></pre> <p>I am using this string in a scripted sql connector. What parameter has to be included in this url string to connect to the table?</p>
[ { "answer_id": 74505911, "author": "Gordon Davisson", "author_id": 89817, "author_profile": "https://Stackoverflow.com/users/89817", "pm_score": 3, "selected": true, "text": "read cat cmd >outputfile 2> >(read firstline; echo \"First line is: '$firstline'\"; cat -u)\n read cat { read firstline; cat -u; } < <(cmd 2>&1 >outputfile)\necho \"First line is: '$firstline'\"\n cmd read cat 2>&1" }, { "answer_id": 74505913, "author": "anubhava", "author_id": 548225, "author_profile": "https://Stackoverflow.com/users/548225", "pm_score": 1, "selected": false, "text": "line=\nwhile read -r; do\n [[ -z $line ]] && line=\"$REPLY\" || echo \"$REPLY\"\ndone < <(cmd 2>&1 >out.log)\n\nstderr data line 2\nstderr data line 3\n\n# check $line\necho \"$line\"\n\nstderr data line 1 (important)\n out.log head -n 1" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4995349/" ]
74,505,850
<p>I wanted to render an array into a 2d grid (3 rows and 3 columns). The array itself is just a one-dimensional array.</p> <pre class="lang-js prettyprint-override"><code>const array = Array.from({ length: 9 }, (_, i) =&gt; i + 1); </code></pre> <p>I have a React component that renders it into a list of <code>div</code></p> <pre class="lang-js prettyprint-override"><code>export default function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;div className=&quot;grid&quot;&gt; {array.map((cell) =&gt; ( &lt;div className=&quot;cell&quot;&gt;{cell}&lt;/div&gt; ))} &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p>Now the cells are just stack on each other which is expected. I wonder if there is a way to make it a 3 x 3 grid without having to change the existing DOM structure by only adding styles?</p>
[ { "answer_id": 74505910, "author": "Yanick Rochon", "author_id": 320700, "author_profile": "https://Stackoverflow.com/users/320700", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.grid {\n display: grid;\n grid-template-columns: auto auto auto;\n background-color: #2196F3;\n padding: 10px;\n}\n.cell {\n background-color: rgba(255, 255, 255, 0.8);\n border: 1px solid rgba(0, 0, 0, 0.8);\n padding: 20px;\n font-size: 30px;\n text-align: center;\n}\n</style>\n</head>\n<body>\n<h1>Grid Elements</h1>\n\n<div class=\"grid\">\n <div class=\"cell\">1</div>\n <div class=\"cell\">2</div>\n <div class=\"cell\">3</div> \n <div class=\"cell\">4</div>\n <div class=\"cell\">5</div>\n <div class=\"cell\">6</div> \n <div class=\"cell\">7</div>\n <div class=\"cell\">8</div>\n <div class=\"cell\">9</div> \n</div>\n\n</body>\n</html>" }, { "answer_id": 74506001, "author": "Kamran Davar", "author_id": 12510464, "author_profile": "https://Stackoverflow.com/users/12510464", "pm_score": 0, "selected": false, "text": " display: grid;\n grid-template-columns: auto auto auto;\n background-color: #2196f3;\n padding: 10px;\n}\n.grid-item {\n background-color: rgba(255, 255, 255, 0.8);\n border: 1px solid rgba(0, 0, 0, 0.8);\n padding: 20px;\n font-size: 30px;\n text-align: center;\n}\n import \"./styles.css\";\nconst array = Array.from({ length: 9 }, (_, i) => i + 1);\n\nexport default function App() {\n return (\n <div className=\"App\">\n <div className=\"grid-container\">\n {array.map((cell) => (\n <div className=\"grid-item\">{cell}</div>\n ))}\n </div>\n </div>\n );\n}\n" }, { "answer_id": 74506059, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 0, "selected": false, "text": "grid array.map() const array = Array.from({ length: 9 }, (_, i) => i + 1);\n\nconst App = () =>\n<div className=\"App\">\n <div className=\"grid\">\n {array.map((cell, index) => (\n <div className=\"cell\" key={cell}>{cell}</div>\n ))}\n </div>\n</div>\n;\n\nReactDOM.render(<App />, document.querySelector('#root')); .grid {\n display: grid;\n grid-template-columns: repeat(3, 50px);\n grid-template-rows: repeat(3, 50px);\n}\n\n.cell {\n display: flex;\n justify-content: center;\n align-items: center;\n color: #333;\n background-color: pink;\n}\n\n.cell:nth-child(even) {\n color: #fff;\n background-color: hotpink;\n} <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7624223/" ]
74,505,863
<p>I need to check if the value of <code>url</code> exists within the <code>path</code> property in any of the objects or nodes of the following tree.</p> <p>Regarding the tree. The <code>children</code> property is optional but if it exists it could be expanded indefinitely</p> <p>The tree looks similar to the following</p> <pre><code>const items = [ { path: &quot;/admin/dashboard&quot;, menuIcon: { icon: &quot;dashboard&quot;, title: &quot;toolbar.dashboard&quot;, }, // children: [ // { // path: &quot;/admin/collection&quot;, // menuIcon: { // icon: &quot;summarize&quot;, // title: &quot;toolbar.reports&quot;, // }, // }, // ], }, { path: &quot;/admin/contents&quot;, menuIcon: { icon: &quot;archive&quot;, title: &quot;toolbar.contents&quot;, }, }, { path: &quot;/admin/cigar-house-management&quot;, menuIcon: { icon: &quot;home&quot;, title: &quot;toolbar.directory-management&quot;, }, children: [ { path: &quot;/admin/reports&quot;, menuIcon: { icon: &quot;summarize&quot;, title: &quot;toolbar.reports&quot;, }, children: [ { path: &quot;/admin/admin-reports&quot;, menuIcon: { icon: &quot;summarize&quot;, title: &quot;toolbar.reports&quot;, }, }, ], }, ], }, ]; </code></pre> <p>In order to achieve the desired result I am using the following function</p> <pre><code>function isValid(url, tree) { if (tree &amp;&amp; Array.isArray(tree) &amp;&amp; tree.length &gt; 0) { for (const node of tree) { if (node.path === url) { return true; } if (!node.children) { continue; } const found = isValid(url, node.children); if (found) { return found; } return false; } } } </code></pre> <p>Can be checked here</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const url = "/admin/admin-reports"; const items = [ { path: "/admin/dashboard", menuIcon: { icon: "dashboard", title: "toolbar.dashboard", }, // children: [ // { // path: "/admin/collection", // menuIcon: { // icon: "summarize", // title: "toolbar.reports", // }, // }, // ], }, { path: "/admin/contents", menuIcon: { icon: "archive", title: "toolbar.contents", }, }, { path: "/admin/cigar-house-management", menuIcon: { icon: "home", title: "toolbar.directory-management", }, children: [ { path: "/admin/reports", menuIcon: { icon: "summarize", title: "toolbar.reports", }, children: [ { path: "/admin/admin-reports", menuIcon: { icon: "summarize", title: "toolbar.reports", }, }, ], }, ], }, ]; function isValid(url, tree) { if (tree &amp;&amp; Array.isArray(tree) &amp;&amp; tree.length &gt; 0) { for (const node of tree) { if (node.path === url) { return true; } if (!node.children) { continue; } const found = isValid(url, node.children); if (found) { return found; } return false; } } } const output = isValid(url, items); console.log(output);</code></pre> </div> </div> </p> <p>But I have noticed that when adding a new node (like the commented node in the tree example), for example as a child of the first node, it does not evaluate the ones after the parent node.</p> <p>Also, recursion is usually difficult for me so I would appreciate your advice.</p> <p>Thanks in advance</p>
[ { "answer_id": 74505918, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 2, "selected": true, "text": "true false function isValid(url, tree) {\n return tree.some(item =>\n item.path === url || (item.children && isValid(url, item.children))\n );\n}\n" }, { "answer_id": 74507176, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 0, "selected": false, "text": " /* \n || Without that extra >children< property, the function goes on to find\n || the given search term \n */ \n if (!node.children) {\n continue;\n }\n /*\n || But with that extra >children< property on the way the function is \n || forced to continue onto this snafu. Since the extra >children<\n || property returns as false from isValid(), the control statement \n || is skipped and goes to the last line which is return false. So the \n || function terminates because a return statement always terminates the \n || function thereby never reaching the end of the array. \n */ \n const found = isValid(url, node.children);\n if (found) {\n return found;\n }\n /*\n || Do not use a return within a \"for\" loop. If it is reached then most\n || likely the function terminates too early and the loop never continues \n || onto the next iteration.\n */\n return false; \n }\n const admin = [{\n title: \"Dashboard\",\n path: \"/admin/dashboard\",\n items: [{\n title: \"Dashboard Reports\",\n path: \"/admin/dashboard/reports\"\n }]\n },\n {\n title: \"Management\",\n path: \"/admin/management\",\n items: [{\n title: \"Management Reports\",\n path: \"/admin/management/reports\"\n }]\n },\n {\n title: \"Archive\",\n path: \"/admin/archive\",\n items: [{\n title: \"Archive Reports\",\n path: \"/admin/archive/reports\",\n items: [{\n title: \"Archive Reports Management\",\n path: \"/admin/archive/reports/management\"\n }, {\n title: \"Archive Reports Dashboard\",\n path: \"/admin/archive/reports/dashboard\"\n }]\n }]\n }\n];\n\n/**\n * Searches for a given string within each object's >path< property value of a\n * given array of objects.\n * @param {String} term - The string segment to search for.\n * @param {Array<object>} struct - The array of objects to search through\n * @returns {Array<array>} - An array of arrays that contain the value of each\n * >path< property that has >term< within it.\n */\nfunction searchStruct(term, struct) {\n let data = []; // 1\n if (Array.isArray(struct)) {\n for (const node of struct) {\n if (node.path.includes(term)) {\n data.push(node.path); // 2\n }\n if (node.items) {\n data.push(searchStruct(term, node.items)); // 3\n }\n }\n }\n return data; // 4\n}\n\nconsole.log(searchStruct(\"reports\", admin));\n/**\n * If you just want a simple true/false returned, replace the line at\n * 1 with: (remove line)\n * 2 with: return true;\n * 3 with: if (searchStruct(term, node.items)) return true;\n * 4 with: return false;\n */ if (node.items) {\n data.push(searchStruct(term, node.items));\n}\n searchStruct(term, node.items)\n// New value passed ⤴️\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615274/" ]
74,505,867
<p>I am doing a simple props drilling using typeScript. I want to pass the array from my useState hook to the component. But I couldn't pass the props as it's mentioned in the warning dialogue.</p> <pre><code>Type '{ contactData: Props[] | null; }' is not assignable to type 'IntrinsicAttributes &amp; Props[]'. Property 'contactData' does not exist on type 'IntrinsicAttributes &amp; Props[]' </code></pre> <p>I am wondering is there any type definition error or any props passing error. <strong>please anyone pick me up from the sea.</strong> Here is the code:</p> <pre><code>import {useState } from &quot;react&quot;; import &quot;./App.css&quot;; interface Props { name: string; email: string; } function App() { const [contactData, setContactData] = useState&lt; Props[] | null&gt;(null); return ( &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;Hello from MARS&lt;/h1&gt; &lt;div className=&quot;container&quot;&gt; &lt;div&gt; &lt;TableData contactData={contactData}/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } export default App; const TableData = ({contactData}: Props[]) =&gt; { return ( &lt;div&gt; {!contactData &amp;&amp; &lt;p&gt;No data to show!!&lt;/p&gt;} {contactData.map((item: Props, index: number) =&gt; ( &lt;div key={index}&gt; &lt;h2&gt;Name: {item.name}&lt;/h2&gt; &lt;h3&gt;Email: {item.email}&lt;/h3&gt; &lt;/div&gt; ))} &lt;/div&gt; ); }; </code></pre> <p>How can I pass the props to the components with compliant with typescript definition?</p>
[ { "answer_id": 74505918, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 2, "selected": true, "text": "true false function isValid(url, tree) {\n return tree.some(item =>\n item.path === url || (item.children && isValid(url, item.children))\n );\n}\n" }, { "answer_id": 74507176, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 0, "selected": false, "text": " /* \n || Without that extra >children< property, the function goes on to find\n || the given search term \n */ \n if (!node.children) {\n continue;\n }\n /*\n || But with that extra >children< property on the way the function is \n || forced to continue onto this snafu. Since the extra >children<\n || property returns as false from isValid(), the control statement \n || is skipped and goes to the last line which is return false. So the \n || function terminates because a return statement always terminates the \n || function thereby never reaching the end of the array. \n */ \n const found = isValid(url, node.children);\n if (found) {\n return found;\n }\n /*\n || Do not use a return within a \"for\" loop. If it is reached then most\n || likely the function terminates too early and the loop never continues \n || onto the next iteration.\n */\n return false; \n }\n const admin = [{\n title: \"Dashboard\",\n path: \"/admin/dashboard\",\n items: [{\n title: \"Dashboard Reports\",\n path: \"/admin/dashboard/reports\"\n }]\n },\n {\n title: \"Management\",\n path: \"/admin/management\",\n items: [{\n title: \"Management Reports\",\n path: \"/admin/management/reports\"\n }]\n },\n {\n title: \"Archive\",\n path: \"/admin/archive\",\n items: [{\n title: \"Archive Reports\",\n path: \"/admin/archive/reports\",\n items: [{\n title: \"Archive Reports Management\",\n path: \"/admin/archive/reports/management\"\n }, {\n title: \"Archive Reports Dashboard\",\n path: \"/admin/archive/reports/dashboard\"\n }]\n }]\n }\n];\n\n/**\n * Searches for a given string within each object's >path< property value of a\n * given array of objects.\n * @param {String} term - The string segment to search for.\n * @param {Array<object>} struct - The array of objects to search through\n * @returns {Array<array>} - An array of arrays that contain the value of each\n * >path< property that has >term< within it.\n */\nfunction searchStruct(term, struct) {\n let data = []; // 1\n if (Array.isArray(struct)) {\n for (const node of struct) {\n if (node.path.includes(term)) {\n data.push(node.path); // 2\n }\n if (node.items) {\n data.push(searchStruct(term, node.items)); // 3\n }\n }\n }\n return data; // 4\n}\n\nconsole.log(searchStruct(\"reports\", admin));\n/**\n * If you just want a simple true/false returned, replace the line at\n * 1 with: (remove line)\n * 2 with: return true;\n * 3 with: if (searchStruct(term, node.items)) return true;\n * 4 with: return false;\n */ if (node.items) {\n data.push(searchStruct(term, node.items));\n}\n searchStruct(term, node.items)\n// New value passed ⤴️\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19309580/" ]
74,505,903
<p>So I'm trying to set up a custom domain for my AWS Lambda function.</p> <p>I went through all the instructions to buy a domain name via google domains, set up a certificate through AWS Certificate manager, and created the corresponding route 53 hosted zone.</p> <p><a href="https://i.stack.imgur.com/jjwaL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jjwaL.png" alt="enter image description here" /></a></p> <p>For whatever reason, I unfortunately get a 403 error when I try to reach the API Gateway domain name endpoint. In this case, it's <a href="https://d-frdw0740fd.execute-api.us-east-1.amazonaws.com" rel="nofollow noreferrer">https://d-frdw0740fd.execute-api.us-east-1.amazonaws.com</a>.</p> <p>Also for context, here is my API mappings tab.</p> <p><a href="https://i.stack.imgur.com/G9bON.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G9bON.png" alt="API mappings tab" /></a></p> <p>For more context, here is my hosted zone in route 53 corresponding with my custom domain name:</p> <p><a href="https://i.stack.imgur.com/73YfG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/73YfG.png" alt="route 53" /></a></p> <p>Instead of bringing me to a <code>{&quot;message&quot;: &quot;Not Found&quot;}</code> page, I'd like it to bring me to my actual aws endpoint.</p> <p>Where am I going wrong in order to set up my configuration so that my API Gateway domain name is correctly linked to the functional aws endpoint instead of just reaching a 404 error?</p> <p>UPDATE: I redeployed my serverless function and not instead of getting now instead of the 404 <code>Not Found</code> error I get 403 <code>Forbidden</code>:</p> <pre><code>{ &quot;message&quot;: &quot;Forbidden&quot; } </code></pre>
[ { "answer_id": 74505918, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 2, "selected": true, "text": "true false function isValid(url, tree) {\n return tree.some(item =>\n item.path === url || (item.children && isValid(url, item.children))\n );\n}\n" }, { "answer_id": 74507176, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 0, "selected": false, "text": " /* \n || Without that extra >children< property, the function goes on to find\n || the given search term \n */ \n if (!node.children) {\n continue;\n }\n /*\n || But with that extra >children< property on the way the function is \n || forced to continue onto this snafu. Since the extra >children<\n || property returns as false from isValid(), the control statement \n || is skipped and goes to the last line which is return false. So the \n || function terminates because a return statement always terminates the \n || function thereby never reaching the end of the array. \n */ \n const found = isValid(url, node.children);\n if (found) {\n return found;\n }\n /*\n || Do not use a return within a \"for\" loop. If it is reached then most\n || likely the function terminates too early and the loop never continues \n || onto the next iteration.\n */\n return false; \n }\n const admin = [{\n title: \"Dashboard\",\n path: \"/admin/dashboard\",\n items: [{\n title: \"Dashboard Reports\",\n path: \"/admin/dashboard/reports\"\n }]\n },\n {\n title: \"Management\",\n path: \"/admin/management\",\n items: [{\n title: \"Management Reports\",\n path: \"/admin/management/reports\"\n }]\n },\n {\n title: \"Archive\",\n path: \"/admin/archive\",\n items: [{\n title: \"Archive Reports\",\n path: \"/admin/archive/reports\",\n items: [{\n title: \"Archive Reports Management\",\n path: \"/admin/archive/reports/management\"\n }, {\n title: \"Archive Reports Dashboard\",\n path: \"/admin/archive/reports/dashboard\"\n }]\n }]\n }\n];\n\n/**\n * Searches for a given string within each object's >path< property value of a\n * given array of objects.\n * @param {String} term - The string segment to search for.\n * @param {Array<object>} struct - The array of objects to search through\n * @returns {Array<array>} - An array of arrays that contain the value of each\n * >path< property that has >term< within it.\n */\nfunction searchStruct(term, struct) {\n let data = []; // 1\n if (Array.isArray(struct)) {\n for (const node of struct) {\n if (node.path.includes(term)) {\n data.push(node.path); // 2\n }\n if (node.items) {\n data.push(searchStruct(term, node.items)); // 3\n }\n }\n }\n return data; // 4\n}\n\nconsole.log(searchStruct(\"reports\", admin));\n/**\n * If you just want a simple true/false returned, replace the line at\n * 1 with: (remove line)\n * 2 with: return true;\n * 3 with: if (searchStruct(term, node.items)) return true;\n * 4 with: return false;\n */ if (node.items) {\n data.push(searchStruct(term, node.items));\n}\n searchStruct(term, node.items)\n// New value passed ⤴️\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1947730/" ]
74,505,924
<p>They offer great details on setContent and commands in general. But, I've been ctrl+F looking everywhere for where &quot;commands&quot; should be placed in code. I'm just hoping to load in HTML that I exported earlier with this Tiptap Editor.</p> <p><a href="https://tiptap.dev/api/commands/set-content" rel="nofollow noreferrer">https://tiptap.dev/api/commands/set-content</a></p> <p>Here's some of my code for reference. Although, not sure if this has anything to do with where to put commands:</p> <pre><code>import &quot;../../styles/tiptap.scss&quot;; import { EditorContent, useEditor } from &quot;@tiptap/react&quot;; import StarterKit from &quot;@tiptap/starter-kit&quot;; import React, { useEffect } from &quot;react&quot;; const MenuBar = ({ editor }) =&gt; { if (!editor) { return null; } return ( &lt;&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleBold().run()} disabled={!editor.can().chain().focus().toggleBold().run()} className={editor.isActive(&quot;bold&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; bold &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleItalic().run()} disabled={!editor.can().chain().focus().toggleItalic().run()} className={editor.isActive(&quot;italic&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; italic &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleStrike().run()} disabled={!editor.can().chain().focus().toggleStrike().run()} className={editor.isActive(&quot;strike&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; strike &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleCode().run()} disabled={!editor.can().chain().focus().toggleCode().run()} className={editor.isActive(&quot;code&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; code &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().unsetAllMarks().run()}&gt;clear marks&lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().clearNodes().run()}&gt;clear nodes&lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().setParagraph().run()} className={editor.isActive(&quot;paragraph&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; paragraph &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleHeading({ level: 1 }).run()} className={editor.isActive(&quot;heading&quot;, { level: 1 }) ? &quot;is-active&quot; : &quot;&quot;} &gt; h1 &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleHeading({ level: 2 }).run()} className={editor.isActive(&quot;heading&quot;, { level: 2 }) ? &quot;is-active&quot; : &quot;&quot;} &gt; h2 &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleHeading({ level: 3 }).run()} className={editor.isActive(&quot;heading&quot;, { level: 3 }) ? &quot;is-active&quot; : &quot;&quot;} &gt; h3 &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleHeading({ level: 4 }).run()} className={editor.isActive(&quot;heading&quot;, { level: 4 }) ? &quot;is-active&quot; : &quot;&quot;} &gt; h4 &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleHeading({ level: 5 }).run()} className={editor.isActive(&quot;heading&quot;, { level: 5 }) ? &quot;is-active&quot; : &quot;&quot;} &gt; h5 &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleHeading({ level: 6 }).run()} className={editor.isActive(&quot;heading&quot;, { level: 6 }) ? &quot;is-active&quot; : &quot;&quot;} &gt; h6 &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleBulletList().run()} className={editor.isActive(&quot;bulletList&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; bullet list &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleOrderedList().run()} className={editor.isActive(&quot;orderedList&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; ordered list &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleCodeBlock().run()} className={editor.isActive(&quot;codeBlock&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; code block &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().toggleBlockquote().run()} className={editor.isActive(&quot;blockquote&quot;) ? &quot;is-active&quot; : &quot;&quot;} &gt; blockquote &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().setHorizontalRule().run()}&gt; horizontal rule &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().setHardBreak().run()}&gt;hard break&lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().undo().run()} disabled={!editor.can().chain().focus().undo().run()} &gt; undo &lt;/button&gt; &lt;button onClick={() =&gt; editor.chain().focus().redo().run()} disabled={!editor.can().chain().focus().redo().run()} &gt; redo &lt;/button&gt; &lt;/&gt; ); }; export default ({ newPostRichText, setNewPostRichText }) =&gt; { const editor = useEditor({ extensions: [StarterKit], content: ` &lt;h2&gt; Hi there, &lt;/h2&gt; &lt;p&gt; this is a &lt;em&gt;basic&lt;/em&gt; example of &lt;strong&gt;tiptap&lt;/strong&gt;. Sure, there are all kind of basic text styles you’d probably expect from a text editor. But wait until you see the lists: &lt;/p&gt; &lt;ul&gt; &lt;li&gt; That’s a bullet list with one … &lt;/li&gt; &lt;li&gt; … or two list items. &lt;/li&gt; &lt;/ul&gt; &lt;p&gt; Isn’t that great? And all of that is editable. But wait, there’s more. Let’s try a code block: &lt;/p&gt; &lt;pre&gt;&lt;code class=&quot;language-css&quot;&gt;body { display: none; }&lt;/code&gt;&lt;/pre&gt; &lt;p&gt; I know, I know, this is impressive. It’s only the tip of the iceberg though. Give it a try and click a little bit around. Don’t forget to check the other examples too. &lt;/p&gt; &lt;blockquote&gt; Wow, that’s amazing. Good work, boy! &lt;br /&gt; — Mom &lt;/blockquote&gt; `, // triggered on every change onUpdate: ({ editor }) =&gt; { setNewPostRichText(editor?.getHTML()); //console.log(newPostRichText); }, }); return ( &lt;div&gt; &lt;MenuBar editor={editor} /&gt; &lt;EditorContent editor={editor} /&gt; &lt;/div&gt; ); }; </code></pre> <p>I'm hoping to pass the HTML I exported from TipTap back in</p>
[ { "answer_id": 74505918, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 2, "selected": true, "text": "true false function isValid(url, tree) {\n return tree.some(item =>\n item.path === url || (item.children && isValid(url, item.children))\n );\n}\n" }, { "answer_id": 74507176, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 0, "selected": false, "text": " /* \n || Without that extra >children< property, the function goes on to find\n || the given search term \n */ \n if (!node.children) {\n continue;\n }\n /*\n || But with that extra >children< property on the way the function is \n || forced to continue onto this snafu. Since the extra >children<\n || property returns as false from isValid(), the control statement \n || is skipped and goes to the last line which is return false. So the \n || function terminates because a return statement always terminates the \n || function thereby never reaching the end of the array. \n */ \n const found = isValid(url, node.children);\n if (found) {\n return found;\n }\n /*\n || Do not use a return within a \"for\" loop. If it is reached then most\n || likely the function terminates too early and the loop never continues \n || onto the next iteration.\n */\n return false; \n }\n const admin = [{\n title: \"Dashboard\",\n path: \"/admin/dashboard\",\n items: [{\n title: \"Dashboard Reports\",\n path: \"/admin/dashboard/reports\"\n }]\n },\n {\n title: \"Management\",\n path: \"/admin/management\",\n items: [{\n title: \"Management Reports\",\n path: \"/admin/management/reports\"\n }]\n },\n {\n title: \"Archive\",\n path: \"/admin/archive\",\n items: [{\n title: \"Archive Reports\",\n path: \"/admin/archive/reports\",\n items: [{\n title: \"Archive Reports Management\",\n path: \"/admin/archive/reports/management\"\n }, {\n title: \"Archive Reports Dashboard\",\n path: \"/admin/archive/reports/dashboard\"\n }]\n }]\n }\n];\n\n/**\n * Searches for a given string within each object's >path< property value of a\n * given array of objects.\n * @param {String} term - The string segment to search for.\n * @param {Array<object>} struct - The array of objects to search through\n * @returns {Array<array>} - An array of arrays that contain the value of each\n * >path< property that has >term< within it.\n */\nfunction searchStruct(term, struct) {\n let data = []; // 1\n if (Array.isArray(struct)) {\n for (const node of struct) {\n if (node.path.includes(term)) {\n data.push(node.path); // 2\n }\n if (node.items) {\n data.push(searchStruct(term, node.items)); // 3\n }\n }\n }\n return data; // 4\n}\n\nconsole.log(searchStruct(\"reports\", admin));\n/**\n * If you just want a simple true/false returned, replace the line at\n * 1 with: (remove line)\n * 2 with: return true;\n * 3 with: if (searchStruct(term, node.items)) return true;\n * 4 with: return false;\n */ if (node.items) {\n data.push(searchStruct(term, node.items));\n}\n searchStruct(term, node.items)\n// New value passed ⤴️\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574734/" ]
74,505,984
<p>How can I put a widget/compose in bottom end corner of Column?</p> <pre><code>Column( verticalArrangement = , horizontalAlignment = ) { // omitted codes } </code></pre> <p>I only find horizontal and vertical position to it? IS there a way to put a widget/compose in bottom end?</p> <p>I can’t find a parameter in column to place widget/compose in bottom end corner</p>
[ { "answer_id": 74506157, "author": "Vahid Garousi", "author_id": 5909910, "author_profile": "https://Stackoverflow.com/users/5909910", "pm_score": 2, "selected": false, "text": "@Composable\nfun BoxExample2() {\n Box(\n modifier = Modifier\n .background(color = Color.LightGray)\n .fillMaxSize()\n ) {\n \n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.TopStart),\n text = \"TopStart\"\n )\n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.TopCenter),\n text = \"TopCenter\"\n )\n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.TopEnd),\n text = \"TopEnd\"\n )\n \n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.CenterStart),\n text = \"CenterStart\"\n )\n \n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.Center),\n text = \"Center\"\n )\n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.CenterEnd),\n text = \"CenterEnd\"\n )\n \n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.BottomStart),\n text = \"BottomStart\"\n )\n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.BottomCenter),\n text = \"BottomCenter\"\n )\n Text(\n style = MaterialTheme.typography.h6,\n modifier = Modifier\n .background(Color.Yellow)\n .padding(10.dp)\n .align(Alignment.BottomEnd),\n text = \"BottomEnd\"\n )\n }\n}\n" }, { "answer_id": 74506512, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "Column Column(\n modifier=Modifier.fillMaxSize(),\n verticalArrangement = Arrangement.Bottom,\n horizontalAlignment = Alignment.End\n) { \n\n Button(onClick = {}){\n Text(\"Button\")\n }\n\n}\n verticalArrangement horizontalAlignment Column Column(\n modifier=Modifier.fillMaxWidth().height(80.dp).background(Yellow),\n verticalArrangement = Arrangement.Bottom,\n horizontalAlignment = Alignment.End\n)\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20552417/" ]
74,505,985
<p>I am displaying the data in the list with sort order in the textbox. User can change the order and click on submit will save the changed order in the database. list will be displaying in the new order on page refresh. Issue: How to refresh the list on form submit Without Page Refresh. Please help. Please find my sandbox:<a href="https://codesandbox.io/s/gallant-morning-k4emln" rel="nofollow noreferrer">https://codesandbox.io/s/gallant-morning-k4emln</a></p> <pre><code>import React from &quot;react&quot;; import XMLParser from &quot;react-xml-parser&quot;; const data = `&lt;?xml version=&quot;1.0&quot;?&gt; &lt;Category&gt; &lt;description description-id=&quot;11&quot; display-sequence=&quot;2&quot;&gt;testing&lt;/description&gt; &lt;description description-id=&quot;15&quot; display-sequence=&quot;5&quot;&gt;Guide&lt;/description&gt; &lt;description description-id=&quot;20&quot; display-sequence=&quot;7&quot;&gt;test&lt;/description&gt; &lt;description description-id=&quot;25&quot; display-sequence=&quot;10&quot;&gt;Guide&lt;/description&gt; &lt;description description-id=&quot;30&quot; display-sequence=&quot;12&quot;&gt;test&lt;/description&gt; &lt;/Category&gt; &lt;/xml&gt;`; const REQUEST_URL = &quot;&quot;; const axios = { get: () =&gt; new Promise((resolve) =&gt; { setTimeout(resolve, 1000, { data }); }) }; class Order_Descriptions extends React.Component { constructor(props) { super(props); this.state = { proddescriptions: [], proddescription_id: &quot;&quot;, display_sequence: &quot;&quot; }; } handleChange = (event) =&gt; { const { name, value } = event.target; this.setState((prevState) =&gt; ({ proddescriptions: prevState.proddescriptions.map((el) =&gt; el.id === name ? { ...el, sequence: value } : el ) })); }; componentDidMount() { this.getlistofdescriptions(); } getlistofdescriptions() { axios .get(REQUEST_URL, { &quot;Content-Type&quot;: &quot;application/xml; charset=utf-8&quot; }) .then((response) =&gt; { const jsonDataFromXml = new XMLParser().parseFromString(data); const descriptions = jsonDataFromXml.getElementsByTagName( &quot;description&quot; ); /* console.log(descriptions); this.setState({ proddescriptions: jsonDataFromXml.getElementsByTagName(&quot;description&quot;) }); }); const URL = &quot;/descriptionlist&quot; axios .get(URL, { 'withCredentials': 'true' }) .then((response) =&gt; { const jsonDataFromXml = new XMLParser().parseFromString(response.data); const descriptions = jsonDataFromXml.getElementsByTagName( &quot;description&quot; )*/ const proddescriptions = descriptions.map(({ attributes, value }) =&gt; ({ id: attributes[&quot;description-id&quot;], sequence: attributes[&quot;display-sequence&quot;], value })); this.setState({ proddescriptions }); }); } handleSubmit = (event) =&gt; { event.preventDefault(); const ProdDescriptions = this.state.proddescriptions; const URL = &quot;/descriptionlist/order&quot;; const data = { ProdDescriptions }; fetch(URL, { method: &quot;POST&quot;, headers: { &quot;Content-Type&quot;: &quot;application/json&quot; }, credentials: &quot;include&quot;, body: JSON.stringify(data) }) .then((response) =&gt; response.json()) .then((data) =&gt; { this.setState({ ValidationStatus: data }); }) .catch((error) =&gt; console.error(&quot;Error:&quot;, error)); }; render() { return ( &lt;div&gt; &lt;form onSubmit={this.handleSubmit}&gt; &lt;div&gt; &lt;ul style={{ listStyle: &quot;none&quot; }}&gt; {this.state.proddescriptions.map((item) =&gt; ( &lt;li key={item.id}&gt; &lt;label&gt; &lt;input type=&quot;text&quot; name={item.id} size=&quot;5&quot; maxLength=&quot;3&quot; value={item.sequence} onChange={this.handleChange} /&gt; &lt;/label&gt; &amp;nbsp;{item.value}{&quot; &quot;} &lt;/li&gt; ))} &lt;/ul&gt; &lt;/div&gt; &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot; id=&quot;btnsubmit&quot; /&gt; &lt;/form&gt; &lt;/div&gt; ); } } export default function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;Sort Data&lt;/h1&gt; &lt;h5&gt;Submit button sort list without page refresh&lt;/h5&gt; &lt;Order_Descriptions /&gt; &lt;/div&gt; ); } </code></pre> <p>thanks</p>
[ { "answer_id": 74506041, "author": "fatih-erikli", "author_id": 17805504, "author_profile": "https://Stackoverflow.com/users/17805504", "pm_score": 0, "selected": false, "text": "this.getlistofdescriptions()" }, { "answer_id": 74506070, "author": "Ali Sattarzadeh", "author_id": 11434567, "author_profile": "https://Stackoverflow.com/users/11434567", "pm_score": 2, "selected": true, "text": "compare(a, b) {\n if (parseInt(a.sequence, 10) > parseInt(b.sequence, 10)) return 1;\n if (parseInt(a.sequence, 10) < parseInt(b.sequence, 10)) return -1;\n return 0;\n}\n this.setState({ proddescriptions: ProdDescriptions.sort(compare) });\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037420/" ]
74,505,993
<p>I am trying to build my portfolio website and I dont have any prior knowledge of html. I am trying to align buttons horizontally on the webpage and was hoping I could get some help on how I can edit this piece of code to fix this alignment issue.</p> <p><a href="https://i.stack.imgur.com/9xma9.png" rel="nofollow noreferrer">Webpage</a></p> <p>Below is the code snippet:</p> <pre><code>&lt;article&gt; &lt;header&gt; &lt;h2&gt;&lt;a href=&quot;#&quot;&gt;Labeling using&lt;br /&gt; Weak Supervision&lt;/a&gt; &lt;/h2&gt; &lt;/header&gt; &lt;a href=&quot;#&quot; class=&quot;image fit&quot;&gt;&lt;img src=&quot;images/Snorkel-AI.png&quot; alt=&quot;&quot; width =auto height =auto /&gt;&lt;/a&gt; &lt;p&gt;Snorkel is a system for programmatically building and managing training datasets using the concept of weak supervision. This use cases demonstrates programtically labeling of text messages as spam or non-spam using snorkel.&lt;/p&gt; &lt;ul class=&quot;actions special&quot;&gt; &lt;li&gt;&lt;a href=&quot;https://github.com/tauseef1234/Spam_Labeling_Snorkel/blob/main/SMS_Snorkel.ipynb&quot; class=&quot;button&quot;&gt;GitHub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; &lt;article&gt; &lt;header&gt; &lt;h2&gt;&lt;a href=&quot;#&quot;&gt;Traffic Sign &lt;br /&gt; Detection&lt;/a&gt; &lt;/h2&gt; &lt;/header&gt; &lt;a href=&quot;#&quot; class=&quot;image fit&quot;&gt;&lt;img src=&quot;images/traffic.png&quot; alt=&quot;&quot; width =auto height =auto /&gt;&lt;/a&gt; &lt;p&gt;In this project, I use TensorFlow to build a neural network to classify road signs based on an image of those signs. For this project, the German Traffic Sign Recognition Benchmark (GTSRB) dataset was used that contains thousands of images of 43 different kinds of road signs. &lt;/p&gt; &lt;ul class=&quot;actions special&quot;&gt; &lt;li&gt;&lt;a href=&quot;https://github.com/tauseef1234/Traffic_CNN&quot; class=&quot;button&quot;&gt;GitHub&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; </code></pre> <p>I tried adding extra spaces but that required lot of editing in the existing code.</p>
[ { "answer_id": 74506041, "author": "fatih-erikli", "author_id": 17805504, "author_profile": "https://Stackoverflow.com/users/17805504", "pm_score": 0, "selected": false, "text": "this.getlistofdescriptions()" }, { "answer_id": 74506070, "author": "Ali Sattarzadeh", "author_id": 11434567, "author_profile": "https://Stackoverflow.com/users/11434567", "pm_score": 2, "selected": true, "text": "compare(a, b) {\n if (parseInt(a.sequence, 10) > parseInt(b.sequence, 10)) return 1;\n if (parseInt(a.sequence, 10) < parseInt(b.sequence, 10)) return -1;\n return 0;\n}\n this.setState({ proddescriptions: ProdDescriptions.sort(compare) });\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74505993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15229524/" ]
74,506,004
<p>I tried to create a tic tac toe program with python list:</p> <pre><code>theBoard=[' '' '' ']*3 def userInput(board): loop=True while loop: userInput=input(&quot;Please enter (row,column)&quot;) row=int(userInput[0]) column=int(userInput[2]) if row&lt;1 or row&gt;3: print('[ERROR: Invalid Input]') loop=True elif column&lt;1 or column&gt;3: print('[ERROR: Invalid Input]') loop=True else: board[row-1][column-1]='X' loop=False def drawBoard(board): #Function that prints out board print(board[0][0]+' | '+board[0][1]+' | '+board[0][2]) print('---------') print(board[1][0]+' | '+board[1][1]+' | '+board[1][2]) print('---------') print(board[2][0]+' | '+board[2][1]+' | '+board[2][2]) print('---------') userInput(theBoard) drawBoard(theBoard) </code></pre> <p>Error I got: TypeError: 'str' object does not support item assignment</p> <p><a href="https://i.stack.imgur.com/QniIG.png" rel="nofollow noreferrer">edit: sorry, i forgot to add the error line</a></p> <p>I dont know why but the program mistook theBoard as a string rather than a list.</p> <p>*A lot of people asked me to change theBoard=[' '' '' ']*3 to theBoard=[' ',' ',' ']*3 which i did however, I am still receiving the same error</p>
[ { "answer_id": 74506041, "author": "fatih-erikli", "author_id": 17805504, "author_profile": "https://Stackoverflow.com/users/17805504", "pm_score": 0, "selected": false, "text": "this.getlistofdescriptions()" }, { "answer_id": 74506070, "author": "Ali Sattarzadeh", "author_id": 11434567, "author_profile": "https://Stackoverflow.com/users/11434567", "pm_score": 2, "selected": true, "text": "compare(a, b) {\n if (parseInt(a.sequence, 10) > parseInt(b.sequence, 10)) return 1;\n if (parseInt(a.sequence, 10) < parseInt(b.sequence, 10)) return -1;\n return 0;\n}\n this.setState({ proddescriptions: ProdDescriptions.sort(compare) });\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20552475/" ]
74,506,023
<p>I have to select some employees from a Syncfusion Multiselect in Blazor WASM. When I use it with 5000 employee data, it works so slow or crashes. I search my employee with FullName or Personnel Number(FullInfo is FullName and Personnel Number together). I try to send my search string after 4 string to the backend and receive result and set it to datasource and refresh the dropdown list, but it also not work efficiently and I think this isn't the best practice for this issue.</p> <pre><code>&lt;SfMultiSelect @ref=&quot;mulObj&quot; TValue=&quot;List&lt;string&gt;&quot; TItem=&quot;EmployeeQueryModel&quot; Mode=&quot;VisualMode.Box&quot; EnableRtl=&quot;true&quot; Query=&quot;LocalDataQuery&quot; EnableVirtualization=&quot;true&quot; Placeholder=&quot;Please choose your employees...&quot; AllowFiltering=&quot;true&quot; DataSource=&quot;employeesDropDown&quot; @bind-Value=&quot;CommandModel.MultiSelectEmployees&quot;&gt; &lt;MultiSelectFieldSettings Value=&quot;PersonnelCode&quot; Text=&quot;FullInfo&quot;&gt; &lt;/MultiSelectFieldSettings&gt; &lt;MultiSelectEvents TItem=&quot;EmployeeQueryModel&quot; TValue=&quot;List&lt;string&gt;&quot; ValueRemoved=&quot;@ValueRemovedHandler&quot; Filtering=&quot;@FilteringHandler&quot; OnValueSelect=&quot;@OnValueSelectHandler&quot; Cleared=&quot;@ClearedHandler&quot;&gt; &lt;/MultiSelectEvents&gt; &lt;/SfMultiSelect&gt; @code { ... private void OnValueSelectHandler(SelectEventArgs&lt;EmployeeQueryModel&gt; args) { selectedEmployees.Add(args.ItemData); } private void ValueRemovedHandler(RemoveEventArgs&lt;EmployeeQueryModel&gt; args) { selectedEmployees.Remove(args.ItemData); } private void ClearedHandler(MouseEventArgs args) { selectedEmployees = new List&lt;EmployeeQueryModel&gt;(); } private async Task FilteringHandler(FilteringEventArgs args) { if (args.Text.Length &gt;= 4) { args.PreventDefaultAction = true; employeesDropDown = GetFilteredEmployees(args.Text); employeesDropDown.AddRange(selectedEmployees); await mulObj.FilterAsync(employeesFiltered, LocalDataQuery); await mulObj.RefreshDataAsync(); } } ... </code></pre> <p>How can I implement Blazor Syncfusion MultiSelect in a better way and improve performance of my app? How to use Blazor Syncfusion MultiSelect in a better way?</p>
[ { "answer_id": 74506082, "author": "AlirezaK", "author_id": 4444757, "author_profile": "https://Stackoverflow.com/users/4444757", "pm_score": 2, "selected": false, "text": "AsAsyncEnumerable public IAsyncEnumerable<Employee> GetEmployees()\n {\n return _dbContext.Employees \n .AsAsyncEnumerable();\n } \n" }, { "answer_id": 74519465, "author": "sureshkumar", "author_id": 6487280, "author_profile": "https://Stackoverflow.com/users/6487280", "pm_score": 1, "selected": false, "text": "<SfMultiSelect @ref=\"DDLObj\" AllowFiltering=\"true\" TValue=\"string[]\" TItem=\"Record\" Placeholder=\"e.g. Item 1\" DataSource=\"@Records\" Query=\"@LocalDataQuery\" PopupHeight=\"130px\" EnableVirtualization=\"true\">\n<MultiSelectFieldSettings Text=\"Text\" Value=\"ID\" />\n<MultiSelectEvents TValue=\"string[]\" TItem=\"Record\" Filtering=\"OnFilter\"></MultiSelectEvents>\n @code {\nSfMultiSelect<string[], Record> DDLObj;\npublic Query LocalDataQuery = new Query().Take(6);\npublic class Record\n{\n public string ID { get; set; }\n public string Text { get; set; }\n}\npublic List<Record> Records { get; set; }\nprotected override void OnInitialized()\n{\n this.Records = Enumerable.Range(1, 5000).Select(i => new Record()\n {\n ID = i.ToString(),\n Text = i.ToString(),\n }).ToList();\n}\n\n\n\nasync Task OnFilter(FilteringEventArgs args)\n{\n if (args.Text.Length >= 4)\n {\n args.PreventDefaultAction = true;\n Query query = new Query().Where(new WhereFilter()\n {\n Field = \"ID\",\n value = args.Text,\n Operator = \"startswith\",\n IgnoreCase = true\n });\n\n await this.DDLObj.FilterAsync(this.Records, query);\n }\n}\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10954203/" ]
74,506,025
<p>I have a list with multiple dataframes say 30,000 and in each dataframe i have multiple columns. the sample list with three dataframes is as follows</p> <pre><code>df1 &lt;- data.frame(ID = c('a', 'a', 'a', 'a','a', 'a'), a = c('a','b','c','d','e','f'), b = c(0,1,2,3,0,5), c= c(11,3,2,4,0,'NA'), d=c(0,2,5,7,'NA',5), e = c(0,5,'NA',3,0,'NA'), f = c(14,7,4,3,'NA',7), g = c(1,2,3,4,5,6), h = c(10,2,13,4,5,6)) df2 &lt;- data.frame(ID = c('b', 'b', 'b', 'b','b', 'b'), a = c('a','b','c','d','e','f'), b = c(0,1,2,3,0,5), c= c(11,3,2,4,0,'NA'), d=c(0,2,15,7,'NA',5), e = c(0,5,'NA',3,0,'NA'), f = c(14,7,4,3,'NA',7), g = c(1,2,3,4,5,6), h = c(10,2,13,4,5,6)) df3 &lt;- data.frame(ID = c('c', 'c', 'c', 'c','c', 'c'), a = c('a','b','c','d','e','f'), b = c(0,1,2,3,0,5), c= c(11,3,2,4,0,'NA'), d=c(0,2,5,27,'NA',5), e = c(0,5,'NA',3,0,'NA'), f = c(14,7,4,3,'NA',7), g = c(1,2,3,4,5,6), h = c(10,2,13,4,5,6)) abc &lt;- list (df1, df2, df3) </code></pre> <p>i would like to find out the maximum value of each dataframe in a list. The final desired output should be in a dataframe as follows</p> <pre><code>abc &lt;- ID Max.Value 'a' 14 'b' 15 'c' 27 </code></pre> <p>I have tried the following codes</p> <pre><code>max(unlist(abc), na.rm = T) </code></pre> <p>using the following code i am getting only maximum/minimum values</p> <pre><code>sapply(abc, function(x) max(x[3:9], na.rm=TRUE)) </code></pre> <p>but i am looking for the desired output as mentioned above</p>
[ { "answer_id": 74506076, "author": "SBMVNO", "author_id": 16702151, "author_profile": "https://Stackoverflow.com/users/16702151", "pm_score": 0, "selected": false, "text": "for (i in 1:length(abc))\n{\n print(max( as.numeric(unlist(abc[[i]])), na.rm=TRUE))\n}\n data.frame(\n ID=sapply(1:length(abc), FUN=function(x) abc[[x]][1,'ID']),\n Max.Value=sapply(1:length(abc), FUN= function(x)max( as.numeric(unlist(abc[[x]])), na.rm=TRUE) )\n )\n" }, { "answer_id": 74506088, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\nbind_rows(abc)%>%\n group_by(ID)%>%\n type_convert()%>%\n summarise(max_value = max(across(where(is.numeric)), na.rm = TRUE))\n\n# A tibble: 3 × 2\n ID max_value\n <chr> <dbl>\n1 a 14\n2 b 15\n3 c 27\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9247629/" ]
74,506,079
<p>I want to remove parenthesis along with all the characters inside it...</p> <pre><code>var str = B.Tech(CSE)2020; print(str.replaceAll(new RegExp('/([()])/g'), ''); // output =&gt; B.Tech(CSE)2020 // output required =&gt; B.Tech 2020 </code></pre> <p>I tried with bunch of Regex but nothing is working...</p> <p>I am using Dart...</p>
[ { "answer_id": 74506139, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "String str = \"B.Tech(CSE)2020\";\nprint(str.replaceAll(RegExp(r'\\(.*?\\)'), \" \")); // B.Tech 2020\n" }, { "answer_id": 74508725, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "/ r * \\([^()]*\\)\n var str = \"B.Tech(CSE)2020\";\nprint(str.replaceAll(new RegExp(r'\\([^()]*\\)'), ' '));\n B.Tech 2020\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15145842/" ]
74,506,084
<pre><code>const user = [ {name:&quot;jonh&quot; ,id:EAD1234}, {name:&quot;peter&quot; ,id:EAD1235}, {name:&quot;matt&quot; ,id:EAD1236}, {name:&quot;henry&quot; ,id:EAD1237}, ] </code></pre> <p>I have above mentioned array of object, I want to get selected user id dynamically based on user selection using es6 and javascript e.g. if i select john i should get EAD1234. and it must suitable on large number of records</p> <p>I tried using filter method</p>
[ { "answer_id": 74506100, "author": "flyingfox", "author_id": 3176419, "author_profile": "https://Stackoverflow.com/users/3176419", "pm_score": 1, "selected": false, "text": "Array.filter() Array.map() mysql redis const user = [\n{name:\"jonh\" ,id:'EAD1234'},\n{name:\"peter\" ,id:'EAD1235'},\n{name:\"matt\" ,id:'EAD1236'},\n{name:\"henry\" ,id:'EAD1237'}\n]\n\nlet id = 'EAD1234'\nlet result = user.filter(u => u.id === id).map(u => u.name)\nconsole.log(result)" }, { "answer_id": 74506151, "author": "Vignesh Ravindran", "author_id": 18230372, "author_profile": "https://Stackoverflow.com/users/18230372", "pm_score": 0, "selected": false, "text": "const user = [\n {name:\"john\" ,id:'EAD1234'},\n {name:\"peter\" ,id:'EAD1235'},\n {name:\"matt\" ,id:'EAD1236'},\n {name:\"henry\" ,id:'EAD1237'},\n];\n\nlet userName = \"john\";\nlet userId = user.filter(user => user.name === userName)[0].name;\n" }, { "answer_id": 74506261, "author": "Jordan Wright", "author_id": 17097798, "author_profile": "https://Stackoverflow.com/users/17097798", "pm_score": 2, "selected": false, "text": "function getUserByID(id, users) {\n for (const u of users) {\n if (u.id === id) {\n return u;\n }\n }\n return null;\n}\n\n function getUserByID(id, users) {\n return users.find((u) => u.id === id) || null;\n}\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729455/" ]
74,506,117
<p>why Null Coalescing is not working with ternary operator. I would expect to get tdy.</p> <pre><code>const test = { todo: { day: 'tdy' } } const filterDayRange = [{ day: 'mon' }] const result = test.todo?.day ?? filterDayRange.length &gt; 0 ? filterDayRange[0].day : 'tdy'; console.log(result) // expected Output: tdy </code></pre> <p><a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBFCm0YF4YG8BQM4gCYgC50tsZcBDATyIHIpdKaSBfDVjUSWAMwEsAbBACcAIlQBK5MAHN4KGAG1MpMlVoBbcE2YBdDFk5IhiAK6CUJFQmgA6KHhAB%20GxUoxHjmH0HxREqbI2-PAyUAAWMAB8MAAM7l4CwmKUkjLwCjE6LlQwtPSMANwc4BAgwUEg0gAUxhBmUACUQA" rel="nofollow noreferrer">Playground link</a></p>
[ { "answer_id": 74506131, "author": "Емил Цоков", "author_id": 4264994, "author_profile": "https://Stackoverflow.com/users/4264994", "pm_score": 0, "selected": false, "text": "const test = {\n todo: { \n day: 'tdy'\n }\n}\n\nconst filterDayRange = [{\n day: 'mon'\n}]\n\n const result =\n test.todo?.day ?? filterDayRange.length > 0 ? 'tdy': filterDayRange[0].day;\n\nconsole.log(result)\n" }, { "answer_id": 74506134, "author": "Sarkar", "author_id": 13741787, "author_profile": "https://Stackoverflow.com/users/13741787", "pm_score": 2, "selected": false, "text": "let result = test.todo?.day ?? (filterDayRange.length > 0 ? filterDayRange[0].day : 'tdy')\n" }, { "answer_id": 74506136, "author": "Ali Sattarzadeh", "author_id": 11434567, "author_profile": "https://Stackoverflow.com/users/11434567", "pm_score": 2, "selected": true, "text": " test.todo?.day ?? (filterDayRange.length > 0 ? filterDayRange[0].day : 'tdy');\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10842900/" ]
74,506,123
<p>When I execute this code the value of <code>ans1</code>, <code>ans2</code> is <code>50002896</code> and <code>50005000</code>.<br /> I know there is some issues with <code>ceil</code> function but was not able to figure out the exact cause.</p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; int main() { long long ans1 = 0, ans2 = 0; for (long long i = 1; i &lt;= 10000; i++) { ans1 = ans1 + ceil((float)i / 1); ans2 = ans2 + i; } cout &lt;&lt; ans1 &lt;&lt; &quot; &quot; &lt;&lt; ans2 &lt;&lt; endl; } </code></pre>
[ { "answer_id": 74506203, "author": "wohlstad", "author_id": 18519921, "author_profile": "https://Stackoverflow.com/users/18519921", "pm_score": 3, "selected": true, "text": "ceil float f1 = 100000000;\nf1++;\nstd::cout << std::to_string(f1) << std::endl;\n 100000000.000000\n double float double f1 = 100000000;\nf1++;\nstd::cout << std::to_string(f1) << std::endl;\n 100000001.000000\n #include <bits/stdc++.h>" }, { "answer_id": 74507267, "author": "Sammed", "author_id": 18139248, "author_profile": "https://Stackoverflow.com/users/18139248", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <iomanip>\nusing namespace std;\n\n// Driver Code\nint main()\n{\n float num1 = 10000.29;\n float num2 = 10000.2;\n\n // Output should be 0.0900000000\n cout << std::setprecision(15)\n << (num1 - num2);\n return 0;\n}\n 0.08984375\n\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12474063/" ]
74,506,124
<p>I am doing email validation for admin registration using JavaScript and save the data to database using PHP. Supposedly, the registration is done only if the email is valid. But when the email evaluates to invalid, the PHP code still run. How do I do it so that when the email is invalid, the PHP won't run.</p> <p>Below is the PHP code to save data to database:</p> <blockquote> <pre><code>&lt;?php include('connection.php'); if(isset($_POST['saveBtn'])) { $name = $_POST['name']; $ic = $_POST['ic']; $email = $_POST['email']; $pass = $_POST['pass']; $dob = $_POST['dob']; $contact = $_POST['contact']; $gender = $_POST['gender']; $des = $_POST['des']; $address = $_POST['address']; // Check if data exist $check = &quot;SELECT * FROM admin WHERE admEmail = '&quot;.$email.&quot;' AND admPassword = '&quot;.$pass.&quot;'&quot;; if(mysqli_num_rows(mysqli_query($connect,$check)) &gt; 0) { ?&gt; &lt;script&gt; alert('This email and password already registered!'); &lt;/script&gt; &lt;?php } else { $insert = &quot;INSERT INTO admin (admName, admIC, admEmail, admPassword, admDOB, admContact, admGender, admDesignation, admAddress, admDateJoin) VALUES ('&quot;.$name.&quot;', '&quot;.$ic.&quot;', '&quot;.$email.&quot;', '&quot;.$pass.&quot;', '&quot;.$dob.&quot;', '&quot;.$contact.&quot;', '&quot;.$gender.&quot;', '&quot;.$des.&quot;', '&quot;.$address.&quot;', NOW())&quot;; if(mysqli_query($connect, $insert)) { ?&gt; &lt;script&gt; alert('Insertion Successful!'); window.close(); window.opener.location.reload(); &lt;/script&gt; &lt;?php } else { ?&gt; &lt;script&gt; alert('Insertion Failed. Try Again!'); &lt;/script&gt; &lt;?php } } } ?&gt; </code></pre> </blockquote> <p>Below is the JS:</p> <pre><code>function validateEmail() { var email = document.addAdminForm.email.value; var validRegex = /^[a-zA-Z0-9.!#$%&amp;'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; if (email.match(validRegex)) { alert(&quot;Valid email address!&quot;); return true; } else { document.getElementById(&quot;email_error&quot;).innerHTML = &quot;Invalid email&quot;; document.addAdminForm.email.focus(); return false; } } </code></pre> <p>Below is the partial HTML form:</p> <pre><code>&lt;form class=&quot;w-100&quot; name=&quot;addAdminForm&quot; method=&quot;POST&quot; onsubmit=&quot;validateEmail(this)&quot; action=&quot;add_admin.php&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col form-group&quot;&gt; &lt;!-- &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt; --&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;email&quot; placeholder=&quot;Email&quot; required&gt; &lt;span class=&quot;error email_error&quot; id=&quot;email_error&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class=&quot;float-right&quot;&gt; &lt;input type=&quot;submit&quot; class=&quot;btn button_primary&quot; value=&quot;Save&quot; name=&quot;saveBtn&quot;&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I expect PHP run when validation is true</p>
[ { "answer_id": 74506218, "author": "Niaho", "author_id": 15283583, "author_profile": "https://Stackoverflow.com/users/15283583", "pm_score": 2, "selected": true, "text": "onsubmit=\"return validateEmail(this)\"\n" }, { "answer_id": 74506251, "author": "Niaho", "author_id": 15283583, "author_profile": "https://Stackoverflow.com/users/15283583", "pm_score": -1, "selected": false, "text": "var validRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$/;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19106554/" ]
74,506,162
<p>anyone can teach me how to use this kind of id in the jquery or js? i was trying to make a function where in if you click a button this table data input will be enabled</p> <pre><code>&lt;td&gt;&lt;input type=&quot;number&quot; disabled name=&quot;qty[]&quot; min=&quot;0&quot; id=&quot;qty_&lt;?php echo $x; ?&gt;&quot; class=&quot;form-control&quot; required onclick=&quot;getTotal(&lt;?php echo $x; ?&gt;)&quot; onkeyup=&quot;getTotal(&lt;?php echo $x; ?&gt;)&quot; value=&quot;&lt;?php echo $val['qty'] ?&gt;&quot; autocomplete=&quot;off&quot;&gt;&lt;/td&gt; </code></pre> <ul> <li>i tried to add a new id like this but i realize that we can not have multiple id in one html element anyone can show me how to use this id=&quot;qty_&quot; to call this id in jquery? i want to call the id to use it to enable and disable when a button click</li> </ul> <p>i tried this when the button is click</p> <pre><code>$('*#my_field').prop( &quot;disabled&quot;, false ); </code></pre> <p>it works because i add a new id but i know html element supose to have a 1 id so how can i use the <code>id=&quot;qty_&lt;?php echo $x; ?&gt;&quot;</code> i tried using it with computation <code>Number($(&quot;#qty_&quot;+row).val());</code> it has <code>+row</code> so how can i use something like this in js or jquery?</p>
[ { "answer_id": 74506218, "author": "Niaho", "author_id": 15283583, "author_profile": "https://Stackoverflow.com/users/15283583", "pm_score": 2, "selected": true, "text": "onsubmit=\"return validateEmail(this)\"\n" }, { "answer_id": 74506251, "author": "Niaho", "author_id": 15283583, "author_profile": "https://Stackoverflow.com/users/15283583", "pm_score": -1, "selected": false, "text": "var validRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$/;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15028880/" ]
74,506,193
<p>Trying to fetch meaning of an entered text from urban dictionary. The problem is that urban dictionary shows several definitions posted by different users. I've used 'importxml' for fetching the first page that shows up when someone searches for a particular word.</p> <p>Now I want this data to be split in different columns so that I can get each definition in seperate column.</p> <p>If we look at the fetched data, at the end of every definition there is &quot;by username month dd,yyyy&quot; string.</p> <p>How can I use this string to split that raw data into definitions in separate columns?</p> <p>Tried RegEx but could not figure it out because this is the first time I'm using Regex.</p>
[ { "answer_id": 74506218, "author": "Niaho", "author_id": 15283583, "author_profile": "https://Stackoverflow.com/users/15283583", "pm_score": 2, "selected": true, "text": "onsubmit=\"return validateEmail(this)\"\n" }, { "answer_id": 74506251, "author": "Niaho", "author_id": 15283583, "author_profile": "https://Stackoverflow.com/users/15283583", "pm_score": -1, "selected": false, "text": "var validRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$/;\n" } ]
2022/11/20
[ "https://Stackoverflow.com/questions/74506193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12141436/" ]