qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,373,477
<p>dummy code:</p> <pre><code>void fun() { while (m-&gt;hasMessage()) { std::pair&lt;std::string, Vector&gt; msg_pair = m-&gt;getMessage(); auto topic = msg_pair.first; auto msg = msg_pair.second; for (auto const&amp; x : msg) { auto const type = m-&gt;MessageType(x); if (type == &quot;a&quot;) { funa(x,topic); } else if (type == &quot;b&quot;) { funb(x,topic); } else if (type == &quot;c&quot;) { func(x,topic); } } } } </code></pre> <p>fun a,fun b , fun c are private functions and fun is public function of same class how to test function fun using google test</p>
[ { "answer_id": 74375515, "author": "Ingo Kegel", "author_id": 936832, "author_profile": "https://Stackoverflow.com/users/936832", "pm_score": 2, "selected": true, "text": "class ApiUser {\n Listener listener;\n void registerListener() {\n listener = new Listener() {\n @Override\n public void event() {\n // TODO\n }\n };\n Api.registerListener(listener);\n }\n}\n\nclass Api {\n static WeakHashMap<Listener, Object> listeners = new WeakHashMap<>();\n static void registerListener(Listener listener) {\n listeners.put(listener, null);\n } \n\n static void fireListeners() {\n for (Listener listener : listeners.keySet()) {\n if (listener != null) {\n listener.event();\n }\n }\n }\n}\n\ninterface Listener {\n void event();\n}\n" }, { "answer_id": 74386184, "author": "Holger", "author_id": 2711488, "author_profile": "https://Stackoverflow.com/users/2711488", "pm_score": 2, "selected": false, "text": "WeakHashMap" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457918/" ]
74,373,499
<p>I have a set of 50 vectors and would like to create a dataframe from those 50 vectors values and their names as the following example.</p> <p><strong>Example with 3 vector, but reality is about 50 vectors.</strong></p> <pre><code>vector_a&lt;- c(&quot;a1&quot;,&quot;a2&quot;, &quot;a3&quot;,&quot;a4&quot;) vector_cx&lt;- c(&quot;1&quot;,&quot;2&quot;,&quot;3&quot;) vector_3 &lt;-c(&quot;x1&quot;,&quot;x2&quot;) </code></pre> <p><strong>Expected result.</strong></p> <pre><code>data.frame(values=c(&quot;a1&quot;,&quot;a2&quot;, &quot;a3&quot;,&quot;a4&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;x1&quot;,&quot;x2&quot;), vector_names=c(&quot;vector_a&quot;,&quot;vector_a&quot;, &quot;vector_a&quot;,&quot;vector_a&quot;,&quot;vector_cx&quot;,&quot;vector_cx&quot;,&quot;vector_cx&quot;,&quot;vector_3&quot;,&quot;vector_3&quot;)) </code></pre> <p><strong>The code above produces the following table.</strong></p> <pre><code> values vector_names 1 a1 vector_a 2 a2 vector_a 3 a3 vector_a 4 a4 vector_a 5 1 vector_cx 6 2 vector_cx 7 3 vector_cx 8 x1 vector_3 9 x2 vector_3 </code></pre>
[ { "answer_id": 74373841, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 3, "selected": true, "text": "stack(mget(ls(pattern = \"^vector_\")))\n# values ind\n# 1 x1 vector_3\n# 2 x2 vector_3\n# 3 a1 vector_a\n# 4 a2 vector_a\n# 5 a3 vector_a\n# 6 a4 vector_a\n# 7 1 vector_cx\n# 8 2 vector_cx\n# 9 3 vector_cx\n" }, { "answer_id": 74373883, "author": "Hansel Palencia", "author_id": 10897981, "author_profile": "https://Stackoverflow.com/users/10897981", "pm_score": 1, "selected": false, "text": "purrr" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9503697/" ]
74,373,523
<p>I have a list of dictionaries shaped like this:</p> <pre><code>[{'country': 'Afghanistan', 'continent': 'Asia', '1990': 500, '1990_lower': 200, '1990_upper': 1000, '1991': 500, '1991_lower': 200, '1991_upper': 1000, '1992': 500, '1992_lower': 200, '1992_upper': 1000, '1993': 1000, '1993_lower': 500, '1993_upper': 1100, '1994': 1000, '1994_lower': 500, '1994_upper': 1300, '1995': 1000, '1995_lower': 500, '1995_upper': 1600, '1996': 1000, '1996_lower': 500, '1996_upper': 1900, '1997': 1000, '1997_lower': 500, '1997_upper': 2100, '1998': 1200, '1998_lower': 1000, '1998_upper': 2500, '1999': 1300, '1999_lower': 1000, '1999_upper': 3000, '2000': 1500, '2000_lower': 1000, '2000_upper': 3600, '2001': 1800, '2001_lower': 1000, '2001_upper': 4100, '2002': 2000, '2002_lower': 1100, '2002_upper': 4800, '2003': 2300, '2003_lower': 1300, '2003_upper': 5700, '2004': 2600, '2004_lower': 1400, '2004_upper': 7000, '2005': 2900, '2005_lower': 1500, '2005_upper': 7200, '2006': 3200, '2006_lower': 1700, '2006_upper': 7900, '2007': 3500, '2007_lower': 1800, '2007_upper': 8300, '2008': 3800, '2008_lower': 2000, '2008_upper': 8900, '2009': 4200, '2009_lower': 2100, '2009_upper': 9600, '2010': 4600, '2010_lower': 2300, '2010_upper': 11000, '2011': 5100, '2011_lower': 2500, '2011_upper': 12000, '2012': 5600, '2012_lower': 2700, '2012_upper': 14000, '2013': 6300, '2013_lower': 3100, '2013_upper': 16000, '2014': 6900, '2014_lower': 3300, '2014_upper': 18000, '2015': 7600, '2015_lower': 3600, '2015_upper': 21000, '2016': 8400, '2016_lower': 3900, '2016_upper': 24000, '2017': 9200, '2017_lower': 4100, '2017_upper': 28000, '2018': 10000, '2018_lower': 4300, '2018_upper': 33000, '2019': 11000, '2019_lower': 4500, '2019_upper': 38000, '2020': 12000, '2020_lower': 4700, '2020_upper': 43000}, {'country': 'Albania', 'continent': 'Europe', '1990': 100, '1990_lower': 100, '1990_upper': 100, '1991': 100, '1991_lower': 100, '1991_upper': 100, '1992': 100, '1992_lower': 100, '1992_upper': 100, '1993': 100, '1993_lower': 100, '1993_upper': 100, '1994': 100, '1994_lower': 100, '1994_upper': 100, '1995': 100, '1995_lower': 100, '1995_upper': 100, '1996': 100, '1996_lower': 100, '1996_upper': 100, '1997': 100, '1997_lower': 100, '1997_upper': 100, '1998': 100, '1998_lower': 100, '1998_upper': 100, '1999': 100, '1999_lower': 100, '1999_upper': 200, '2000': 100, '2000_lower': 100, '2000_upper': 200, '2001': 200, '2001_lower': 100, '2001_upper': 200, '2002': 200, '2002_lower': 200, '2002_upper': 200, '2003': 200, '2003_lower': 200, '2003_upper': 500, '2004': 500, '2004_lower': 200, '2004_upper': 500, '2005': 500, '2005_lower': 500, '2005_upper': 500, '2006': 500, '2006_lower': 500, '2006_upper': 500, '2007': 500, '2007_lower': 500, '2007_upper': 500, '2008': 500, '2008_lower': 500, '2008_upper': 1000, '2009': 1000, '2009_lower': 500, '2009_upper': 1000, '2010': 1000, '2010_lower': 1000, '2010_upper': 1000, '2011': 1000, '2011_lower': 1000, '2011_upper': 1000, '2012': 1000, '2012_lower': 1000, '2012_upper': 1000, '2013': 1000, '2013_lower': 1000, '2013_upper': 1000, '2014': 1000, '2014_lower': 1000, '2014_upper': 1100, '2015': 1100, '2015_lower': 1000, '2015_upper': 1200, '2016': 1200, '2016_lower': 1000, '2016_upper': 1300, '2017': 1300, '2017_lower': 1100, '2017_upper': 1400, '2018': 1300, '2018_lower': 1100, '2018_upper': 1500, '2019': 1400, '2019_lower': 1200, '2019_upper': 1600, '2020': 1400, '2020_lower': 1200, '2020_upper': 1700}, {'country': 'Algeria', 'continent': 'Africa', '1990': 500, '1990_lower': 500, '1990_upper': 500, '1991': 500, '1991_lower': 500, '1991_upper': 1000, '1992': 1000, '1992_lower': 500, '1992_upper': 1000, '1993': 1000, '1993_lower': 1000, '1993_upper': 1000, '1994': 1000, '1994_lower': 1000, '1994_upper': 1000, '1995': 1000, '1995_lower': 1000, '1995_upper': 1100, '1996': 1100, '1996_lower': 1000, '1996_upper': 1200, '1997': 1300, '1997_lower': 1100, '1997_upper': 1400, '1998': 1500, '1998_lower': 1300, '1998_upper': 1600, '1999': 1700, '1999_lower': 1500, '1999_upper': 1900, '2000': 2000, '2000_lower': 1800, '2000_upper': 2200, '2001': 2200, '2001_lower': 2000, '2001_upper': 2500, '2002': 2500, '2002_lower': 2300, '2002_upper': 2800, '2003': 2800, '2003_lower': 2600, '2003_upper': 3200, '2004': 3200, '2004_lower': 2900, '2004_upper': 3500, '2005': 3500, '2005_lower': 3200, '2005_upper': 3900, '2006': 3900, '2006_lower': 3600, '2006_upper': 4300, '2007': 4300, '2007_lower': 4000, '2007_upper': 4700, '2008': 4700, '2008_lower': 4400, '2008_upper': 5100, '2009': 5200, '2009_lower': 4800, '2009_upper': 5600, '2010': 5800, '2010_lower': 5300, '2010_upper': 6200, '2011': 6500, '2011_lower': 5900, '2011_upper': 7000, '2012': 7300, '2012_lower': 6700, '2012_upper': 7900, '2013': 8200, '2013_lower': 7500, '2013_upper': 8900, '2014': 9400, '2014_lower': 8700, '2014_upper': 10000, '2015': 11000, '2015_lower': 10000, '2015_upper': 12000, '2016': 12000, '2016_lower': 11000, '2016_upper': 14000, '2017': 14000, '2017_lower': 13000, '2017_upper': 15000, '2018': 15000, '2018_lower': 14000, '2018_upper': 17000, '2019': 17000, '2019_lower': 16000, '2019_upper': 18000, '2020': 18000, '2020_lower': 17000, '2020_upper': 20000}, {'country': 'Angola', 'continent': 'Africa', '1990': 12000, '1990_lower': 6200, '1990_upper': 22000, '1991': 15000, '1991_lower': 8500, '1991_upper': 26000, '1992': 20000, '1992_lower': 12000, '1992_upper': 32000, '1993': 25000, '1993_lower': 16000, '1993_upper': 39000, '1994': 31000, '1994_lower': 20000, '1994_upper': 46000, '1995': 38000, '1995_lower': 26000, '1995_upper': 56000, '1996': 46000, '1996_lower': 33000, '1996_upper': 66000, '1997': 56000, '1997_lower': 41000, '1997_upper': 78000, '1998': 67000, '1998_lower': 49000, '1998_upper': 90000, '1999': 79000, '1999_lower': 60000, '1999_upper': 100000, '2000': 92000, '2000_lower': 70000, '2000_upper': 120000, '2001': 110000, '2001_lower': 83000, '2001_upper': 130000, '2002': 120000, '2002_lower': 97000, '2002_upper': 150000, '2003': 140000, '2003_lower': 110000, '2003_upper': 170000, '2004': 150000, '2004_lower': 120000, '2004_upper': 190000, '2005': 170000, '2005_lower': 140000, '2005_upper': 200000, '2006': 190000, '2006_lower': 150000, '2006_upper': 220000, '2007': 200000, '2007_lower': 160000, '2007_upper': 240000, '2008': 220000, '2008_lower': 180000, '2008_upper': 260000, '2009': 230000, '2009_lower': 190000, '2009_upper': 270000, '2010': 250000, '2010_lower': 200000, '2010_upper': 290000, '2011': 260000, '2011_lower': 210000, '2011_upper': 310000, '2012': 270000, '2012_lower': 220000, '2012_upper': 320000, '2013': 290000, '2013_lower': 240000, '2013_upper': 330000, '2014': 300000, '2014_lower': 250000, '2014_upper': 340000, '2015': 310000, '2015_lower': 260000, '2015_upper': 360000, '2016': 320000, '2016_lower': 270000, '2016_upper': 370000, '2017': 320000, '2017_lower': 270000, '2017_upper': 380000, '2018': 330000, '2018_lower': 280000, '2018_upper': 390000, '2019': 340000, '2019_lower': 280000, '2019_upper': 390000, '2020': 340000, '2020_lower': 280000, '2020_upper': 400000}, {'country': 'Argentina', 'continent': 'America', '1990': 13000, '1990_lower': 10000, '1990_upper': 15000, '1991': 18000, '1991_lower': 15000, '1991_upper': 21000, '1992': 23000, '1992_lower': 20000, '1992_upper': 27000, '1993': 29000, '1993_lower': 25000, '1993_upper': 33000, '1994': 34000, '1994_lower': 30000, '1994_upper': 38000, '1995': 39000, '1995_lower': 34000, '1995_upper': 44000, '1996': 43000, '1996_lower': 38000, '1996_upper': 48000, '1997': 47000, '1997_lower': 42000, '1997_upper': 52000, '1998': 51000, '1998_lower': 45000, '1998_upper': 56000, '1999': 55000, '1999_lower': 49000, '1999_upper': 60000, '2000': 59000, '2000_lower': 53000, '2000_upper': 64000, '2001': 64000, '2001_lower': 57000, '2001_upper': 69000, '2002': 68000, '2002_lower': 61000, '2002_upper': 73000, '2003': 72000, '2003_lower': 65000, '2003_upper': 77000, '2004': 76000, '2004_lower': 69000, '2004_upper': 82000, '2005': 80000, '2005_lower': 73000, '2005_upper': 86000, '2006': 84000, '2006_lower': 76000, '2006_upper': 90000, '2007': 88000, '2007_lower': 80000, '2007_upper': 94000, '2008': 92000, '2008_lower': 84000, '2008_upper': 98000, '2009': 96000, '2009_lower': 88000, '2009_upper': 100000, '2010': 100000, '2010_lower': 92000, '2010_upper': 110000, '2011': 100000, '2011_lower': 95000, '2011_upper': 110000, '2012': 110000, '2012_lower': 99000, '2012_upper': 120000, '2013': 110000, '2013_lower': 100000, '2013_upper': 120000, '2014': 120000, '2014_lower': 110000, '2014_upper': 130000, '2015': 120000, '2015_lower': 110000, '2015_upper': 130000, '2016': 120000, '2016_lower': 110000, '2016_upper': 130000, '2017': 130000, '2017_lower': 120000, '2017_upper': 140000, '2018': 130000, '2018_lower': 120000, '2018_upper': 140000, '2019': 140000, '2019_lower': 120000, '2019_upper': 150000, '2020': 140000, '2020_lower': 130000, '2020_upper': 150000}, {'country': 'Armenia', 'continent': 'Europe', '1990': 100, '1990_lower': 100, '1990_upper': 100, '1991': 100, '1991_lower': 100, '1991_upper': 100, '1992': 100, '1992_lower': 100, '1992_upper': 100, '1993': 100, '1993_lower': 100, '1993_upper': 200, '1994': 100, '1994_lower': 100, '1994_upper': 500, '1995': 200, '1995_lower': 100, '1995_upper': 500, '1996': 200, '1996_lower': 100, '1996_upper': 1000, '1997': 500, '1997_lower': 200, '1997_upper': 1200, '1998': 500, '1998_lower': 500, '1998_upper': 1700, '1999': 1000, '1999_lower': 500, '1999_upper': 2200, '2000': 1100, '2000_lower': 1000, '2000_upper': 2600, '2001': 1500, '2001_lower': 1000, '2001_upper': 3000, '2002': 1900, '2002_lower': 1200, '2002_upper': 3300, '2003': 2400, '2003_lower': 1700, '2003_upper': 3900, '2004': 2800, '2004_lower': 2100, '2004_upper': 4300, '2005': 3200, '2005_lower': 2500, '2005_upper': 4500, '2006': 3500, '2006_lower': 2800, '2006_upper': 4700, '2007': 3700, '2007_lower': 3100, '2007_upper': 4800, '2008': 3800, '2008_lower': 3200, '2008_upper': 4900, '2009': 3800, '2009_lower': 3200, '2009_upper': 4800, '2010': 3900, '2010_lower': 3300, '2010_upper': 4800, '2011': 3900, '2011_lower': 3300, '2011_upper': 4800, '2012': 3900, '2012_lower': 3400, '2012_upper': 4700, '2013': 3900, '2013_lower': 3400, '2013_upper': 4600, '2014': 3900, '2014_lower': 3500, '2014_upper': 4600, '2015': 4000, '2015_lower': 3500, '2015_upper': 4600, '2016': 4100, '2016_lower': 3600, '2016_upper': 4700, '2017': 4200, '2017_lower': 3700, '2017_upper': 4800, '2018': 4400, '2018_lower': 3900, '2018_upper': 5000, '2019': 4500, '2019_lower': 4000, '2019_upper': 5300, '2020': 4800, '2020_lower': 4200, '2020_upper': 5600}, {'country': 'Australia', 'continent': 'Oceania', '1990': 9800, '1990_lower': 7800, '1990_upper': 12000, '1991': 11000, '1991_lower': 8400, '1991_upper': 13000, '1992': 11000, '1992_lower': 8800, '1992_upper': 13000, '1993': 11000, '1993_lower': 9100, '1993_upper': 14000, '1994': 12000, '1994_lower': 9300, '1994_upper': 14000, '1995': 12000, '1995_lower': 9300, '1995_upper': 14000, '1996': 12000, '1996_lower': 9300, '1996_upper': 14000, '1997': 12000, '1997_lower': 9700, '1997_upper': 14000, '1998': 13000, '1998_lower': 10000, '1998_upper': 15000, '1999': 13000, '1999_lower': 11000, '1999_upper': 16000, '2000': 14000, '2000_lower': 11000, '2000_upper': 16000, '2001': 14000, '2001_lower': 12000, '2001_upper': 17000, '2002': 15000, '2002_lower': 12000, '2002_upper': 17000, '2003': 16000, '2003_lower': 13000, '2003_upper': 18000, '2004': 16000, '2004_lower': 13000, '2004_upper': 18000, '2005': 17000, '2005_lower': 14000, '2005_upper': 19000, '2006': 17000, '2006_lower': 14000, '2006_upper': 20000, '2007': 18000, '2007_lower': 15000, '2007_upper': 20000, '2008': 19000, '2008_lower': 16000, '2008_upper': 21000, '2009': 20000, '2009_lower': 16000, '2009_upper': 22000, '2010': 21000, '2010_lower': 17000, '2010_upper': 23000, '2011': 22000, '2011_lower': 18000, '2011_upper': 24000, '2012': 23000, '2012_lower': 19000, '2012_upper': 25000, '2013': 24000, '2013_lower': 19000, '2013_upper': 27000, '2014': 25000, '2014_lower': 20000, '2014_upper': 28000, '2015': 26000, '2015_lower': 21000, '2015_upper': 29000, '2016': 26000, '2016_lower': 22000, '2016_upper': 30000, '2017': 27000, '2017_lower': 22000, '2017_upper': 31000, '2018': 28000, '2018_lower': 23000, '2018_upper': 32000, '2019': 29000, '2019_lower': 23000, '2019_upper': 33000, '2020': 30000, '2020_lower': 24000, '2020_upper': 34000}, {'country': 'Austria', 'continent': 'Europe', '1990': -1, '1990_lower': -1, '1990_upper': -1, '1991': -1, '1991_lower': -1, '1991_upper': -1, '1992': -1, '1992_lower': -1, '1992_upper': -1, '1993': -1, '1993_lower': -1, '1993_upper': -1, '1994': -1, '1994_lower': -1, '1994_upper': -1, '1995': -1, '1995_lower': -1, '1995_upper': -1, '1996': -1, '1996_lower': -1, '1996_upper': -1, '1997': -1, '1997_lower': -1, '1997_upper': -1, '1998': -1, '1998_lower': -1, '1998_upper': -1, '1999': -1, '1999_lower': -1, '1999_upper': -1, '2000': -1, '2000_lower': -1, '2000_upper': -1, '2001': -1, '2001_lower': -1, '2001_upper': -1, '2002': -1, '2002_lower': -1, '2002_upper': -1, '2003': -1, '2003_lower': -1, '2003_upper': -1, '2004': -1, '2004_lower': -1, '2004_upper': -1, '2005': -1, '2005_lower': -1, '2005_upper': -1, '2006': -1, '2006_lower': -1, '2006_upper': -1, '2007': -1, '2007_lower': -1, '2007_upper': -1, '2008': -1, '2008_lower': -1, '2008_upper': -1, '2009': -1, '2009_lower': -1, '2009_upper': -1, '2010': -1, '2010_lower': -1, '2010_upper': -1, '2011': -1, '2011_lower': -1, '2011_upper': -1, '2012': -1, '2012_lower': -1, '2012_upper': -1, '2013': -1, '2013_lower': -1, '2013_upper': -1, '2014': -1, '2014_lower': -1, '2014_upper': -1, '2015': -1, '2015_lower': -1, '2015_upper': -1, '2016': -1, '2016_lower': -1, '2016_upper': -1, '2017': -1, '2017_lower': -1, '2017_upper': -1, '2018': -1, '2018_lower': -1, '2018_upper': -1, '2019': -1, '2019_lower': -1, '2019_upper': -1, '2020': -1, '2020_lower': -1, '2020_upper': -1}, </code></pre> <p>I'm trying to write a function that looks through this list of dictionaries called dataset, and creates a new dictionary where the keys are all the continents that are in the dataset, and the values are nested dictionaries where the years are the keys (1990, 2020). The upper and lower are just estimations, and can be ignored in this problem. The values of this nested dictionary are the amount of cases per continent. My current code looks like this:</p> <pre class="lang-py prettyprint-override"><code>def compute_cases_per_continent(): final_dict: dict = {} years: list = [] cases: list = [] for i in range(1990,2021): years.append(i) cases.append(0) years_cases: dict = dict(zip(years,cases)) for i in dataset: if i['continent'] not in final_dict: final_dict.update({i['continent']: years_cases}) for dictionary in dataset: if dictionary['continent'] in final_dict.keys(): for x in years: years_cases[x] += dictionary[x] print(final_dict) </code></pre> <p>But I am currently getting the following error;</p> <pre class="lang-py prettyprint-override"><code>--------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-29-1c63542122fe&gt; in &lt;module&gt; 18 #// END_TODO [3.a_sub-saharan_africa] 19 ---&gt; 20 compute_cases_per_continent() &lt;ipython-input-29-1c63542122fe&gt; in compute_cases_per_continent() 14 if dictionary['continent'] in final_dict.keys(): 15 for x in years: ---&gt; 16 years_cases[x] += dictionary[x] 17 print(final_dict) 18 #// END_TODO [3.a_sub-saharan_africa] KeyError: 1990 </code></pre> <p>I tried the code above, but I do not really see what to change to make it work like it should.</p>
[ { "answer_id": 74373672, "author": "EEtch", "author_id": 14912887, "author_profile": "https://Stackoverflow.com/users/14912887", "pm_score": 2, "selected": true, "text": "years_cases[x] += dictionary[x]" }, { "answer_id": 74373954, "author": "imburningbabe", "author_id": 17781468, "author_profile": "https://Stackoverflow.com/users/17781468", "pm_score": 0, "selected": false, "text": "final_dict = {}\n\nfor el in dataset:\n final_dict[el['country']] = {k:v for k,v in el.items() if k.isdigit()}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20323201/" ]
74,373,536
<p>I am creating a React.js DApp which will interact with <a href="https://developers.rsk.co/" rel="noreferrer">Rootstock (RSK)</a> deployed smart contracts. Recently I came across a React library called <a href="https://usedapp-docs.netlify.app/docs/" rel="noreferrer">useDApp</a>. This library automates the blockchain connection, smart contract interaction and sending transactions by using React hooks and context providers. ​ For example:</p> <pre class="lang-js prettyprint-override"><code>const { activateBrowserWallet, account } = useEthers(); const etherBalance = useEtherBalance(account); </code></pre> <p>​ However, I don't see Rootstock among the <a href="https://github.com/TrueFiEng/useDApp/tree/master/packages/core/src/model/chain" rel="noreferrer">supported networks</a>. ​</p> <p>I have tried to create a Rootstock configuration as <a href="https://usedapp-docs.netlify.app/docs/#example" rel="noreferrer">described in the docs</a>: ​</p> <pre class="lang-js prettyprint-override"><code>const config = { readOnlyChainId: 30, readOnlyUrls: { 31: 'https://public-node.testnet.rsk.co', 30: 'https://public-node.rsk.co', }, }; </code></pre> <p>​ Unfortunately, adding the above appears to be insufficient, and I was unable to connect to either RSK Mainnet nor RSK Testnet.</p> <p>Is it possible <a href="https://usedapp-docs.netlify.app/docs/API%20Reference/Models#config" rel="noreferrer">to configure</a> useDApp to connect to Rootstock?</p>
[ { "answer_id": 74374298, "author": "bguiz", "author_id": 194982, "author_profile": "https://Stackoverflow.com/users/194982", "pm_score": 3, "selected": false, "text": "const rootstockTestnetExplorerUrl = 'https://explorer.testnet.rsk.co/';\n\nexport const RootstockTestnet = {\n chainId: 31,\n chainName: 'Rootstock Testnet',\n isTestChain: true,\n isLocalChain: false,\n rpcUrl: 'https://public-node.testnet.rsk.co',\n // deployed at https://explorer.testnet.rsk.co/address/0xca11bde05977b3631167028862be2a173976ca11\n multicallAddress: '0xcA11bde05977b3631167028862bE2a173976CA11',\n nativeCurrency: {\n name: 'Test Rootstock Bitcoin',\n symbol: 'tRBTC',\n decimals: 18,\n },\n getExplorerAddressLink: getAddressLink(rootstockTestnetExplorerUrl),\n getExplorerTransactionLink: getTransactionLink(rootstockTestnetExplorerUrl),\n};\n\nconst rootstockMainnetExplorerUrl = 'https://explorer.rsk.co/';\n\nexport const RootstockMainnet = {\n chainId: 30,\n chainName: 'Rootstock Mainnet',\n isTestChain: false,\n isLocalChain: false,\n rpcUrl: 'https://public-node.rsk.co',\n // deployed at https://explorer.rsk.co/address/0xca11bde05977b3631167028862be2a173976ca11\n multicallAddress: '0xcA11bde05977b3631167028862bE2a173976CA11',\n nativeCurrency: {\n name: 'Rootstock Bitcoin',\n symbol: 'RBTC',\n decimals: 18,\n },\n getExplorerAddressLink: getAddressLink(rootstockMainnetExplorerUrl),\n getExplorerTransactionLink: getTransactionLink(rootstockMainnetExplorerUrl),\n};\n" }, { "answer_id": 74402014, "author": "Jesse Clark", "author_id": 2218156, "author_profile": "https://Stackoverflow.com/users/2218156", "pm_score": 2, "selected": false, "text": "yarn add @rsksmart/rlogin\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18620436/" ]
74,373,561
<p>I'm trying to transform a string that contains a dict to a dict object using json. But in the data contains a &quot; example</p> <pre><code>string = '{&quot;key1&quot;:&quot;my&quot;value&quot;,&quot;key2&quot;:&quot;my&quot;value2&quot;}' js = json.loads(s,strict=False) </code></pre> <p>it outputs json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 13 (char 12) as &quot; is a delimiter and there is too much of it</p> <p>What is the best way to achieve my goal ?</p> <p>The solution I have found is to perform several .replace on the string to replace legit &quot; by a pattern until only illgal &quot; remains then replace back the pattern by the legit &quot; After that I can use json.loads and then replace the remaining pattern by the illegal &quot; But there must be another way</p> <p>ex :</p> <pre><code>string = '{&quot;key1&quot;:&quot;my&quot;value&quot;,&quot;key2&quot;:&quot;my&quot;value2&quot;}' string = string.replace('{&quot;','__pattern_1') string = string.replace('}&quot;','__pattern_2') ... ... string = string.replace('&quot;','__pattern_42') string = string.replace('__pattern_1','{&quot;') string = string.replace('__pattern_2','}&quot;') ... ... js = json.loads(s,strict=False) </code></pre>
[ { "answer_id": 74373767, "author": "ChamRun", "author_id": 14761615, "author_profile": "https://Stackoverflow.com/users/14761615", "pm_score": 0, "selected": false, "text": "string" }, { "answer_id": 74373919, "author": "jrudolf", "author_id": 6113285, "author_profile": "https://Stackoverflow.com/users/6113285", "pm_score": 0, "selected": false, "text": "'{\"key1\": \"my\"value\", \"key2\": \"my\"value2\"}'" }, { "answer_id": 74374650, "author": "Rohan Chavan", "author_id": 20458336, "author_profile": "https://Stackoverflow.com/users/20458336", "pm_score": 1, "selected": false, "text": "import re\nimport json\n\ndef fix_json_string(st):\n st = re.sub(r'\",\"',\"!!\",st)\n st = re.sub(r'\":\"',\"--\",st)\n st = re.sub(r'{\"',\"{{\",st)\n st = re.sub(r'\"}',\"}}\",st)\n st = st.replace('\"','')\n st = re.sub(r'}}','\"}',st)\n st = re.sub(r'{{','{\"',st)\n st = re.sub(r'--','\":\"',st)\n st = re.sub(r'!!','\",\"',st)\n return st\n\nbroken_string = '{\"key1\":\"my\"value\",\"key2\":\"my\"value2\"}'\nfixed_string = fix_json_string(broken_string)\nprint(fixed_string)\njs = json.dumps(eval(fixed_string))\nprint(js)\n\n\nOutput -\n{\"key1\":\"myvalue\",\"key2\":\"myvalue2\"} # str\n{\"key1\": \"myvalue\", \"key2\": \"myvalue2\"} # converted to json\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458141/" ]
74,373,582
<p>Having a dataframe like this:</p> <pre><code>structure(list(id = c(1, 2, 3), date1 = c(13, 9, 0), date2 = c(17L, 13L, 17L)), row.names = c(NA, -3L), class = &quot;data.frame&quot;) </code></pre> <p>How is it possible to check if a row has different numbers than 0 or/and 17 and keep them into a new dataframe (excluding id column)?</p> <p>Example expected output</p> <pre><code> id date1 date2 1 13 17 2 9 13 </code></pre>
[ { "answer_id": 74373767, "author": "ChamRun", "author_id": 14761615, "author_profile": "https://Stackoverflow.com/users/14761615", "pm_score": 0, "selected": false, "text": "string" }, { "answer_id": 74373919, "author": "jrudolf", "author_id": 6113285, "author_profile": "https://Stackoverflow.com/users/6113285", "pm_score": 0, "selected": false, "text": "'{\"key1\": \"my\"value\", \"key2\": \"my\"value2\"}'" }, { "answer_id": 74374650, "author": "Rohan Chavan", "author_id": 20458336, "author_profile": "https://Stackoverflow.com/users/20458336", "pm_score": 1, "selected": false, "text": "import re\nimport json\n\ndef fix_json_string(st):\n st = re.sub(r'\",\"',\"!!\",st)\n st = re.sub(r'\":\"',\"--\",st)\n st = re.sub(r'{\"',\"{{\",st)\n st = re.sub(r'\"}',\"}}\",st)\n st = st.replace('\"','')\n st = re.sub(r'}}','\"}',st)\n st = re.sub(r'{{','{\"',st)\n st = re.sub(r'--','\":\"',st)\n st = re.sub(r'!!','\",\"',st)\n return st\n\nbroken_string = '{\"key1\":\"my\"value\",\"key2\":\"my\"value2\"}'\nfixed_string = fix_json_string(broken_string)\nprint(fixed_string)\njs = json.dumps(eval(fixed_string))\nprint(js)\n\n\nOutput -\n{\"key1\":\"myvalue\",\"key2\":\"myvalue2\"} # str\n{\"key1\": \"myvalue\", \"key2\": \"myvalue2\"} # converted to json\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20224217/" ]
74,373,594
<p>I need help in working with big Excel Tables.</p> <h3>Description</h3> <hr /> <p>I have an export of Data from our ERP System that has 400K Rows at least. In this report the format is quite messed up and I want to write a script that will clean up all the data.</p> <p>I started to write little sub just to delete empty rows and such that have a special behavior. please see below:</p> <pre><code>Sub Main() OptimizeVBA (True) DeleteLastRows OptimizeVBA (False) End Sub Sub DeleteLastRows() 'Achtung, diese Funktion dauert sehr lange Dim total total = ActiveSheet.UsedRange.Rows.Count Dim Tim1 As Single Tim1 = Timer For i = total To total - 100 Step -1 If ThatSpecialLine(&quot;0&quot;, i, 1, 9) Then 'DeleteRow (i) Rows(i).EntireRow.Delete ElseIf EmptyRow(i, 1, 13) Then 'DeleteRow (i) Rows(i).EntireRow.Delete End If Next Tim1 = Timer - Tim1 MsgBox (&quot;Anzahl der Zeilen nach der Bearbeitung: &quot; &amp; ActiveSheet.UsedRange.Rows.Count &amp; vbNewLine &amp; &quot;Dafür wurde: &quot; &amp; Tim1 &amp; &quot; gebraucht&quot;) End Sub Function EmptyRow(ByVal Row As Long, ByVal startc As Integer, ByVal EndC As Integer) As Boolean EmptyRow = True Dim temp As String For i = startc To EndC temp = Cells(Row, i).Value temp = Trim(temp) If temp &lt;&gt; &quot;&quot; Then EmptyRow = False Exit Function End If Next End Function Function ThatSpecialLine(ByVal val As String, ByVal Row As Long, ByVal startc As Integer, ByVal EndC As Integer) As Boolean ThatSpecialLine = False If EmptyRow(Row, startc, EndC) Then If Cells(Row, EndC + 1).Value = val Then ThatSpecialLine = True End If End If End Function Sub OptimizeVBA(isOn As Boolean) Application.Calculation = IIf(isOn, xlCalculationManual, xlCalculationAutomatic) Application.EnableEvents = Not (isOn) Application.ScreenUpdating = Not (isOn) ActiveSheet.DisplayPageBreaks = Not (isOn) End Sub </code></pre> <p>This code needs about 14 seconds to execute for just 100 lines. I am wondering why the performance is so bad. I have no experience in making an application performance optimizing so please be kind if my question is very stupid :).</p> <h3>Questions</h3> <hr /> <ol> <li>Would it be better / faster to export this .xlsx file to .txt file and process with a programm i write in Visual studio with vb.net or C#? this would be my next idea.</li> <li>How to improve my vba code?</li> </ol> <p>Would it be better / faster to export this .xlsx file to .txt file and process with a programm i write in Visual studio with vb.net or C#? this would be my next idea.</p> <p>Thanks in advance</p>
[ { "answer_id": 74377140, "author": "FunThomas", "author_id": 7599798, "author_profile": "https://Stackoverflow.com/users/7599798", "pm_score": 3, "selected": true, "text": "Sub DeleteLastRows()\n Const DeleteChunkSize = 1000\n \n Dim lastRow As Long\n With ThisWorkbook.Sheets(1)\n lastRow = .Cells(.Rows.Count, \"A\").End(xlUp).row\n \n ' Read all Data into Memory\n Dim AllData As Variant\n AllData = .Range(.Cells(1, 1), .Cells(lastRow, 13))\n Debug.Print \"data read\"\n Dim row As Long\n For row = lastRow To 2 Step -1\n If row Mod 100 = 0 Then DoEvents\n Dim deleteRange As Range, deleteCount As Long\n \n Dim toBeDeleted As Boolean\n toBeDeleted = ThatSpecialLine(AllData, \"0\", row, 1, 9) Or EmptyRow(AllData, row, 1, 13)\n If toBeDeleted Then\n deleteCount = deleteCount + 1\n If deleteRange Is Nothing Then\n Set deleteRange = .Cells(row, 1).EntireRow\n Else\n Set deleteRange = Union(deleteRange, .Cells(row, 1).EntireRow)\n End If\n\n ' Delete only if a certain number of rows to be deleted is reached to speed up runtime\n If deleteCount >= DeleteChunkSize Then\n DoEvents\n deleteRange.Delete xlUp\n Set deleteRange = Nothing\n deleteCount = 0\n End If\n End If\n \n Next row\n End With\n ' delete the last chunk of data if any\n If Not deleteRange Is Nothing Then\n deleteRange.Delete xlUp\n End If\n\nEnd Sub\n" }, { "answer_id": 74377153, "author": "Lexxy_B", "author_id": 19640110, "author_profile": "https://Stackoverflow.com/users/19640110", "pm_score": 0, "selected": false, "text": "Imports System.IO\nImports System.IO.File\nImports System.Text\n\nPublic Class Form1\n\n Public Datas As New List(Of String())\n\n Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n FileToList()\n DataToFile()\n End Sub\n\n\n Sub FileToList()\n Using sr As StreamReader = New StreamReader(\"Bestand 31.10.2022.CSV\", Encoding.Default)\n Dim Time As DateTime = Now\n Dim span As TimeSpan\n Do Until sr.Peek() = -1\n Dim s As String = sr.ReadLine()\n Dim a() As String = s.Split(\";\")\n If Not EmptyRow(a) Then\n Datas.Add(a)\n End If\n Loop\n span = Now - Time\n\n Dim i As Long = Datas.Count\n MessageBox.Show(String.Format(\"Es sind: {0} Zeilen vorhanden in der Liste\" & vbCrLf &\n \"Dies benötigte: {1}s\", i, span.TotalSeconds))\n End Using\n\n End Sub\n\n Sub DataToFile()\n Dim Time As DateTime = Now\n Dim span As TimeSpan\n Using fs As FileStream = New FileStream(\"Test_\" & DateTime.Now.ToShortDateString & \".csv\", FileMode.Create)\n Using sw As StreamWriter = New StreamWriter(fs, Encoding.Default)\n For i = 0 To Datas.Count - 1\n sw.WriteLine(Join(Datas(i), \";\"))\n Next\n End Using\n End Using\n\n span = Now - Time\n MessageBox.Show(String.Format(\"Das Erstellen der neuen Datei hat: {0}s gedauert\", span.TotalSeconds))\n End Sub\n\n Function EmptyRow(ByVal Array As String()) As Boolean\n\n For i = 0 To Array.Count - 1\n If Array(i) <> \"\" Then\n Return False\n End If\n Return True\n Next\n\n End Function\n\n\nEnd Class\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19640110/" ]
74,373,601
<p>I've written the function which shall everytime it is called get new data trough a service file.</p> <p>The function looks like this:</p> <pre><code>onCarChange() { this.carService.getCarData(this.selectedCar).subscribe( async (response: CarData) =&gt; { if (response?.data === null) { this.showCarData = false; } else { this.showCarData = true; } }, (error) =&gt; { this.showCarData = false console.error(error); } }; </code></pre> <p>My service.ts file looks like this:</p> <pre><code>getCarData(carId: string) { return this.http.get(API.carData.get(carId)); } </code></pre> <p>The function is working fine and as intended so no issues on that. But right now I'm trying to clean up my code and I've noticed that the subscribe method is crossed out and marked as deprecated. Does somebody know how to get rid of this? Do I need to reconstruct the function? And if yes what would it look like?</p>
[ { "answer_id": 74373696, "author": "Carles Ramos", "author_id": 13309394, "author_profile": "https://Stackoverflow.com/users/13309394", "pm_score": 2, "selected": false, "text": "onCarChange() {\n this.carService.getCarData(this.selectedCar).subscribe({\n next: async (response) => {\n if (response?.data === null) {\n this.showCarData = false;\n } else {\n this.showCarData = true;\n }\n }, error: (err) => {\n this.showCarData = false\n console.error(err);\n }\n });\n};\n" }, { "answer_id": 74374201, "author": "Saidamir", "author_id": 15148870, "author_profile": "https://Stackoverflow.com/users/15148870", "pm_score": 2, "selected": true, "text": ".subscribe({\n next: () => { ... }, // (required) nextHandler\n error: () => { ... }, // (required) errorHandler\n complete: () => {.. }, // (optional) completeHandler\n})\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19666704/" ]
74,373,633
<p>I have one box div inside that, user can easily add link for h1 tag i.e for title tag. but I require that it should apply to the whole div. The anchor tag is coming from Wordpress editor toolbar, so how can I extract that <code>href</code> and add to whole div. code is using React.</p> <p>eg :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="box"&gt; &lt;h1&gt; &lt;a href="https://stackoverflow.com/questions/13396721/if-href-url-change-add-class-to-parent- element"&gt;The new face of marketing&lt;/a&gt; &lt;/h1&gt; &lt;p&gt;Marketing&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I will need whatever user will add url for title it should apply to whole div and make div clickable with respect to its url.</p>
[ { "answer_id": 74373696, "author": "Carles Ramos", "author_id": 13309394, "author_profile": "https://Stackoverflow.com/users/13309394", "pm_score": 2, "selected": false, "text": "onCarChange() {\n this.carService.getCarData(this.selectedCar).subscribe({\n next: async (response) => {\n if (response?.data === null) {\n this.showCarData = false;\n } else {\n this.showCarData = true;\n }\n }, error: (err) => {\n this.showCarData = false\n console.error(err);\n }\n });\n};\n" }, { "answer_id": 74374201, "author": "Saidamir", "author_id": 15148870, "author_profile": "https://Stackoverflow.com/users/15148870", "pm_score": 2, "selected": true, "text": ".subscribe({\n next: () => { ... }, // (required) nextHandler\n error: () => { ... }, // (required) errorHandler\n complete: () => {.. }, // (optional) completeHandler\n})\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14561768/" ]
74,373,638
<p>I have the simple task to print elements inside a LinkedList that has no duplicates with commas in between, but I have come up with two ways to do it and I'm unsure about how LinkedList iteration works so I don't know which way is best. I have some assumptions about both ways.</p> <pre><code> public static void main(String[] args) { LinkedList&lt;Integer&gt; pres = new LinkedList&lt;Integer&gt;(); pres.add(112); pres.add(114); pres.add(326); pres.add(433); pres.add(119); // ---------------------------------- METHOD 1 --------------------------------- for (int i = 0; i &lt; pres.size(); i++) { System.out.print(pres.get(i) + (i == pres.size() - 1 ? &quot;&quot; : &quot;,&quot;)); } // ---------------------------------- METHOD 2 --------------------------------- for (int courseIndex : pres) { System.out.print(courseIndex + (courseIndex == pres.getLast() ? &quot;&quot; : &quot;,&quot;)); } } </code></pre> <p>For Method 1, I'm wondering if calling <code>pres.get(i)</code> in every iteration traverses the list from the beginning each time: (112) - (112 -&gt; 114) - (112 -&gt; 114 -&gt; 326)... Or does the pointer stay where it last was and just move to the next element?</p> <p>For Method 2, it seems like the foreach loop avoids the possible problem that I'm assuming in Method 1, but I'm calling <code>getLast</code> on every iteration as well. Is it a doubly linked list? Is get last an O(1) operation? If not, is calling <code>getLast</code> on each iteration even worse than Method 1, since it traverses the list all the way down each time?</p>
[ { "answer_id": 74375160, "author": "Matt Timmermans", "author_id": 5483526, "author_profile": "https://Stackoverflow.com/users/5483526", "pm_score": 0, "selected": false, "text": "get(i)" }, { "answer_id": 74375277, "author": "Joop Eggen", "author_id": 984823, "author_profile": "https://Stackoverflow.com/users/984823", "pm_score": 1, "selected": false, "text": "String s = pres.stream()\n .map(Integer::toString)\n .collect(Collectors.joining(\", \"));\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17944655/" ]
74,373,674
<p>I am trying to provide wrappers for short-cutting every-day commands. Python environments are very useful to do that.</p> <p>Is it possible to provide all methods of an object to the local namespace within a new environment?</p> <pre class="lang-py prettyprint-override"><code>class my_object: def method_a(): ... class my_environment: ... def __enter__(self): some_object = my_object() # something like `from some_object import *` ?? return(some_object) ... with my_environment() as some_object: # standard syntax: some_object.method_a() # shortcut: method_a() # how to make this possible? </code></pre>
[ { "answer_id": 74373942, "author": "rgpereira", "author_id": 8433948, "author_profile": "https://Stackoverflow.com/users/8433948", "pm_score": 0, "selected": false, "text": "class MyObject:\n def method_a():\n ...\n\nclass MyEnvironment(MyObject):\n ...\n def __enter__(self):\n return self\n ...\n\nwith MyEnvironment() as some_object:\n # standard syntax:\n some_object.method_a() \n" }, { "answer_id": 74373984, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 1, "selected": false, "text": "__enter__" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2575273/" ]
74,373,713
<p>My task is the following:</p> <blockquote> <p>Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).</p> </blockquote> <p>I figured I could do a def function to check if the inputs are all integers and not floats or strings. While the programme works if only integers are input, it gets stuck on my except if another type is input</p> <pre class="lang-py prettyprint-override"><code>def valuecheck(checker): loopx = True while loopx: try: #first it checks if the input is actually an integer checker = int(checker) loopx = False return(checker) #if input isn't an integer the below prompt is printed except: input(&quot;Value isn't a valid input, try again: &quot;) varA = input(&quot;please input an integer: &quot;) varA = valuecheck(varA) x = varA varB = input(&quot;please input anther integer: &quot;) varB = valuecheck(varB) y = varB varC = input(&quot;please input another integer: &quot;) varC = valuecheck(varC) z = varC if x == y == z: print(3,&quot;of the integers are of the same value&quot;) elif x == y or y == z or x == z: print(2,&quot;of the integers are of the same value&quot;) else: print(0, &quot;of the integers are of the same value&quot;) </code></pre> <p>This is my code so far. It should be able to tell the user if anything other than an integer is input and allow them to try again.</p>
[ { "answer_id": 74373756, "author": "Mureinik", "author_id": 2422776, "author_profile": "https://Stackoverflow.com/users/2422776", "pm_score": 4, "selected": true, "text": "checker" }, { "answer_id": 74373822, "author": "Bram", "author_id": 20457959, "author_profile": "https://Stackoverflow.com/users/20457959", "pm_score": 0, "selected": false, "text": "checker = input(\"Value isn't a valid input, try again: \")\n" }, { "answer_id": 74373851, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def valuecheck(value):\n if isinstance(value, int):\n return value\n else:\n while(True):\n value = input(\"Value isn't a valid input, try again: \")\n try:\n value = int(value)\n return val\n except:\n pass\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458305/" ]
74,373,714
<p>Learning work with Maps...Can't have access to the element specified? what is the problem. please give me some links to read or watch working with Maps in flutter. <a href="https://i.stack.imgur.com/PAfES.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PAfES.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74373756, "author": "Mureinik", "author_id": 2422776, "author_profile": "https://Stackoverflow.com/users/2422776", "pm_score": 4, "selected": true, "text": "checker" }, { "answer_id": 74373822, "author": "Bram", "author_id": 20457959, "author_profile": "https://Stackoverflow.com/users/20457959", "pm_score": 0, "selected": false, "text": "checker = input(\"Value isn't a valid input, try again: \")\n" }, { "answer_id": 74373851, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def valuecheck(value):\n if isinstance(value, int):\n return value\n else:\n while(True):\n value = input(\"Value isn't a valid input, try again: \")\n try:\n value = int(value)\n return val\n except:\n pass\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20019751/" ]
74,373,748
<p>I am a beginner web developer and as a test task I got the following:</p> <blockquote> <p>An unordered array of printed ASCII characters is given. Describe in your own words (without code or pseudocode) a sorting algorithm that allows you to sort this array alphabetically in linear time. It is necessary to describe the actions at each step of the algorithm. Is a stable version of such a sorting algorithm possible?</p> </blockquote> <p>I'm not very good at algorithms, because I have just started studying, so I do not understand how to approach this task.</p> <p>Thanks for the help.</p>
[ { "answer_id": 74373756, "author": "Mureinik", "author_id": 2422776, "author_profile": "https://Stackoverflow.com/users/2422776", "pm_score": 4, "selected": true, "text": "checker" }, { "answer_id": 74373822, "author": "Bram", "author_id": 20457959, "author_profile": "https://Stackoverflow.com/users/20457959", "pm_score": 0, "selected": false, "text": "checker = input(\"Value isn't a valid input, try again: \")\n" }, { "answer_id": 74373851, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def valuecheck(value):\n if isinstance(value, int):\n return value\n else:\n while(True):\n value = input(\"Value isn't a valid input, try again: \")\n try:\n value = int(value)\n return val\n except:\n pass\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432333/" ]
74,373,818
<p>I need to validate and clean a field in CSV. There is column for IP address and I need to remove only invalid data inside that column.</p> <p>I tried the following command :</p> <pre><code>awk 'BEGIN{ FS=OFS=&quot;,&quot; }{ gsub(/^([0-9]{1,3}[\.]){3}[0-9]{1,3}$/,&quot;&quot;, $3) }1' input.csv </code></pre> <p>Input file</p> <pre><code>anna,new york,192.168.1.5,usa james,denver,240.210.1.8,usa peter,denver,colarado,usa tommy,new york,10.2.8.3 male,usa </code></pre> <p>Current output</p> <pre><code>anna,new york,,usa james,denver,,usa peter,denver,colarado,usa tommy,new york,10.2.8.3 male,usa </code></pre> <p>Expected output</p> <pre><code>anna,new york,192.168.1.5,usa james,denver,240.210.1.8,usa peter,denver,,usa tommy,new york,10.2.8.3,usa </code></pre> <p>This command remove the matching data, but I need the opposite. How do I remove only the non-matching data in the IP column ?</p>
[ { "answer_id": 74373756, "author": "Mureinik", "author_id": 2422776, "author_profile": "https://Stackoverflow.com/users/2422776", "pm_score": 4, "selected": true, "text": "checker" }, { "answer_id": 74373822, "author": "Bram", "author_id": 20457959, "author_profile": "https://Stackoverflow.com/users/20457959", "pm_score": 0, "selected": false, "text": "checker = input(\"Value isn't a valid input, try again: \")\n" }, { "answer_id": 74373851, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def valuecheck(value):\n if isinstance(value, int):\n return value\n else:\n while(True):\n value = input(\"Value isn't a valid input, try again: \")\n try:\n value = int(value)\n return val\n except:\n pass\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458378/" ]
74,373,844
<p>React: I have a menu and list of sub menus. I want to calculate the sub menus count and if it exceed from 3, rest sub menus will be hide.</p> <p><code>Code for try count the elements</code></p> <pre><code>export default function App() { const ElementRef = useRef(null) useEffect(() =&gt; { const Elementcount = ElementRef.current.childNodes.length; console.log(Elementcount); }) return ( &lt;div className=&quot;menus&quot; ref={ElementRef}&gt; &lt;div className=&quot;submenus&quot;&gt; &lt;div&gt;Menu 1&lt;/div&gt; &lt;div&gt;Menu 2&lt;/div&gt; &lt;div&gt;Menu 3&lt;/div&gt; // Menu 4 &amp; 5 hide &lt;div&gt;Menu 4&lt;/div&gt; &lt;div&gt;Menu 5&lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;submenus&quot;&gt; &lt;div&gt;Menu 1&lt;/div&gt; &lt;div&gt;Menu 2&lt;/div&gt; &lt;div&gt;Menu 3&lt;/div&gt; // Menu 4 hide &lt;div&gt;Menu 4&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } </code></pre>
[ { "answer_id": 74373756, "author": "Mureinik", "author_id": 2422776, "author_profile": "https://Stackoverflow.com/users/2422776", "pm_score": 4, "selected": true, "text": "checker" }, { "answer_id": 74373822, "author": "Bram", "author_id": 20457959, "author_profile": "https://Stackoverflow.com/users/20457959", "pm_score": 0, "selected": false, "text": "checker = input(\"Value isn't a valid input, try again: \")\n" }, { "answer_id": 74373851, "author": "Will", "author_id": 12829151, "author_profile": "https://Stackoverflow.com/users/12829151", "pm_score": -1, "selected": false, "text": "def valuecheck(value):\n if isinstance(value, int):\n return value\n else:\n while(True):\n value = input(\"Value isn't a valid input, try again: \")\n try:\n value = int(value)\n return val\n except:\n pass\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5444560/" ]
74,373,868
<p>I want to list/search all the issues in Jira. I have a code like :</p> <pre><code>url = 'https://company.com/rest/api/2/search' auth = HTTPBasicAuth(&quot;username&quot;, &quot;password&quot;) // I tries token as well headers = { 'Accept': 'application/json' } query = { 'jql': 'project=PRKJECTKEY', 'startAt': 0 } response = requests.request( &quot;GET&quot;, url, headers=headers, auth=auth, params=query ) </code></pre> <p>I am not sure if the password should be token or the actual password and the url should be should be starting from companyname.com. This gives me <code>&lt;Response [401]&gt;</code> but i have all the permissions with the account.</p> <p>Can someone help me with the authentication is supposed to be used this way.</p>
[ { "answer_id": 74373988, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 0, "selected": false, "text": "atlassian-python-api" }, { "answer_id": 74375381, "author": "Andreas G.", "author_id": 9836432, "author_profile": "https://Stackoverflow.com/users/9836432", "pm_score": 2, "selected": true, "text": "user = 'firstname.familyname@account.xx'\n\napikey = 'xxxxxxxxxxxxxxxxx'\nserver = 'https://companypage.atlassian.net'\n\noptions = {\n 'server': server\n}\n\njira = JIRA(options, basic_auth=(user, apikey))\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8671089/" ]
74,373,870
<p>I want to create a cool animation that when the user clicks on the email input or the password the label of the input will go up and have a nice transition in the bottom border.</p> <p><strong>This is what I have:</strong></p> <p><a href="https://i.stack.imgur.com/8otpb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8otpb.png" alt="This is what I have" /></a></p> <p><strong>And this is what I want to create:</strong></p> <p><a href="https://i.stack.imgur.com/OQzHr.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQzHr.gif" alt="This is what I want to create" /></a></p> <p>My code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.form { position: relative; display: flex; flex-direction: column; margin-bottom: 1rem; } .input { background: none; color: #c6c6c6; font-size: 1.8rem; padding: 1.6rem; display: block; border: none; border-bottom: 1px solid #c6c6c6; width: 100%; } .label { position: absolute; color: #c6c6c6; font-size: 1.6rem; left: 0.5rem; top: 1rem; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="form"&gt; &lt;input class="email input" type="email" name="email" /&gt; &lt;label class="label" for="email"&gt;Email Address&lt;/label&gt; &lt;/div&gt; &lt;div class="form"&gt; &lt;input class="password input" type="password" name="password" /&gt; &lt;label class="label" for="password"&gt;Password&lt;/label&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I've searched a lot but every code example I found was with SCCS, SASS and I don't understand it. So please help me with plain CSS. Any help would be greatly appreciated!</p>
[ { "answer_id": 74373988, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 0, "selected": false, "text": "atlassian-python-api" }, { "answer_id": 74375381, "author": "Andreas G.", "author_id": 9836432, "author_profile": "https://Stackoverflow.com/users/9836432", "pm_score": 2, "selected": true, "text": "user = 'firstname.familyname@account.xx'\n\napikey = 'xxxxxxxxxxxxxxxxx'\nserver = 'https://companypage.atlassian.net'\n\noptions = {\n 'server': server\n}\n\njira = JIRA(options, basic_auth=(user, apikey))\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19087533/" ]
74,373,886
<p>I have a splash screen in my <code>homepage</code> activity which should then redirect to my <code>second activity</code>:</p> <pre><code>class _MyHomePageState extends State&lt;MyHomePage&gt; { @override void initState(){ super.initState(); Timer(const Duration(seconds: 3), ()=&gt;Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) =&gt; SecondScreen() ) ) ); } @override Widget build(BuildContext context) { return Container( color: Colors.white, child:FlutterLogo(size:MediaQuery.of(context).size.height) ); } } class SecondScreen extends StatelessWidget { //checking if internet connection exists here late StreamSubscription subscription; var isDeviceConnected = false; bool isAlertSet = false; @override void initState(){ getConnectivity(); super.initState(); //initState() is undefined } getConnectivity() =&gt; subscription = Connectivity().onConnectivityChanged.listen( (ConnectivityResult result) async { isDeviceConnected = await InternetConnectionChecker().hasConnection; if (!isDeviceConnected &amp;&amp; isAlertSet == false) { showDialogBox(); setState(() =&gt; isAlertSet = true); //setState() is undefined } }, ); @override void dispose() { subscription.cancel(); super.dispose(); //dispose() is undefined } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment:MainAxisAlignment.center, children:[ Image( image: const AssetImage('images/logo.png'), height: AppBar().preferredSize.height,), const SizedBox( width: 15, ), Text( widget.title ), ] ) ) ); } showDialogBox() =&gt; showCupertinoDialog&lt;String&gt;( context: context, builder: (BuildContext context) =&gt; CupertinoAlertDialog( title: const Text('No internet connection'), content: const Text('Please make sure you have an active internet connection to continue'), actions: &lt;Widget&gt;[ TextButton( onPressed: () async { Navigator.pop(context, 'Cancel'); setState(() =&gt; isAlertSet = false); isDeviceConnected = await InternetConnectionChecker().hasConnection; if (!isDeviceConnected &amp;&amp; isAlertSet == false) { showDialogBox(); setState(() =&gt; isAlertSet = true); } }, child: const Text('OK'), ), ], ), ); } </code></pre> <p>The flow is such that, in the homepage activity a splash screen will open and then it will redirect to the second activity which will check if the user has an active internet connection.</p> <p>I tried changing the <code>SecondScreen</code> to <code>statefulWidget</code>, but I still keep getting the same error.</p>
[ { "answer_id": 74374106, "author": "Sachin Kumawat", "author_id": 11830339, "author_profile": "https://Stackoverflow.com/users/11830339", "pm_score": 3, "selected": true, "text": "class SecondScreen extends StatefulWidget {\n const SecondScreen({Key? key}) : super(key: key);\n\n @override\n State<SecondScreen> createState() => _SecondScreenState();\n}\n\nclass _SecondScreenState extends State<SecondScreen> {\n @override\n void initState() {\n // TODO: implement initState\n super.initState();\n }\n @override\n Widget build(BuildContext context) {\n return Container();\n }\n}\n" }, { "answer_id": 74374125, "author": "john", "author_id": 16146701, "author_profile": "https://Stackoverflow.com/users/16146701", "pm_score": 0, "selected": false, "text": " \n\n\nclass SecondScreen extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n\nWidgetsBinding.instance?.addPostFrameCallback((_) {\n // do something\n print(\"Build Completed\"); \n });\n \n return Container(\n color: Colors.blue,\n child: WhatEverWidget()\n );\n }\n}" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,373,917
<p>is there a way to subset from a data set some IDs based on an external list? In other words, I have a data set:</p> <blockquote> <pre><code> ID Value 0001 0.3 0001 0.6 0002 0.7 0002 0.71 0002 0.43 0003 0.01 0003 0.2 0005 12 0005 11 </code></pre> </blockquote> <p>and a list:</p> <blockquote> <pre><code> ID 0001 0002 0005 </code></pre> </blockquote> <p>The desired output would be:</p> <blockquote> <pre><code> ID Value 0001 0.3 0001 0.6 0002 0.7 0002 0.71 0002 0.43 0005 12 0005 11 </code></pre> </blockquote> <p>My point is that in the data set, IDs are repeated.</p> <p>Thank you in advance</p>
[ { "answer_id": 74374446, "author": "Negdo", "author_id": 19646183, "author_profile": "https://Stackoverflow.com/users/19646183", "pm_score": 1, "selected": true, "text": "data have;\n input ID Value;\n format ID z4.;\n datalines;\n0001 0.3\n0001 0.6\n0002 0.7\n0002 0.71\n0002 0.43\n0003 0.01\n0003 0.2\n0005 12\n0005 11\n;\nrun;\n" }, { "answer_id": 74378895, "author": "Reeza", "author_id": 1919583, "author_profile": "https://Stackoverflow.com/users/1919583", "pm_score": 1, "selected": false, "text": "proc sql;\ncreate table want as\nselect * from have\nwhere ID in \n (select id from id_list);\nquit;\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19938845/" ]
74,373,927
<p>I have a data frame with three columns:</p> <pre><code> df &lt;- data.frame(col1=c('71711', '71711', '71711', 'Comment 4', '71711', 'Comment 6'), col2=c('Comment 1','Comment 2','Comment 3', '24','Comment 5','26'), col3 = c('21','22','23',NA,'25',NA)) </code></pre> <p>Desired output:</p> <pre><code>Col1 Col2 Col3 71711 Comment 1 21 71711 Comment 2 22 71711 Comment 3 23 71711 Comment 4 24 71711 Comment 5 25 71711 Comment 6 26 </code></pre> <p>I tried the following but it replaces desired values with numeric one:</p> <pre><code>for (i in 1:nrow(df)) { if (any(sapply(df$col2, is.numeric)) == &quot;True&quot; ) df$col3[i] &lt;- df$col2[i] df$col1[i] &lt;- df$col2[i] } </code></pre> <p>Thanks</p>
[ { "answer_id": 74374044, "author": "det", "author_id": 12148402, "author_profile": "https://Stackoverflow.com/users/12148402", "pm_score": 2, "selected": true, "text": "NA" }, { "answer_id": 74374046, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "apply" }, { "answer_id": 74374269, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndf |>\n transmute(txt = pmap_chr(list(col1, col2, col3), \n ~ paste(c(...)[!is.na(c(...))], collapse = \"---\")))|>\n extract(col = txt, \n into = c(\"col1\", \"col2\", \"col3\"), \n regex = \"(ID\\\\d+)?(?:---)?(Comment\\\\s\\\\d+)---(\\\\d+)$\", \n remove = TRUE, \n convert = TRUE) |>\n mutate(col1 = paste0(\"ID\", row_number()))\n#> col1 col2 col3\n#> 1 ID1 Comment 1 21\n#> 2 ID2 Comment 2 22\n#> 3 ID3 Comment 3 23\n#> 4 ID4 Comment 4 24\n#> 5 ID5 Comment 5 25\n#> 6 ID6 Comment 6 26\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8629463/" ]
74,373,967
<p>I would need your help with the following</p> <p>Our goal is to increase our overall share in the market - To do this, we would like to know whether introducing a specific combination of products to different countries would have an impact on our market share.</p> <p>Following is a mockup data over a period of August and September of 2021 and 2022</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Year</th> <th style="text-align: center;">Country</th> <th style="text-align: right;">Product</th> <th style="text-align: center;">Aug_Sales_Euros</th> <th style="text-align: right;">Sept_Sales_Euros</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">Kenya</td> <td style="text-align: right;">20MB_Internet</td> <td style="text-align: center;">12000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">Kenya</td> <td style="text-align: right;">200min_Call</td> <td style="text-align: center;">7000</td> <td style="text-align: right;">9000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">Kenya</td> <td style="text-align: right;">10MB_100min</td> <td style="text-align: center;">6000</td> <td style="text-align: right;">5000</td> </tr> <tr> <td style="text-align: left;">2021</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">10MB_100min</td> <td style="text-align: center;">9000</td> <td style="text-align: right;">10000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">20MB_Internet</td> <td style="text-align: center;">60000</td> <td style="text-align: right;">50000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">900MB_Internet</td> <td style="text-align: center;">12000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">400min_Call</td> <td style="text-align: center;">70000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">200min_Call</td> <td style="text-align: center;">12000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2021</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">400min_Call</td> <td style="text-align: center;">50000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2021</td> <td style="text-align: center;">USA</td> <td style="text-align: right;">200min_Call</td> <td style="text-align: center;">12000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2022</td> <td style="text-align: center;">FRANCE</td> <td style="text-align: right;">200min_Call</td> <td style="text-align: center;">12000</td> <td style="text-align: right;">8000</td> </tr> <tr> <td style="text-align: left;">2021</td> <td style="text-align: center;">FRANCE</td> <td style="text-align: right;">200min_Call</td> <td style="text-align: center;">12000</td> <td style="text-align: right;">8000</td> </tr> </tbody> </table> </div> <p>We would like to know, for instance, which product should be introduced with 200min_call in France such that our overall market share is increased? or which existing product combination has the best results? FYI: we use python for our analysis.</p> <p>There is a lot more data, with lot more combination of products and countries</p> <p>How should I approach this problem, or even better, is there an example that I can refer to?</p> <p>Thanks, Justin</p>
[ { "answer_id": 74374044, "author": "det", "author_id": 12148402, "author_profile": "https://Stackoverflow.com/users/12148402", "pm_score": 2, "selected": true, "text": "NA" }, { "answer_id": 74374046, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "apply" }, { "answer_id": 74374269, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndf |>\n transmute(txt = pmap_chr(list(col1, col2, col3), \n ~ paste(c(...)[!is.na(c(...))], collapse = \"---\")))|>\n extract(col = txt, \n into = c(\"col1\", \"col2\", \"col3\"), \n regex = \"(ID\\\\d+)?(?:---)?(Comment\\\\s\\\\d+)---(\\\\d+)$\", \n remove = TRUE, \n convert = TRUE) |>\n mutate(col1 = paste0(\"ID\", row_number()))\n#> col1 col2 col3\n#> 1 ID1 Comment 1 21\n#> 2 ID2 Comment 2 22\n#> 3 ID3 Comment 3 23\n#> 4 ID4 Comment 4 24\n#> 5 ID5 Comment 5 25\n#> 6 ID6 Comment 6 26\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539912/" ]
74,373,968
<p>SO, I am trying to solve LCS using Recursion + memorization.<br> I know dp is more efficient but just for understanding, I wanted to solve using hashmap.<br></p> <p>APPROACH -&gt; There are 2 strings given s1 and s2 with lengths are x, and y. <br> In normal recursion we do something like this. <br></p> <p>if (x==-1 || y==-1) return 0;<br> if (s1[x] == s2[y]) return 1 + lcs(s1, s2, x-1, y-1); <br> else return max(lcs(s1, s2, x-1, y), lcs(s1, s2, x, y-1)); <br></p> <p>Now for implementing memorization, I will be using a hashmap <br> hashmap will be of string and int and the hashmap will be storing like this : <br> key -&gt; to_string(x) + &quot;@@&quot; + to_string(y)<br> value -&gt; the answer <br></p> <p>I am using &quot;@@&quot; just to seperate those 2 numbers.<br></p> <p>SO my code is -&gt;:<br></p> <pre><code>int lcsRecursiveAndMemorization(std::string S1, std::string S2, std::unordered_map&lt;std::string, int&gt; &amp;um, int x, int y) { // if either string is empty if (x == -1 || y == -1) { return 0; } // check if it is present already std::string temp = std::to_string(x) + &quot;@@&quot; + std::to_string(y); if (um.find(temp) != um.end()) { return um[temp]; } else { // check for if both the characters are equal if (S1[x] == S2[y]) { // after getting answer store it and then return it. std::string temp1 = std::to_string(x - 1) + &quot;@@&quot; + std::to_string(y - 1); um[temp1] = 1 + lcsRecursiveAndMemorization(S1, S2, um, x - 1, y - 1); return um[temp1]; } else { // store answer for all the cases i.e., // for x-1, y and x, y-1 // and for x, y also std::string temp2 = std::to_string(x - 1) + &quot;@@&quot; + std::to_string(y); std::string temp3 = std::to_string(x) + &quot;@@&quot; + std::to_string(y - 1); int first_ = lcsRecursiveAndMemorization(S1, S2, um, x - 1, y); int second_ = lcsRecursiveAndMemorization(S1, S2, um, x, y - 1); // storing um[temp2] = first_; um[temp3] = second_; um[temp] = std::max(first_, second_); return um[temp]; } } } int main() { std::string S2 = &quot;pmjghexybyrgzczy&quot;; std::string S1 = &quot;hafcdqbgncrcbihkd&quot;; int x = S1.size() - 1; int y = S2.size() - 1; std::unordered_map&lt;std::string, int&gt; um; cout &lt;&lt; &quot;The LCS length using recursion + memorization is -&gt; &quot; &lt;&lt; lcsRecursiveAndMemorization(S1, S2, um, x, y) &lt;&lt; &quot;\n&quot;; return 0; } </code></pre> <p>So what is the problem with this code? <br> For me it's looks just fine. <br> It gives correct answer for small string, but for large string the answer is wrong.<br> It behaves in undefined manner like for the above two string the correct answer is 4.<br> And my program gives 5, but... if we swap the s1 with s2 it gives the correct answer i.e., 4? How?<br> I mean this should not affect the answer if we swap the 2 stings. <br></p> <p>I just changed the recursive code to recursion + memorization using hashmap. <br> I don't know why its not working, I guess there is some logic problem. <br></p>
[ { "answer_id": 74375930, "author": "pasthec", "author_id": 8923995, "author_profile": "https://Stackoverflow.com/users/8923995", "pm_score": 1, "selected": false, "text": "std::pair<int,int>" }, { "answer_id": 74376139, "author": "varun", "author_id": 19141868, "author_profile": "https://Stackoverflow.com/users/19141868", "pm_score": 1, "selected": true, "text": "int lcsRecursiveAndMemorization(std::string S1, std::string S2, std::unordered_map<std::string, int> &um, int x, int y){\n// if either string is empty \nif (x == -1 || y == -1)\n{\n return 0;\n}\n\n// check if it is present already\nstd::string temp = std::to_string(x) + \"@@\" + std::to_string(y);\nif (um.find(temp) != um.end())\n{\n return um[temp];\n}\nelse\n{\n // check for if both the characters are equal\n if (S1[x] == S2[y])\n {\n // after getting answer store it and then return it.\n // std::string temp1 = std::to_string(x - 1) + \"@@\" + std::to_string(y - 1);\n um[temp] = 1 + lcsRecursiveAndMemorization(S1, S2, um, x - 1, y - 1);\n return um[temp];\n }\n else\n {\n // store answer for all the cases i.e.,\n // for x-1, y and x, y-1\n // and for x, y also\n // std::string temp2 = std::to_string(x - 1) + \"@@\" + std::to_string(y);\n // std::string temp3 = std::to_string(x) + \"@@\" + std::to_string(y - 1);\n\n int first_ = lcsRecursiveAndMemorization(S1, S2, um, x - 1, y);\n int second_ = lcsRecursiveAndMemorization(S1, S2, um, x, y - 1);\n\n // storing\n // um[temp2] = first_;\n // um[temp3] = second_;\n um[temp] = std::max(first_, second_);\n return um[temp];\n // return std::max(first_, second_);\n }\n}}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74373968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19141868/" ]
74,374,015
<p>I am displaying several <code>ggplots</code> into a <code>ggarrange</code> matrix.<br /> <code>ggarrange</code> displays each subsequent plot one by one by column and starts with a new row when the last column is reached.</p> <p>What I would like to do is to display each plot by row then start with a new column when the last row is reached.</p> <p>Here is an example</p> <pre><code>##### Import libraries library(ggplot2) library(ggpubr) ##### Initiating objects set.seed(1) df &lt;- data.frame(matrix(rnorm(100), 25, 4)) listggplots &lt;- list() k &lt;- 0 vecColors &lt;- rep(c(&quot;#21b78c&quot;, &quot;#21a0b7&quot;, &quot;#2143b7&quot;, &quot;#b521b7&quot;), each=4) ##### Filling list of ggplots for(i in 1:ncol(df)){ for(j in 1:ncol(df)){ k &lt;- k + 1 dfTemp &lt;- df[, c(i, j)] colnames(dfTemp) &lt;- c(&quot;var1&quot;, &quot;var2&quot;) listggplots[[k]] &lt;- ggplot(dfTemp, aes(var1, var2)) + geom_point(size=10, color=vecColors[k]) + scale_x_continuous(name=colnames(df)[i]) + scale_y_continuous(name=colnames(df)[j]) + theme(legend.position=&quot;none&quot;, axis.title=element_text(size=12)) } } ##### Display plots ggarrange(plotlist=c(listggplots), nrow=4, ncol=4) </code></pre> <p><a href="https://i.stack.imgur.com/oSHaY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oSHaY.png" alt="enter image description here" /></a></p> <p>As we can see, the current matrix order for displaying plots is:</p> <pre><code> [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 5 6 7 8 [3,] 9 10 11 12 [4,] 13 14 15 16 </code></pre> <p>I would like each column to have only one ggplot color.<br /> So the order of the matrix would be:</p> <pre><code> [,1] [,2] [,3] [,4] [1,] 1 5 9 13 [2,] 2 6 10 14 [3,] 3 7 11 15 [4,] 4 8 12 16 </code></pre> <p>I found the following topic but it is manual disposition of plots and I would like something automatic.<br /> <a href="https://stackoverflow.com/questions/62750077/ggarrange-combine-multiple-plots">ggarrange: combine multiple plots</a></p> <p>Thank you for any idea</p>
[ { "answer_id": 74374211, "author": "Hansel Palencia", "author_id": 10897981, "author_profile": "https://Stackoverflow.com/users/10897981", "pm_score": 1, "selected": false, "text": "rep()" }, { "answer_id": 74374227, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 3, "selected": true, "text": "cowplot::plot_grid(plotlist = listggplots, byrow = FALSE, nrow = 4, ncol = 4)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17049772/" ]
74,374,051
<p>I have a normal, easy flexbox layout. I try to show two elements per row. There is enough width for 2 elements. But strangely, every element gets one whole row. I don't know why. Here is my code:</p> <p>gallery.html:</p> <pre><code>&lt;div class=&quot;container&quot; *ngFor=&quot;let imageOrFile of imagesAndFiles&quot;&gt; &lt;div class=&quot;image&quot;&gt; &lt;dispo-einsatz-dokumente-gallery-image-item [image]=&quot;imageOrFile&quot; &gt;&lt;/dispo-einsatz-dokumente-gallery-image-item&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>gallery.scss:</p> <pre><code>.container { display: flex; flex-direction: row; } .image { width: 40%; height: 200px; } </code></pre> <p>And the child component html:</p> <pre><code>&lt;p&gt;{{ image.name }}&lt;/p&gt; </code></pre> <p>This is the result:</p> <p><a href="https://i.stack.imgur.com/SQKKn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SQKKn.png" alt="enter image description here" /></a></p> <p>Why is it like this? How do I get my two elements in one row?</p>
[ { "answer_id": 74374216, "author": "Luca Angrisani", "author_id": 13240452, "author_profile": "https://Stackoverflow.com/users/13240452", "pm_score": 2, "selected": false, "text": "<div class=\"container\">\n <div class=\"image\" *ngFor=\"let imageOrFile of imagesAndFiles\">\n <dispo-einsatz-dokumente-gallery-image-item [image]=\"imageOrFile\">\n </dispo-einsatz-dokumente-gallery-image-item>\n </div>\n</div>\n" }, { "answer_id": 74374220, "author": "Mr. Stash", "author_id": 13625800, "author_profile": "https://Stackoverflow.com/users/13625800", "pm_score": 3, "selected": true, "text": "<div class=\"container\">\n <div class=\"image\" *ngFor=\"let imageOrFile of imagesAndFiles\">\n <dispo-einsatz-dokumente-gallery-image-item\n [image]=\"imageOrFile\"\n ></dispo-einsatz-dokumente-gallery-image-item>\n </div>\n</div>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14287016/" ]
74,374,053
<p><a href="https://i.stack.imgur.com/qEJRb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEJRb.png" alt="enter image description here" /></a></p> <p>I like to increase the count of Item 1 without changing the count of Item 2 and Item 3. How do I do that in React Native? I am a beginner.</p> <p>Here is my code: (Never mind the AppText and AppButton component those are my own)</p> <pre><code>const items = [ { id: 1 }, { id: 2 }, { id: 3 } ] const [quantity, setQuantity] = useState(1) return ( &lt;View style={styles.container}&gt; &lt;FlatList data={items} renderItem={({ item }) =&gt; ( &lt;View style={styles.item}&gt; &lt;AppText style={styles.number}&gt;Item {item.id} |&lt;/AppText&gt; &lt;View style={styles.buttonContainer}&gt; &lt;AppButton title={&quot;-&quot;} type={&quot;contained&quot;} style={styles.button} onPress={() =&gt; setQuantity(quantity - 1)} /&gt; &lt;/View&gt; &lt;AppText style={styles.number}&gt;{quantity}&lt;/AppText&gt; &lt;View style={styles.buttonContainer}&gt; &lt;AppButton title={&quot;+&quot;} type={&quot;contained&quot;} style={styles.button} onPress={() =&gt; setQuantity(quantity + 1)} /&gt; &lt;/View&gt; &lt;/View&gt; )} /&gt; &lt;/View&gt; </code></pre>
[ { "answer_id": 74374216, "author": "Luca Angrisani", "author_id": 13240452, "author_profile": "https://Stackoverflow.com/users/13240452", "pm_score": 2, "selected": false, "text": "<div class=\"container\">\n <div class=\"image\" *ngFor=\"let imageOrFile of imagesAndFiles\">\n <dispo-einsatz-dokumente-gallery-image-item [image]=\"imageOrFile\">\n </dispo-einsatz-dokumente-gallery-image-item>\n </div>\n</div>\n" }, { "answer_id": 74374220, "author": "Mr. Stash", "author_id": 13625800, "author_profile": "https://Stackoverflow.com/users/13625800", "pm_score": 3, "selected": true, "text": "<div class=\"container\">\n <div class=\"image\" *ngFor=\"let imageOrFile of imagesAndFiles\">\n <dispo-einsatz-dokumente-gallery-image-item\n [image]=\"imageOrFile\"\n ></dispo-einsatz-dokumente-gallery-image-item>\n </div>\n</div>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20307955/" ]
74,374,098
<p>Hi there I'm trying to use the following</p> <pre><code>sValue.substr(0,1000); </code></pre> <p>on the string</p> <p><code>&amp;lt;ul class='ulIndentRight'&amp;gt;&amp;lt;li&amp;gt;&amp;lt;b&amp;gt;Altissimo Guesthouse&amp;lt;/b&amp;gt; &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Luxury Room With Queen Bed Rtid 1 &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Extra&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt;person Charges May App Superior Room 1 Queen Bedlayout &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Bedroom Internet &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Free Wifi Entertainment &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Plasma Tv&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Satellite Channels&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; And Dvd Playerfood &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Drink &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Refrigerator&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Free Minibar Items&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Coffee&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt;tea Maker&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; And Free Bottled Waterbathroom &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Private Bathroom&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Bathtub Or Shower&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Free Toiletries&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; And A Hair Dryerpractical &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Safe&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Desk&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; And Iron&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt;ironing Board (on Request) Rollaway&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt;extra Beds Available On Requestcomfort &amp;lt;/li&amp;gt;&amp;lt;li&amp;gt; Climate&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt;controlled Air Conditioning And Daily Housekeepingnon&amp;lt;/li&amp;gt;&amp;lt;li&amp;gt;s</code></p> <p>but it keeps on returning a character count of 1136</p> <p>any ideas how to get only 1000 characters</p> <p>Thanks</p>
[ { "answer_id": 74374660, "author": "sme3x", "author_id": 19618943, "author_profile": "https://Stackoverflow.com/users/19618943", "pm_score": 0, "selected": false, "text": "let value = \"Paste_whole_string_in_here\"\nconsole.log(value.substring(0,1000))\n" }, { "answer_id": 74374773, "author": "Ian Brindley", "author_id": 1698723, "author_profile": "https://Stackoverflow.com/users/1698723", "pm_score": 1, "selected": false, "text": "substr" }, { "answer_id": 74375905, "author": "pier farrugia", "author_id": 19996700, "author_profile": "https://Stackoverflow.com/users/19996700", "pm_score": 2, "selected": true, "text": "let string = \n \"&lt;ul class='ulIndentRight'&gt;&lt;li&gt;&lt;b&gt;Altissimo Guesthouse&lt;/b&gt; &lt;/li&gt;&lt;li&gt; Luxury Room With Queen Bed Rtid 1 &lt;/li&gt;&lt;li&gt; Extra&lt;/li&gt;&lt;li&gt;person Charges May App Superior Room 1 Queen Bedlayout &lt;/li&gt;&lt;li&gt; Bedroom Internet &lt;/li&gt;&lt;li&gt; Free Wifi Entertainment &lt;/li&gt;&lt;li&gt; Plasma Tv&lt;/li&gt;&lt;li&gt; Satellite Channels&lt;/li&gt;&lt;li&gt; And Dvd Playerfood &lt;/li&gt;&lt;li&gt; Drink &lt;/li&gt;&lt;li&gt; Refrigerator&lt;/li&gt;&lt;li&gt; Free Minibar Items&lt;/li&gt;&lt;li&gt; Coffee&lt;/li&gt;&lt;li&gt;tea Maker&lt;/li&gt;&lt;li&gt; And Free Bottled Waterbathroom &lt;/li&gt;&lt;li&gt; Private Bathroom&lt;/li&gt;&lt;li&gt; Bathtub Or Shower&lt;/li&gt;&lt;li&gt; Free Toiletries&lt;/li&gt;&lt;li&gt; And A Hair Dryerpractical &lt;/li&gt;&lt;li&gt; Safe&lt;/li&gt;&lt;li&gt; Desk&lt;/li&gt;&lt;li&gt; And Iron&lt;/li&gt;&lt;li&gt;ironing Board (on Request) Rollaway&lt;/li&gt;&lt;li&gt;extra Beds Available On Requestcomfort &lt;/li&gt;&lt;li&gt; Climate&lt;/li&gt;&lt;li&gt;controlled Air Conditioning And Daily Housekeepingnon&lt;/li&gt;&lt;li&gt;s\";\n \n document.querySelector('.string').innerHTML = string;\n\n let string_div = document.querySelector('.string').textContent;\n charCount = Array.from(string_div).length;\n document.querySelector('.count').innerHTML = charCount;\n console.log(charCount);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/930798/" ]
74,374,099
<p>We have created new Rest API To AWS Api Gateway by importing our existing Swagger file. File contains quite long and good introduction for developers about our API. It is Markdown markup language. AWS Api gateway is able to show whole documentation correctly in documentations section. Our API is published to Developer portal. Developer portal shows only the first line of the description part of the documentation. Our Markdown documentation contains linefeeds,subtitles,lists few images and so on. Methods and other documentation parts are ok in Developer portal. I can edit and publish that API part of the documentation to the Developer portal. But only the first line. Is it possible to show better introduction about API in Developer portal than just one line description?</p> <p>I have asked that same question from AWS support including original JSON file. I haven't got an answer so I hope someone else knows how to publish longer API introduction to Developer portal. if this isn't possible is there way to include link to other documentation outside Developer portal?</p> <p>In AWS documentation there is JSON example about documentation. When this is copy/pasted to Api Gateway (Documentation -&gt; API part) and published to Developer portal only one description line is showing. <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-documenting-api-quick-start-with-console.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-documenting-api-quick-start-with-console.html</a></p> <p>{ &quot;info&quot;: { &quot;description&quot;: &quot;Your first API Gateway API.&quot;, &quot;contact&quot;: { &quot;name&quot;: &quot;John Doe&quot;, &quot;email&quot;: &quot;john.doe@api.com&quot; } } }</p>
[ { "answer_id": 74374660, "author": "sme3x", "author_id": 19618943, "author_profile": "https://Stackoverflow.com/users/19618943", "pm_score": 0, "selected": false, "text": "let value = \"Paste_whole_string_in_here\"\nconsole.log(value.substring(0,1000))\n" }, { "answer_id": 74374773, "author": "Ian Brindley", "author_id": 1698723, "author_profile": "https://Stackoverflow.com/users/1698723", "pm_score": 1, "selected": false, "text": "substr" }, { "answer_id": 74375905, "author": "pier farrugia", "author_id": 19996700, "author_profile": "https://Stackoverflow.com/users/19996700", "pm_score": 2, "selected": true, "text": "let string = \n \"&lt;ul class='ulIndentRight'&gt;&lt;li&gt;&lt;b&gt;Altissimo Guesthouse&lt;/b&gt; &lt;/li&gt;&lt;li&gt; Luxury Room With Queen Bed Rtid 1 &lt;/li&gt;&lt;li&gt; Extra&lt;/li&gt;&lt;li&gt;person Charges May App Superior Room 1 Queen Bedlayout &lt;/li&gt;&lt;li&gt; Bedroom Internet &lt;/li&gt;&lt;li&gt; Free Wifi Entertainment &lt;/li&gt;&lt;li&gt; Plasma Tv&lt;/li&gt;&lt;li&gt; Satellite Channels&lt;/li&gt;&lt;li&gt; And Dvd Playerfood &lt;/li&gt;&lt;li&gt; Drink &lt;/li&gt;&lt;li&gt; Refrigerator&lt;/li&gt;&lt;li&gt; Free Minibar Items&lt;/li&gt;&lt;li&gt; Coffee&lt;/li&gt;&lt;li&gt;tea Maker&lt;/li&gt;&lt;li&gt; And Free Bottled Waterbathroom &lt;/li&gt;&lt;li&gt; Private Bathroom&lt;/li&gt;&lt;li&gt; Bathtub Or Shower&lt;/li&gt;&lt;li&gt; Free Toiletries&lt;/li&gt;&lt;li&gt; And A Hair Dryerpractical &lt;/li&gt;&lt;li&gt; Safe&lt;/li&gt;&lt;li&gt; Desk&lt;/li&gt;&lt;li&gt; And Iron&lt;/li&gt;&lt;li&gt;ironing Board (on Request) Rollaway&lt;/li&gt;&lt;li&gt;extra Beds Available On Requestcomfort &lt;/li&gt;&lt;li&gt; Climate&lt;/li&gt;&lt;li&gt;controlled Air Conditioning And Daily Housekeepingnon&lt;/li&gt;&lt;li&gt;s\";\n \n document.querySelector('.string').innerHTML = string;\n\n let string_div = document.querySelector('.string').textContent;\n charCount = Array.from(string_div).length;\n document.querySelector('.count').innerHTML = charCount;\n console.log(charCount);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19373531/" ]
74,374,121
<p>I have two datasets in two react-selects. E.g:</p> <pre><code>options2={ [value: 1, label:&quot;apple&quot;,relationKey=1], [value: 2, label:&quot;orange&quot;,relationKey=2], [value: 3, label:&quot;banana&quot;,relationKey=2], [value: 4, label:&quot;pineapple&quot;,relationKey=2], } options1 ={ [value: 1, label: &quot;drink 1&quot;, relationKey=1], [value: 2, label: &quot;drink 2&quot;, relationKey=2] } </code></pre> <p>Now I have two react-selects where the second one depends on the values selected from the first one.</p> <p>First select:</p> <pre><code> &lt;Select options={options1} placeholder=&quot;Choose...&quot; isSearchable={true} onChange={handleChange} isMulti /&gt; </code></pre> <p>Second select:</p> <pre><code> &lt;Select options={options2} placeholder=&quot;Choose...&quot; onChange={handleChange} isMulti /&gt; </code></pre> <p>Now the scenario works all good transfering the selected value to one another, showing only the desired options and all that. So when I select <code>Drink 1</code> from the first select- it should only give me the options with <code>relationKey=1</code> and if I select <code>drink 2</code> it should list me the other options from option2 as well. And this is working very well.</p> <p>What I want to do is: when I select <code>Drink 1</code> and <code>Drink 2</code> and also select <code>apple, orange, banana, pineapple</code> from the second select, if I deselect Drink2, I should only have <code>apple</code> in the second select option list because <code>Drink1</code> is the only one selected.</p> <p>I have tried with tons of if/else's but the datasets are dynamic and I cannot always know their relationKeys and their values...</p> <p>Hope I was clear enough, thank you in advance.</p>
[ { "answer_id": 74374660, "author": "sme3x", "author_id": 19618943, "author_profile": "https://Stackoverflow.com/users/19618943", "pm_score": 0, "selected": false, "text": "let value = \"Paste_whole_string_in_here\"\nconsole.log(value.substring(0,1000))\n" }, { "answer_id": 74374773, "author": "Ian Brindley", "author_id": 1698723, "author_profile": "https://Stackoverflow.com/users/1698723", "pm_score": 1, "selected": false, "text": "substr" }, { "answer_id": 74375905, "author": "pier farrugia", "author_id": 19996700, "author_profile": "https://Stackoverflow.com/users/19996700", "pm_score": 2, "selected": true, "text": "let string = \n \"&lt;ul class='ulIndentRight'&gt;&lt;li&gt;&lt;b&gt;Altissimo Guesthouse&lt;/b&gt; &lt;/li&gt;&lt;li&gt; Luxury Room With Queen Bed Rtid 1 &lt;/li&gt;&lt;li&gt; Extra&lt;/li&gt;&lt;li&gt;person Charges May App Superior Room 1 Queen Bedlayout &lt;/li&gt;&lt;li&gt; Bedroom Internet &lt;/li&gt;&lt;li&gt; Free Wifi Entertainment &lt;/li&gt;&lt;li&gt; Plasma Tv&lt;/li&gt;&lt;li&gt; Satellite Channels&lt;/li&gt;&lt;li&gt; And Dvd Playerfood &lt;/li&gt;&lt;li&gt; Drink &lt;/li&gt;&lt;li&gt; Refrigerator&lt;/li&gt;&lt;li&gt; Free Minibar Items&lt;/li&gt;&lt;li&gt; Coffee&lt;/li&gt;&lt;li&gt;tea Maker&lt;/li&gt;&lt;li&gt; And Free Bottled Waterbathroom &lt;/li&gt;&lt;li&gt; Private Bathroom&lt;/li&gt;&lt;li&gt; Bathtub Or Shower&lt;/li&gt;&lt;li&gt; Free Toiletries&lt;/li&gt;&lt;li&gt; And A Hair Dryerpractical &lt;/li&gt;&lt;li&gt; Safe&lt;/li&gt;&lt;li&gt; Desk&lt;/li&gt;&lt;li&gt; And Iron&lt;/li&gt;&lt;li&gt;ironing Board (on Request) Rollaway&lt;/li&gt;&lt;li&gt;extra Beds Available On Requestcomfort &lt;/li&gt;&lt;li&gt; Climate&lt;/li&gt;&lt;li&gt;controlled Air Conditioning And Daily Housekeepingnon&lt;/li&gt;&lt;li&gt;s\";\n \n document.querySelector('.string').innerHTML = string;\n\n let string_div = document.querySelector('.string').textContent;\n charCount = Array.from(string_div).length;\n document.querySelector('.count').innerHTML = charCount;\n console.log(charCount);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17823599/" ]
74,374,139
<p>The function cycle removes the first element of a list puts it in the last position. I used pop and append to do so. The problem is that if you use:</p> <pre><code>l=[1,2,3] assert(cycle(l)== [2,3,1]) assert(cycle(cycle(l))== [3,1,2]) </code></pre> <p>it gives you an assertionerror, so i thought maybe the list is changed globally, but i do not want that and i cannot find a solution. I am new to programming.</p> <pre><code>l=[1,2,3] def cycle(y): x=y.pop(0) y.append(x) return (y) assert(cycle(l) == [2, 3, 1]) assert(cycle(cycle(l)) == [3, 1, 2]) assert(l == [1, 2, 3]) </code></pre> <p>I tried changing my code a little by using a copy of y to reset the list in the function afterwards but it seems that did not work either. Maybe i just did it wrong.</p> <pre><code>l=[1,2,3] def cycle(y): z=y.copy x=y.pop(0) y.append(x) return (y) y=z assert(cycle(l) == [2, 3, 1]) assert(cycle(cycle(l)) == [3, 1, 2]) assert(l == [1, 2, 3]) </code></pre>
[ { "answer_id": 74374660, "author": "sme3x", "author_id": 19618943, "author_profile": "https://Stackoverflow.com/users/19618943", "pm_score": 0, "selected": false, "text": "let value = \"Paste_whole_string_in_here\"\nconsole.log(value.substring(0,1000))\n" }, { "answer_id": 74374773, "author": "Ian Brindley", "author_id": 1698723, "author_profile": "https://Stackoverflow.com/users/1698723", "pm_score": 1, "selected": false, "text": "substr" }, { "answer_id": 74375905, "author": "pier farrugia", "author_id": 19996700, "author_profile": "https://Stackoverflow.com/users/19996700", "pm_score": 2, "selected": true, "text": "let string = \n \"&lt;ul class='ulIndentRight'&gt;&lt;li&gt;&lt;b&gt;Altissimo Guesthouse&lt;/b&gt; &lt;/li&gt;&lt;li&gt; Luxury Room With Queen Bed Rtid 1 &lt;/li&gt;&lt;li&gt; Extra&lt;/li&gt;&lt;li&gt;person Charges May App Superior Room 1 Queen Bedlayout &lt;/li&gt;&lt;li&gt; Bedroom Internet &lt;/li&gt;&lt;li&gt; Free Wifi Entertainment &lt;/li&gt;&lt;li&gt; Plasma Tv&lt;/li&gt;&lt;li&gt; Satellite Channels&lt;/li&gt;&lt;li&gt; And Dvd Playerfood &lt;/li&gt;&lt;li&gt; Drink &lt;/li&gt;&lt;li&gt; Refrigerator&lt;/li&gt;&lt;li&gt; Free Minibar Items&lt;/li&gt;&lt;li&gt; Coffee&lt;/li&gt;&lt;li&gt;tea Maker&lt;/li&gt;&lt;li&gt; And Free Bottled Waterbathroom &lt;/li&gt;&lt;li&gt; Private Bathroom&lt;/li&gt;&lt;li&gt; Bathtub Or Shower&lt;/li&gt;&lt;li&gt; Free Toiletries&lt;/li&gt;&lt;li&gt; And A Hair Dryerpractical &lt;/li&gt;&lt;li&gt; Safe&lt;/li&gt;&lt;li&gt; Desk&lt;/li&gt;&lt;li&gt; And Iron&lt;/li&gt;&lt;li&gt;ironing Board (on Request) Rollaway&lt;/li&gt;&lt;li&gt;extra Beds Available On Requestcomfort &lt;/li&gt;&lt;li&gt; Climate&lt;/li&gt;&lt;li&gt;controlled Air Conditioning And Daily Housekeepingnon&lt;/li&gt;&lt;li&gt;s\";\n \n document.querySelector('.string').innerHTML = string;\n\n let string_div = document.querySelector('.string').textContent;\n charCount = Array.from(string_div).length;\n document.querySelector('.count').innerHTML = charCount;\n console.log(charCount);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458448/" ]
74,374,158
<p>What is the best way to merge array contents from JavaScript objects sharing multiple key in common and keys list is also dynamic so we don't know that how much keys are there key is there in keyname with prefix?</p> <p>How can array in the example below be reorganized into output?</p> <pre><code> var keys = [{&quot;id&quot;:&quot;ABC&quot;,&quot;name&quot;:&quot;abc&quot;},{&quot;id&quot;:&quot;DEF&quot;,&quot;name&quot;:&quot;def&quot;},{&quot;id&quot;:&quot;GHI&quot;,&quot;name&quot;:&quot;ghi&quot;}] var array = [ { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Web&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;East&quot;, &quot;device&quot;: &quot;Samsung&quot; }, { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Mobile&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;West&quot;, &quot;device&quot;: [&quot;MI&quot;, &quot;Oppo&quot;] }, { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Web&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;East&quot; &quot;device&quot;: &quot;Apple&quot; }, { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Mobile&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;West&quot;, &quot;device&quot;: &quot;Blackberry&quot; }, { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Tab&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;North&quot;, &quot;device&quot;: &quot;One Plus&quot; } ] </code></pre> <p>Expected Output:</p> <pre><code>Var output = [ { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Web&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;East&quot;, &quot;device&quot;: [&quot;Samsung&quot;, &quot;Apple&quot;] }, { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Mobile&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;West&quot;, &quot;device&quot;: [&quot;MI&quot;, &quot;Oppo&quot;, &quot;Blackberry&quot;] }, { &quot;input_ABC-operator&quot;: &quot;==&quot;, &quot;input_ABC-expression&quot;: &quot;Tab&quot;, &quot;input_DEF-operator&quot;: &quot;==&quot;, &quot;input_DEF-expression&quot;: &quot;North&quot;, &quot;device&quot;: [&quot;One Plus&quot;] } ] </code></pre>
[ { "answer_id": 74374660, "author": "sme3x", "author_id": 19618943, "author_profile": "https://Stackoverflow.com/users/19618943", "pm_score": 0, "selected": false, "text": "let value = \"Paste_whole_string_in_here\"\nconsole.log(value.substring(0,1000))\n" }, { "answer_id": 74374773, "author": "Ian Brindley", "author_id": 1698723, "author_profile": "https://Stackoverflow.com/users/1698723", "pm_score": 1, "selected": false, "text": "substr" }, { "answer_id": 74375905, "author": "pier farrugia", "author_id": 19996700, "author_profile": "https://Stackoverflow.com/users/19996700", "pm_score": 2, "selected": true, "text": "let string = \n \"&lt;ul class='ulIndentRight'&gt;&lt;li&gt;&lt;b&gt;Altissimo Guesthouse&lt;/b&gt; &lt;/li&gt;&lt;li&gt; Luxury Room With Queen Bed Rtid 1 &lt;/li&gt;&lt;li&gt; Extra&lt;/li&gt;&lt;li&gt;person Charges May App Superior Room 1 Queen Bedlayout &lt;/li&gt;&lt;li&gt; Bedroom Internet &lt;/li&gt;&lt;li&gt; Free Wifi Entertainment &lt;/li&gt;&lt;li&gt; Plasma Tv&lt;/li&gt;&lt;li&gt; Satellite Channels&lt;/li&gt;&lt;li&gt; And Dvd Playerfood &lt;/li&gt;&lt;li&gt; Drink &lt;/li&gt;&lt;li&gt; Refrigerator&lt;/li&gt;&lt;li&gt; Free Minibar Items&lt;/li&gt;&lt;li&gt; Coffee&lt;/li&gt;&lt;li&gt;tea Maker&lt;/li&gt;&lt;li&gt; And Free Bottled Waterbathroom &lt;/li&gt;&lt;li&gt; Private Bathroom&lt;/li&gt;&lt;li&gt; Bathtub Or Shower&lt;/li&gt;&lt;li&gt; Free Toiletries&lt;/li&gt;&lt;li&gt; And A Hair Dryerpractical &lt;/li&gt;&lt;li&gt; Safe&lt;/li&gt;&lt;li&gt; Desk&lt;/li&gt;&lt;li&gt; And Iron&lt;/li&gt;&lt;li&gt;ironing Board (on Request) Rollaway&lt;/li&gt;&lt;li&gt;extra Beds Available On Requestcomfort &lt;/li&gt;&lt;li&gt; Climate&lt;/li&gt;&lt;li&gt;controlled Air Conditioning And Daily Housekeepingnon&lt;/li&gt;&lt;li&gt;s\";\n \n document.querySelector('.string').innerHTML = string;\n\n let string_div = document.querySelector('.string').textContent;\n charCount = Array.from(string_div).length;\n document.querySelector('.count').innerHTML = charCount;\n console.log(charCount);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345789/" ]
74,374,168
<p>I am trying to build iOS app from expo managed project. The build fails At Pod installation step.</p> <p>In Expo SDK 44, 45 everything was okay. But when I upgrade to SDK 46, I am facing the issue.</p> <p>Here is my package.json</p> <pre><code>{ &quot;name&quot;: &quot;App1234&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &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;dependencies&quot;: { &quot;@expo/vector-icons&quot;: &quot;^13.0.0&quot;, &quot;@openspacelabs/react-native-zoomable-view&quot;: &quot;^2.0.4&quot;, &quot;@react-native-community/datetimepicker&quot;: &quot;6.2.0&quot;, &quot;@react-native-community/netinfo&quot;: &quot;9.3.0&quot;, &quot;@react-native-community/slider&quot;: &quot;4.2.3&quot;, &quot;@react-native-google-signin/google-signin&quot;: &quot;^8.1.0&quot;, &quot;@react-navigation/bottom-tabs&quot;: &quot;^6.4.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.2&quot;, &quot;@stripe/stripe-react-native&quot;: &quot;0.13.1&quot;, &quot;@types/react-native&quot;: &quot;~0.69.1&quot;, &quot;apisauce&quot;: &quot;^2.1.6&quot;, &quot;expo&quot;: &quot;~46.0.13&quot;, &quot;expo-apple-authentication&quot;: &quot;^4.3.0&quot;, &quot;expo-constants&quot;: &quot;^13.2.4&quot;, &quot;expo-document-picker&quot;: &quot;^10.3.0&quot;, &quot;expo-firebase-recaptcha&quot;: &quot;^2.3.0&quot;, &quot;expo-font&quot;: &quot;^10.2.1&quot;, &quot;expo-image-picker&quot;: &quot;^13.3.1&quot;, &quot;expo-linear-gradient&quot;: &quot;^11.4.0&quot;, &quot;expo-linking&quot;: &quot;^3.2.2&quot;, &quot;expo-location&quot;: &quot;^14.3.0&quot;, &quot;expo-notifications&quot;: &quot;^0.16.1&quot;, &quot;expo-secure-store&quot;: &quot;^11.3.0&quot;, &quot;expo-tracking-transparency&quot;: &quot;^2.3.1&quot;, &quot;expo-updates&quot;: &quot;^0.14.6&quot;, &quot;firebase&quot;: &quot;9.9.2&quot;, &quot;formik&quot;: &quot;^2.2.9&quot;, &quot;html-entities&quot;: &quot;^2.3.3&quot;, &quot;lodash&quot;: &quot;^4.17.21&quot;, &quot;lottie-react-native&quot;: &quot;5.1.3&quot;, &quot;mime&quot;: &quot;^3.0.0&quot;, &quot;moment&quot;: &quot;^2.29.4&quot;, &quot;qs&quot;: &quot;^6.11.0&quot;, &quot;react&quot;: &quot;18.0.0&quot;, &quot;react-native&quot;: &quot;0.69.6&quot;, &quot;react-native-draggable-flatlist&quot;: &quot;^3.1.2&quot;, &quot;react-native-fbsdk-next&quot;: &quot;^11.0.0&quot;, &quot;react-native-geocoding&quot;: &quot;^0.5.0&quot;, &quot;react-native-gesture-handler&quot;: &quot;~2.5.0&quot;, &quot;react-native-google-mobile-ads&quot;: &quot;^8.2.0&quot;, &quot;react-native-maps&quot;: &quot;0.31.1&quot;, &quot;react-native-phone-number-input&quot;: &quot;^2.1.0&quot;, &quot;react-native-progress&quot;: &quot;^5.0.0&quot;, &quot;react-native-razorpay&quot;: &quot;^2.2.9&quot;, &quot;react-native-read-more-text&quot;: &quot;^1.1.2&quot;, &quot;react-native-reanimated&quot;: &quot;~2.9.1&quot;, &quot;react-native-safe-area-context&quot;: &quot;4.3.1&quot;, &quot;react-native-screens&quot;: &quot;~3.15.0&quot;, &quot;react-native-svg&quot;: &quot;12.3.0&quot;, &quot;react-native-webview&quot;: &quot;11.23.0&quot;, &quot;react-native-youtube-iframe&quot;: &quot;^2.2.2&quot;, &quot;typescript&quot;: &quot;^4.6.3&quot;, &quot;yup&quot;: &quot;^0.32.11&quot; }, &quot;devDependencies&quot;: { &quot;@babel/core&quot;: &quot;^7.12.9&quot; }, &quot;private&quot;: true } </code></pre> <p>Here is Install Pods logs</p> <pre><code>Using Expo modules Auto-generating `.xcode.env.local` with $NODE_BINARY=/Users/expo/.nvm/versions/node/v16.13.2/bin/node Adding a custom script phase for Pod RNGoogleMobileAds: [RNGoogleMobileAds] Configuration Auto-linking React Native modules for target `HomListi`: RNDateTimePicker, RNGestureHandler, RNGoogleMobileAds, RNGoogleSignin, RNReanimated, RNSVG, RNScreens, lottie-react-native, react-native-fbsdk-next, react-native-maps, react-native-netinfo, react-native-razorpay, react-native-safe-area-context, react-native-slider, react-native-webview, and stripe-react-native [Codegen] Generating ./build/generated/ios/React-Codegen.podspec.json Analyzing dependencies Fetching podspec for `DoubleConversion` from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec` [Codegen] Found FBReactNativeSpec Fetching podspec for `RCT-Folly` from `../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec` Fetching podspec for `boost` from `../node_modules/react-native/third-party-podspecs/boost.podspec` Fetching podspec for `glog` from `../node_modules/react-native/third-party-podspecs/glog.podspec` [stderr] /Users/expo/workingdir/build/node_modules/react-native-fbsdk-next/react-native-fbsdk-next.podspec:4: warning: already initialized constant Pod::FBSDKVersion [stderr] /Users/expo/workingdir/build/node_modules/react-native-fbsdk-next/react-native-fbsdk-next.podspec:4: warning: previous definition of FBSDKVersion was here Adding spec repo `trunk` with CDN `https://cdn.cocoapods.org/` [!] CocoaPods could not find compatible versions for pod &quot;ExpoAdapterGoogleSignIn&quot;: In Podfile: ExpoAdapterGoogleSignIn (from `../node_modules/@react-native-google-signin/google-signin/ios`) Specs satisfying the `ExpoAdapterGoogleSignIn (from `../node_modules/@react-native-google-signin/google-signin/ios`)` dependency were found, but they required a higher minimum deployment target. Error: Compatible versions of some pods could not be resolved. You are seeing this error because either: - Versions in the cached Podfile.lock do not match required values in Podspecs of some installed libraries. To fix this, you can re-run build command with &quot;--clear-cache&quot; option, or select &quot;Clear cache and retry build&quot; on the build page. - Some of the pods used in your project depend on different versions of the same pod. See logs for more information. </code></pre> <p>I've used 'eas build -p ios' command also used 'eas build -p ios --clear-cache'</p> <p>didn't work.</p> <p>Can anybody help please. Please please please!!!!</p>
[ { "answer_id": 74565601, "author": "Hamed Navabian", "author_id": 9474611, "author_profile": "https://Stackoverflow.com/users/9474611", "pm_score": 1, "selected": false, "text": "platform :ios, '13.0'" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8460578/" ]
74,374,170
<p>i want to use the below values into different columns inside the table now they are storing into one i tried REGEXP_SUBSTR but still i can't use them separately .. any help would be apricated</p> <p>`</p> <pre><code>SELECT REGEXP_SUBSTR('One Thousand Four Hundred Forty Six', '[^ ]+', 1, level) AS parts FROM dual CONNECT BY REGEXP_SUBSTR('One Thousand Four Hundred Forty Six', '[^ ]+', 1, level) IS NOT NULL; the output should be like this : column A : One Thousand column B : Four Hundred column C : Forty Six </code></pre> <p>`</p> <p>the above is my attempt</p>
[ { "answer_id": 74565601, "author": "Hamed Navabian", "author_id": 9474611, "author_profile": "https://Stackoverflow.com/users/9474611", "pm_score": 1, "selected": false, "text": "platform :ios, '13.0'" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13420452/" ]
74,374,178
<p>I want to create a dictionary from the values I get from Excel cells.</p> <p>This my Excel spreadsheet:</p> <p><img src="https://i.stack.imgur.com/Z6yyM.png" alt="" /></p> <p>My expectation about the dictionary is like this:</p> <pre class="lang-py prettyprint-override"><code>{'Ancolmekar': array([ 3. , 20. , 6. , ..., 0.5, 0.5, 0.5]), 'Cidurian': array([0.5, 0.5, 0.5, ..., 0.5, 0.5, 6. ]), 'Dayeuhkolot': array([0.5, 0.5, 0.5, ..., 5.5, 1.5, 0.5]), 'Hantap': array([ 1.5, 17.5, 3. , ..., 0.5, 5. , 1.5]), 'Kertasari': array([ 1.5, 2.5, 0.5, ..., 1.5, 10. , 1.5]), 'Meteolembang': array([ 0.5, 0.5, 0.5, ..., 0.5, 0.5, 10.5]), 'Sapan': array([ 0.5, 0.5, 6. , ..., 0.5, 13.5, 24. ])} </code></pre> <p>Any idea of the code?</p> <p>My code is like this:</p> <pre class="lang-py prettyprint-override"><code># Read Excel data xl = pd.read_excel('export_3.xlsx') contoh = pd.read_excel('export_3.xlsx', header=None, sheet_name='EPA BINER') contoh1 = pd.read_excel('export_3.xlsx', header=None, sheet_name='EPA') contoh2 = pd.read_excel('export_3.xlsx', header=None, sheet_name='SHORT BINER') contoh3 = pd.read_excel('export_3.xlsx', header=None, sheet_name='SHORT EPA') contoh4 = pd.read_excel('export_3.xlsx', header=None, sheet_name='LONG BINER') contoh5 = pd.read_excel('export_3.xlsx', header=None, sheet_name='LONG EPA') </code></pre> <p>The total of rows is 43824.</p>
[ { "answer_id": 74374436, "author": "Willy Lutz", "author_id": 18771355, "author_profile": "https://Stackoverflow.com/users/18771355", "pm_score": 2, "selected": true, "text": "path = 'export_3.xlsx'\nfile = pd.ExcelFile(path)\nsheets = file.sheet_names\n\nfor sheet in sheets:\n sheet_dict = {}\n contoh = pd.read_excel(path, sheet_name=sheet)\n for col in contoh.columns:\n sheet_dict[col] = list(contoh[col])\n print(sheet_dict, \"\\n\\n\\n\")\n \n" }, { "answer_id": 74374539, "author": "amogha_sharma", "author_id": 19199059, "author_profile": "https://Stackoverflow.com/users/19199059", "pm_score": 0, "selected": false, "text": "contoh = pd.read_excel('export_3.xlsx',header=None,sheet_name='EPA BINER')\ndf = contoh.transpose()\ndf['new'] = df.values.tolist()\ndf = df['new']\ndf.to_json(orient = 'columns')\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12368138/" ]
74,374,199
<p>i'm currently trying to make a Logbox for my webapp. It gets an Array of logs and should display them row by row in a div. Im using ngFor and looping trough my Array of logs and then displaying them.</p> <p>My problem is now that the logs get displayed infinite times, not just 5 times (5 Array entries in list) like it should.</p> <p>Does somebody have a hint what im missing?</p> <p><strong>logs.component.html</strong></p> <pre><code>&lt;div class=&quot;logContent&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-12&quot; *ngFor=&quot;let log of this.logService.getLogs()&quot;&gt; &lt;app-singlelog [when]=&quot;log.when&quot; [type]=&quot;log.type&quot; [data]=&quot;log.data&quot;&gt;&lt;/app-singlelog&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>log.service.ts</strong></p> <pre><code>export class LogService { private logArray = []; /* private logObject = {} as Log; */ constructor(private httpservice: HttpserviceService) { } public getLogs(): Array&lt;Log&gt; { this.httpservice.getLogs().subscribe(data =&gt; { data.forEach(index =&gt; { let logObject = {} as Log; logObject.when = index.when; logObject.type = index.type; logObject.data = index.data; this.logArray.push(logObject); }) } ) return this.logArray; } } </code></pre> <p>Thanks :)</p>
[ { "answer_id": 74374331, "author": "Loránd Péter", "author_id": 6146963, "author_profile": "https://Stackoverflow.com/users/6146963", "pm_score": 4, "selected": true, "text": "getLogs()" }, { "answer_id": 74374437, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 2, "selected": false, "text": "logs$ = this.httpservice\n .getLogs()\n .pipe(\n shareReplay(),\n map((data) => data.map(({ when, type, data }) => ({ when, type, data })))\n );\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458614/" ]
74,374,214
<p>I would like to have a code in order to remove special character such as <code>?</code> from values in a column in a dataframe.</p> <p>I would like to remove from</p> <pre><code>()?()()() hello world' </code></pre> <p>the <code>()</code> and the <code>?</code>.</p> <p>However, when I am using the following code:</p> <pre class="lang-py prettyprint-override"><code>Community_final_level_2_description = Community_final_level_2_description.replace('()', ' ', regex=True) </code></pre> <p>or</p> <pre class="lang-py prettyprint-override"><code>Community_final_level_2_description.replace('?', ' ', regex=True) </code></pre> <p>it is not working and I get an error.</p> <p>Can someone provide me the proper code ?</p>
[ { "answer_id": 74374318, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "(" }, { "answer_id": 74374453, "author": "Gonçalo Peres", "author_id": 7109869, "author_profile": "https://Stackoverflow.com/users/7109869", "pm_score": 1, "selected": false, "text": "df" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19543356/" ]
74,374,221
<p>I wrote several commands to transform a dataframe but i would like to simplify the code that I wrote in four parts. Part 1,2 and 3 are to make calculation of column 1, 2 and 3 (count the number of time a value is repeated for each column and complete for missing number comprised between 0 and the max of value of the three column). The fourth part is to join the previous output.</p> <p>I would like to simplify it in order to make the transformation of the 3 column in one block of code instead of 4. Is it possible to do it without using function ?</p> <p>Thank you in advance.</p> <pre><code>set.seed(1234) # Data A=sample(0:10, 20, replace = TRUE) B=sample(0:10, 20, replace = TRUE) C=sample(0:10, 20, replace = TRUE) df=data.frame(A,B,C) A B C 1 9 2 0 2 5 3 5 3 4 9 7 4 8 4 2 5 4 1 5 6 5 7 0 7 3 10 0 8 1 3 8 9 6 2 7 10 5 6 9 11 9 8 0 12 5 2 10 13 3 5 7 14 7 3 9 15 3 7 5 16 3 9 2 17 4 10 8 18 7 1 2 19 3 4 5 20 7 5 8 # Count for A df2=data.frame(A=0:max(max(df$A),max(df$B),max(df$C))) df3_A= df %&gt;% select(A) %&gt;% group_by(A) %&gt;% mutate(A_number= n()) %&gt;% distinct(A_number, .keep_all = TRUE) %&gt;% ungroup() %&gt;% complete (df2) df3_A$A_number[is.na(df3_A$A_number)]=0 # Count for B df2=data.frame(B=0:max(max(df$A),max(df$B),max(df$C))) df3_B= df %&gt;% select(B) %&gt;% group_by(B) %&gt;% mutate(B_number= n()) %&gt;% distinct(B_number, .keep_all = TRUE) %&gt;% ungroup() %&gt;% complete (df2) df3_B$B_number[is.na(df3_B$B_number)]=0 # Count for C df2=data.frame(C=0:max(max(df$A),max(df$B),max(df$C))) df3_C= df %&gt;% select(C) %&gt;% group_by(C) %&gt;% mutate(C_number= n()) %&gt;% distinct(C_number, .keep_all = TRUE) %&gt;% ungroup() %&gt;% complete (df2) df3_C$C_number[is.na(df3_C$C_number)]=0 # Join df3= df3_A %&gt;% left_join(df3_B, by=c(&quot;A&quot;=&quot;B&quot;)) %&gt;% left_join(df3_C, by=c(&quot;A&quot;=&quot;C&quot;)) A A_number B_number C_number &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 0 0 0 4 2 1 1 2 0 3 2 0 3 3 4 3 5 3 0 5 4 3 2 0 6 5 4 2 4 7 6 1 1 0 8 7 3 2 3 9 8 1 1 3 10 9 2 2 2 11 10 0 2 1 </code></pre>
[ { "answer_id": 74374497, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "vctrs::vec_count" }, { "answer_id": 74374552, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>% \n pivot_longer(cols = everything()) %>%\n count(name, value) %>%\n pivot_wider(values_from = n, values_fill = 0) %>%\n arrange(value)\n\n# A tibble: 11 × 4\n value A B C\n <int> <int> <int> <int>\n 1 0 0 0 4\n 2 1 1 2 0\n 3 2 0 3 3\n 4 3 5 3 0\n 5 4 3 2 0\n 6 5 4 2 4\n 7 6 1 1 0\n 8 7 3 2 3\n 9 8 1 1 3\n10 9 2 2 2\n11 10 0 2 1\n" }, { "answer_id": 74374821, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "as.data.frame.matrix(table(stack(df)))\n# A B C\n# 0 0 0 4\n# 1 1 2 0\n# 2 0 3 3\n# 3 5 3 0\n# 4 3 2 0\n# 5 4 2 4\n# 6 1 1 0\n# 7 3 2 3\n# 8 1 1 3\n# 9 2 2 2\n# 10 0 2 1\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16108900/" ]
74,374,245
<p>I have the same function repeating over and over again. I'd like to combine it into one so that I can call it without having to write long code.</p> <pre><code>totalV .filter((nan) =&gt; nan) .reduce((a, b) =&gt; a + b, 0) .toFixed(2) </code></pre> <p>Basically, I want to save it into a const or something.. and then call it whenever needed I tried to do something like this:</p> <pre><code>const Vol = .filter((nan) =&gt; nan) .reduce((a, b) =&gt; a + b, 0) .toFixed(2) </code></pre> <p>But unfortunately I wasn't able to do so, because it's asking for &quot;expression&quot; or array to do this funciton on ( something before EXPRESSION.filter.reduce )</p> <p>EDIT: MORE INFO</p> <pre><code>{ totalV.filter((nan) =&gt; nan) .reduce((a, b) =&gt; a + b, 0) .toFixed(2) == 0.0 ? 0 : totalV.filter((nan) =&gt; nan) .reduce((a, b) =&gt; a + b, 0) .toFixed(2)} </code></pre> <p>So I have this conditional render that I'm writing in a few spots.. however totalV can change, but the rest of the code is the same.. so I thought to store the code that keeps repeating into a variable or something like</p> <pre><code>const repeatableCode = .filter((nan) =&gt; nan) .reduce((a, b) =&gt; a + b, 0) .toFixed(2) </code></pre> <p>but it refuses to work without an array/object being provided ahead of time</p>
[ { "answer_id": 74374497, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "vctrs::vec_count" }, { "answer_id": 74374552, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>% \n pivot_longer(cols = everything()) %>%\n count(name, value) %>%\n pivot_wider(values_from = n, values_fill = 0) %>%\n arrange(value)\n\n# A tibble: 11 × 4\n value A B C\n <int> <int> <int> <int>\n 1 0 0 0 4\n 2 1 1 2 0\n 3 2 0 3 3\n 4 3 5 3 0\n 5 4 3 2 0\n 6 5 4 2 4\n 7 6 1 1 0\n 8 7 3 2 3\n 9 8 1 1 3\n10 9 2 2 2\n11 10 0 2 1\n" }, { "answer_id": 74374821, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "as.data.frame.matrix(table(stack(df)))\n# A B C\n# 0 0 0 4\n# 1 1 2 0\n# 2 0 3 3\n# 3 5 3 0\n# 4 3 2 0\n# 5 4 2 4\n# 6 1 1 0\n# 7 3 2 3\n# 8 1 1 3\n# 9 2 2 2\n# 10 0 2 1\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18984558/" ]
74,374,291
<p>My user account can use the Google Classroom web UI to see all the announcements for a given course. Trying to pull them programmatically using the Google Classroom API.</p> <p>I've set up an app with Oauth consent screen covering (for test purposes) <strong>ALL</strong> the scopes listed under the Google Classroom API, and can run the consent flow with my user account to get an access token.</p> <p>I can successfully GET course details by curl'ing <code>https://classroom.googleapis.com/v1/courses/&lt;my course ID&gt;</code> using the access token obtained from the oauth flow. However, when I GET <code>https://classroom.googleapis.com/v1/courses/&lt;my course ID&gt;/announcements</code> with the same token, I get the following:</p> <pre><code>{ &quot;error&quot;: { &quot;code&quot;: 403, &quot;message&quot;: &quot;Request had insufficient authentication scopes.&quot;, &quot;status&quot;: &quot;PERMISSION_DENIED&quot;, &quot;details&quot;: [ { &quot;@type&quot;: &quot;type.googleapis.com/google.rpc.ErrorInfo&quot;, &quot;reason&quot;: &quot;ACCESS_TOKEN_SCOPE_INSUFFICIENT&quot;, &quot;domain&quot;: &quot;googleapis.com&quot;, &quot;metadata&quot;: { &quot;method&quot;: &quot;google.classroom.v1.Work.ListAnnouncements&quot;, &quot;service&quot;: &quot;classroom.googleapis.com&quot; } } ] } } </code></pre> <p>Behaviour is same in using both client libraries as well as raw REST calls.</p> <p>Am I missing an auth scope (I switched them all on), am I just not allowed to do this since I'm not the course owner, or am I doing something else wrong? Advice please!</p> <pre><code></code></pre>
[ { "answer_id": 74374497, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "vctrs::vec_count" }, { "answer_id": 74374552, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>% \n pivot_longer(cols = everything()) %>%\n count(name, value) %>%\n pivot_wider(values_from = n, values_fill = 0) %>%\n arrange(value)\n\n# A tibble: 11 × 4\n value A B C\n <int> <int> <int> <int>\n 1 0 0 0 4\n 2 1 1 2 0\n 3 2 0 3 3\n 4 3 5 3 0\n 5 4 3 2 0\n 6 5 4 2 4\n 7 6 1 1 0\n 8 7 3 2 3\n 9 8 1 1 3\n10 9 2 2 2\n11 10 0 2 1\n" }, { "answer_id": 74374821, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "as.data.frame.matrix(table(stack(df)))\n# A B C\n# 0 0 0 4\n# 1 1 2 0\n# 2 0 3 3\n# 3 5 3 0\n# 4 3 2 0\n# 5 4 2 4\n# 6 1 1 0\n# 7 3 2 3\n# 8 1 1 3\n# 9 2 2 2\n# 10 0 2 1\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458663/" ]
74,374,292
<p>I have the below code:</p> <pre><code>window.addEventListener('mousemove', ()=&gt;{ myInterval = setTimeout(mouseMove, 2000); }); const mouseMove = () =&gt; { console.log('first console'); onMouseMove = (e) =&gt; console.log(&quot;mouse location:&quot;, e.x, e.y) } </code></pre> <p>Only at the end of the timeout I should console.log the coordinates of the mouse; however, onMouseMove is not respecting the timeout logic.</p> <p>The console.log('first console') is triggered only at the end of the 2 seconds, but onMouseMove triggers with every move of the mouse.</p> <p>In addition to the above, I would like to console.log only the last coordinate at the end of this 2 seconds.</p> <p>I've tried changing between setInterval and setTimeout, also clearing these interval and timeout, but still didnt work as intended.</p>
[ { "answer_id": 74374497, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 1, "selected": false, "text": "vctrs::vec_count" }, { "answer_id": 74374552, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf %>% \n pivot_longer(cols = everything()) %>%\n count(name, value) %>%\n pivot_wider(values_from = n, values_fill = 0) %>%\n arrange(value)\n\n# A tibble: 11 × 4\n value A B C\n <int> <int> <int> <int>\n 1 0 0 0 4\n 2 1 1 2 0\n 3 2 0 3 3\n 4 3 5 3 0\n 5 4 3 2 0\n 6 5 4 2 4\n 7 6 1 1 0\n 8 7 3 2 3\n 9 8 1 1 3\n10 9 2 2 2\n11 10 0 2 1\n" }, { "answer_id": 74374821, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "as.data.frame.matrix(table(stack(df)))\n# A B C\n# 0 0 0 4\n# 1 1 2 0\n# 2 0 3 3\n# 3 5 3 0\n# 4 3 2 0\n# 5 4 2 4\n# 6 1 1 0\n# 7 3 2 3\n# 8 1 1 3\n# 9 2 2 2\n# 10 0 2 1\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458690/" ]
74,374,294
<p>I have been on this problem for hours but couldn't get close to solution. Any help will be appreciated.</p> <pre><code>public static int enterTheAmount(){ int final LOTTO_PRICE = 1000; int amount = Integer.parseInt(Console.readLine()); if(amount%LOTTO_PRICE!=0) throw new IllegalArgumentException(); return amount/LOTTO_PRICE; } </code></pre> <p>Here, a user is going to enter a number, and if the number is not divisible by 1000, it throws an exception.</p> <pre><code>void validateTheEnteredAmount(){ final String INVALID_NUMBER = &quot;1234&quot;; InputStream in = new ByteArrayInputStream(INVALID_NUMBER.getBytes()); System.setIn(in); assertThat(Application.enterTheAmount()). isInstanceOf(IllegalArgumentException.class); } </code></pre> <p>And I want to know when invalid number is entered, illegalArgumentException is thrown. I used assertThat method &amp; isInstanceOf methods to validate. but for some reason, the test keeps failing.. Anyone with clues, please help</p> <p>i used inputStream to store the number into the scanner. On the console, it shows that illegalargumentexception is thrown, but the test fails..</p>
[ { "answer_id": 74374350, "author": "Leonardo Emmanuel de Azevedo", "author_id": 19979867, "author_profile": "https://Stackoverflow.com/users/19979867", "pm_score": 1, "selected": false, "text": "assertThrows" }, { "answer_id": 74374516, "author": "Sobhan", "author_id": 7189597, "author_profile": "https://Stackoverflow.com/users/7189597", "pm_score": -1, "selected": true, "text": "Class" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15440478/" ]
74,374,349
<p>Is it possible to retrieve a true/false answer from a CQL query that checks a condition -- for example, if a collection has a specific value?</p> <p>Consider:</p> <pre><code>CREATE TABLE Test (Id text PRIMARY KEY, Roles set&lt;text&gt;) INSERT INTO Test(Id, Roles) VALUES ('123', {'Driver', 'Pilot', 'Janitor'}) </code></pre> <p>I would like to get a true or false value depending on whether or not the set associated with <code>Id='123'</code> contains a specific value. Here is an imaginary syntax for what I'd like to get; it does not work:</p> <pre><code>SELECT Roles CONTAINS 'Pilot' // &lt;&lt;== Not a valid syntax; this does not work FROM Test WHERE Id = '123' </code></pre>
[ { "answer_id": 74374350, "author": "Leonardo Emmanuel de Azevedo", "author_id": 19979867, "author_profile": "https://Stackoverflow.com/users/19979867", "pm_score": 1, "selected": false, "text": "assertThrows" }, { "answer_id": 74374516, "author": "Sobhan", "author_id": 7189597, "author_profile": "https://Stackoverflow.com/users/7189597", "pm_score": -1, "selected": true, "text": "Class" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335858/" ]
74,374,365
<p>So Im using useQuery from react-query I need to return response from API as a User (based on my interface).</p> <p>I did it like this:</p> <pre><code>export const getUsersQuery = () =&gt; &quot;users&quot;; export const useUsersQuery = () =&gt; useQuery(getUsersQueryKey(), () =&gt; axios .get(&quot;API ENDPOINT&quot;) .then((response) =&gt; response.data as User[]) ); </code></pre> <p>My friend told me that this is not wrong but its also not &quot;best practice&quot; and that I should look up how to retype my response without the <code>response.data as User[]</code> using generic parameters of useQuery and pass the array of Users as one of the parameters.</p> <p>Can somebody walk me through how to change my code?</p>
[ { "answer_id": 74375067, "author": "Marat", "author_id": 15775222, "author_profile": "https://Stackoverflow.com/users/15775222", "pm_score": 3, "selected": true, "text": "useQuery<User[]>(key, queryFn);\n" }, { "answer_id": 74379386, "author": "m_novak", "author_id": 17747601, "author_profile": "https://Stackoverflow.com/users/17747601", "pm_score": 0, "selected": false, "text": "useQuery<User[]>(key, queryFn);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17747601/" ]
74,374,366
<p>I have a dataframe that looks like this:</p> <pre><code> ID Age Score 0 9 5 3 1 4 6 1 2 9 7 2 3 3 2 1 4 12 1 15 5 2 25 6 6 9 5 4 7 9 5 61 8 4 2 12 </code></pre> <p>I want to sort based on the first column, then the second column, and so on.</p> <p>So I want my output to be this:</p> <pre><code> ID Age Score 5 2 25 6 3 3 2 1 8 4 2 12 1 4 6 1 0 9 5 3 6 9 5 4 7 9 5 61 2 9 7 2 4 12 1 15 </code></pre> <p>I know I can do the above with <code>df.sort_values(df.columns.to_list())</code>, however I'm worried this might be quite slow for much larger dataframes (in terms of columns and rows).</p> <p>Is there a more optimal solution?</p>
[ { "answer_id": 74374653, "author": "Martin Lange", "author_id": 19887308, "author_profile": "https://Stackoverflow.com/users/19887308", "pm_score": 0, "selected": false, "text": "df.sort_values()" }, { "answer_id": 74374869, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "numpy.lexsort" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11901834/" ]
74,374,387
<p>Im struggling with some problem. I want to aggregate rows with the same value of &quot;STATUS&quot; and count elements. The problem is, that &quot;STATUS&quot; column is calculated in nested query inside.</p> <p>Query:</p> <pre><code> select (case when stats.status = 'RJCT' AND stats.status_reason = 'NARR' AND stats.signing_status = 'SIGNED' THEN 'Rejected(error)/Unknown' when stats.status = 'RJCT' AND stats.status_reason != 'NARR' THEN 'Rejected' when stats.status = 'PDNG' AND stats.status_reason is null THEN 'Unknown' when stats.status = 'PDNG' AND stats.status_reason = 'NARR' and stats.signing_status = 'SIGNED' THEN 'onHold/PendingUserConfirmation' when stats.status = 'PDNG' AND stats.status_reason = 'DS0A' and stats.signing_status = 'SIGNED' THEN 'PartiallyConfirmed' when stats.status = 'PDNG' AND stats.signing_status = 'PENDING' THEN 'PendingConfirmation' when stats.status = 'PDNG' AND stats.signing_status = 'SIGNING' THEN 'PendingUserApproval' when stats.status = 'PDNG' AND stats.signing_status = 'CANCELLED' THEN 'UserApprovalCancelled' when stats.status = 'PDNG' AND stats.signing_status = 'EXPIRED' THEN 'UserApprovalTimeout' when stats.status = 'PDNG' AND stats.signing_status = 'FAILED' THEN 'UserApprovalFailed' when stats.status = 'PDNG' AND stats.signing_status = 'SIGNED' THEN 'Unknown' when stats.status = 'ACCP' THEN 'Paid' when stats.status = 'ACSP' AND stats.signing_status = 'PENDING' THEN 'PendingConfirmation' when stats.status = 'ACSP' AND stats.signing_status = 'SIGNED' THEN 'Confirmed' when stats.status = 'ACSP' AND stats.signing_status = 'EXPIRED' THEN 'UserApprovalTimeout' when stats.status = 'ACSP' AND stats.signing_status = 'FAILED' THEN 'UserApprovalFailed' when stats.status = 'ACWC' AND stats.status_reason = 'NARR' AND stats.signing_status = 'SIGNED' THEN 'Paid' when stats.status = 'ACWC' AND stats.status_reason = 'NARR' AND stats.signing_status = 'SIGNED' THEN 'Paid' when stats.status = 'ACWC' AND stats.status_reason != 'NARR' THEN 'PendingConfirmation' when stats.status = 'EXECUTING' AND stats.signing_status = 'SIGNED' THEN 'Confirmed' when stats.status = 'EXECUTING' AND stats.signing_status = 'PENDING' THEN 'Confirmed' when stats.status = 'FAILED' THEN 'UserApprovalFailed' ELSE 'UNKNOWN' END) as status, stats.count from (select status, status_reason, signing_status, count(*) as count from payments group by status, signing_status, status_reason) stats; </code></pre> <p>Result:</p> <pre><code>Unknown 125 onHold/PendingUserConfirmation 15 Confirmed 12 UserApprovalFailed 41 UNKNOWN 22 Rejected(error)/Unknown 2 Rejected 176 Paid 1089 Rejected 72 PendingConfirmation 219 Unknown 7 PendingConfirmation 14835 UserApprovalFailed 10 Rejected 13 UserApprovalTimeout 145 Rejected 2 Paid 2 UNKNOWN 1 UserApprovalFailed 355 Unknown 13 PartiallyConfirmed 301 Confirmed 510 Unknown 2 PendingConfirmation 1 UserApprovalFailed 4 Unknown 13 Unknown 5 Confirmed 2399 Rejected 1 Rejected 5 Confirmed 7 Confirmed 170 Unknown 2 UserApprovalTimeout 1 PendingConfirmation 29 UserApprovalFailed 82 UserApprovalFailed 8 UserApprovalCancelled 14 UNKNOWN 1 UserApprovalFailed 16 Rejected 11 PendingConfirmation 76 PendingConfirmation 3 UserApprovalTimeout 6 Paid 2 Paid 1736 PendingUserApproval 790 UserApprovalTimeout 551 Confirmed 9 Paid 288 </code></pre> <p>I wish rows would be summed up by STATUS column. I wouldnt like to rebuild whole CASE function. Is there any solution for that?</p>
[ { "answer_id": 74374653, "author": "Martin Lange", "author_id": 19887308, "author_profile": "https://Stackoverflow.com/users/19887308", "pm_score": 0, "selected": false, "text": "df.sort_values()" }, { "answer_id": 74374869, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "numpy.lexsort" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7293134/" ]
74,374,395
<p>I have dataframe:</p> <pre><code>df = pd.DataFrame({'student_id': [71, 63, 23], 'student_name': [nan, 'Peter Andrews', 'Amy Powers'], }) </code></pre> <p>I am creating new column column which joins id + name using</p> <p><code>df['student_id_name'] = df['student_id'].astype(str) + ' ' + df['student_name']</code></p> <p>Needed output:</p> <p><code>{student_id_name : [71, 63 Peter Andrews, 23 Amy Powers]}</code></p> <p>What I get:</p> <p><code>{student_id_name : [nan, 63 Peter Andrews, 23 Amy Powers]}</code></p> <p>May you help to get to expected outcome?</p>
[ { "answer_id": 74374417, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "Series.str.cat" }, { "answer_id": 74375448, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 0, "selected": false, "text": "fillna()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18352649/" ]
74,374,409
<p>If I have table</p> <pre><code>|a | b | c| |&quot;hello&quot;|&quot;world&quot;| 1| </code></pre> <p>and the variables</p> <pre><code>start =2000 end =2015 </code></pre> <p>How do I in pyspark add 15 cols with 1st column m2000 and second m2001 etc and all these new cols have 0 so new dataframe is</p> <pre><code>|a | b | c|m2000 | m2001 | m2002 | ... | m2015| |&quot;hello&quot;|&quot;world&quot;| 1| 0 | 0 | 0 | ... | 0 | </code></pre> <p>I have tried below but</p> <pre><code> df = df.select( '*', *[&quot;0&quot;.alias(f'm{i}') for i in range(2000, 2016)] ) df.show() </code></pre> <p>I get the error</p> <pre><code>AttributeError: 'str' object has no attribute 'alias' </code></pre>
[ { "answer_id": 74374639, "author": "C Hecht", "author_id": 14578331, "author_profile": "https://Stackoverflow.com/users/14578331", "pm_score": 0, "selected": false, "text": "pandas" }, { "answer_id": 74375339, "author": "Grisha Weintraub", "author_id": 1540264, "author_profile": "https://Stackoverflow.com/users/1540264", "pm_score": 2, "selected": true, "text": "withColumn" }, { "answer_id": 74376405, "author": "Azhar Khan", "author_id": 2847330, "author_profile": "https://Stackoverflow.com/users/2847330", "pm_score": 1, "selected": false, "text": "df = df.select(df.columns + [F.lit(0).alias(f\"m{i}\") for i in range(2000, 2015)])\n" }, { "answer_id": 74380899, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 0, "selected": false, "text": "\"0\"" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9390633/" ]
74,374,430
<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>main { display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 60px; grid-row-gap: 60px; } p { grid-column: 2 / span 1; margin-bottom: 0; background-color: yellow; } p + p { margin-top: -60px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;main&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;p&gt;Another paragraph of text&lt;/p&gt; &lt;p&gt;Possibly another paragraph of text&lt;/p&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;/main&gt;</code></pre> </div> </div> </p> <p>I have a simple two column grid, with headings in the left column and paragraph text in the right hand column. I also have grid-row-gap set to give a nice gap between the rows. This all works fine, until after a heading, there is more than one paragraph <code>&lt;p&gt;</code> element. This second <code>&lt;p&gt;</code> element goes into a new row. I want all the <code>&lt;p&gt;</code> paragraph text to be inside one cell. Or for there to be no grid-row-gap between rows containing adjacent <code>&lt;p&gt;</code> elements. Or some sort of fudge.</p> <p>This is what I want. Two columns. <code>&lt;h3&gt;</code> in left column. Text in right column. And if there is more than one <code>&lt;p&gt;</code> for there to be no grid-row-gap (or the appearance of no gap) between them.</p> <pre><code>&lt;h3&gt; | &lt;p&gt; ========== &lt;h3&gt; | &lt;p&gt; ========== &lt;h3&gt; | &lt;p&gt; | &lt;p&gt; | &lt;p&gt; ========= &lt;h3&gt; | &lt;p&gt; </code></pre> <p>Here is my code</p> <pre><code>&lt;main&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;p&gt;Another paragraph of text&lt;/p&gt; &lt;p&gt;Possibly another paragraph of text&lt;/p&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Some text, blah, blah blah&lt;/p&gt; &lt;/main&gt; main { display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 60px; grid-row-gap: 60px; } p { grid-column: 2 / span 1; margin-bottom: 0; background-colour: yellow; } </code></pre>
[ { "answer_id": 74374591, "author": "user2991837", "author_id": 2991837, "author_profile": "https://Stackoverflow.com/users/2991837", "pm_score": 0, "selected": false, "text": " p + p {\n margin-top: -60px;\n }\n" }, { "answer_id": 74374606, "author": "jazzgot", "author_id": 4519236, "author_profile": "https://Stackoverflow.com/users/4519236", "pm_score": 0, "selected": false, "text": "div" }, { "answer_id": 74377079, "author": "Temani Afif", "author_id": 8620333, "author_profile": "https://Stackoverflow.com/users/8620333", "pm_score": 2, "selected": true, "text": "main {\n display: grid;\n grid-template-columns: 1fr 1fr;\n grid-column-gap: 60px;\n}\nh3 {\n margin: 0;\n}\np {\n grid-column: 2;\n margin: 0;\n background-color: yellow;\n}\nh3:not(:first-child),\nh3:not(:first-child) + p{\n margin-top: 60px\n}" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2991837/" ]
74,374,451
<p>Let's say I have an array that takes instances of the type &quot;Pessoal&quot;:</p> <pre><code>Pessoal[] teste = new Pessoal[6]; </code></pre> <p>Now let's say I have 2 arraylists that are inside of an arraylist:</p> <pre><code>static ArrayList&lt;Pessoal&gt; lista_de_profs; // This one has 4 static ArrayList&lt;Pessoal&gt; lista_de_infos; // And this one has 2, matching the 6 on &quot;teste&quot; // these arrayslists have instances of the type &quot;Pessoal&quot; </code></pre> <pre><code>ArrayList&lt;ArrayList&lt;Pessoal&gt;&gt; lista_de_docentes = new ArrayList&lt;&gt;(); lista_de_docentes.add(lista_de_profs); lista_de_docentes.add(lista_de_infos); </code></pre> <hr /> <p>How do I iterate through the arraylist (lista_de_docentes) that contains more arraylists (lista_de_profs &amp; lista_de_infos), and get their instances, so I can put them inside the array?</p> <p>This works if teste's length is 4</p> <pre><code>for (int i = 0; i &lt; teste.length; i++){ teste[i] = lista_de_profs.get(i); } </code></pre> <p>But this only covers one arraylist, and I want all of the ones inside &quot;lista_de_docentes&quot;, which are: &quot;lista_de_profs&quot; and &quot;lista_de_infos&quot;</p> <p>*Some code in here, the language is in Portuguese, but I can change it to english, if it becomes confusing.</p> <p>I hope I was clear, and thanks.</p>
[ { "answer_id": 74374755, "author": "Melron", "author_id": 8920328, "author_profile": "https://Stackoverflow.com/users/8920328", "pm_score": 2, "selected": false, "text": "List<Pessoal> all= lista_de_docentes.stream()\n .flatMap(List::stream)\n .collect(Collectors.toList());\n\nfor (int i =0; i < all.size(); i++)\n teste[i] = all.get(i);\n" }, { "answer_id": 74374800, "author": "Abra", "author_id": 2164365, "author_profile": "https://Stackoverflow.com/users/2164365", "pm_score": 3, "selected": true, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class Pessoal {\n\n public static void main(String[] args) {\n ArrayList<Pessoal> lista_de_profs = new ArrayList<>();\n ArrayList<Pessoal> lista_de_infos = new ArrayList<>();\n ArrayList<ArrayList<Pessoal>> lista_de_docentes = new ArrayList<>();\n lista_de_docentes.add(lista_de_profs); \n lista_de_docentes.add(lista_de_infos);\n Pessoal[] teste = lista_de_docentes.stream()\n .flatMap(l -> l.stream())\n .collect(Collectors.toList())\n .toArray(new Pessoal[0]);\n System.out.println(Arrays.toString(teste));\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17703613/" ]
74,374,473
<p>I have the following code that generate the unique permutation:</p> <pre><code>library(magrittr) library(tictoc) count_unique_perm &lt;- function(l = NULL) { lo &lt;- combinat::permn(l) do.call(rbind, lapply(lo, paste0, collapse = &quot;&quot;))[, 1] %&gt;% unique() %&gt;% length() } </code></pre> <p>It already give the correct result. With this input:</p> <pre><code>l1 &lt;- c(&quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;E&quot;, &quot;K&quot;, &quot;P&quot;) # 720 l2 &lt;- c(&quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;R&quot;, &quot;Q&quot;, &quot;G&quot;, &quot;K&quot;, &quot;M&quot;, &quot;S&quot;) # 30,240 </code></pre> <p>But it's running extremely slow.</p> <pre><code>tic() count_unique_perm(l = l1) toc() #118.155 sec elapsed #107.793 sec elapsed for l2 </code></pre> <p>How can I speed it up?</p>
[ { "answer_id": 74374755, "author": "Melron", "author_id": 8920328, "author_profile": "https://Stackoverflow.com/users/8920328", "pm_score": 2, "selected": false, "text": "List<Pessoal> all= lista_de_docentes.stream()\n .flatMap(List::stream)\n .collect(Collectors.toList());\n\nfor (int i =0; i < all.size(); i++)\n teste[i] = all.get(i);\n" }, { "answer_id": 74374800, "author": "Abra", "author_id": 2164365, "author_profile": "https://Stackoverflow.com/users/2164365", "pm_score": 3, "selected": true, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class Pessoal {\n\n public static void main(String[] args) {\n ArrayList<Pessoal> lista_de_profs = new ArrayList<>();\n ArrayList<Pessoal> lista_de_infos = new ArrayList<>();\n ArrayList<ArrayList<Pessoal>> lista_de_docentes = new ArrayList<>();\n lista_de_docentes.add(lista_de_profs); \n lista_de_docentes.add(lista_de_infos);\n Pessoal[] teste = lista_de_docentes.stream()\n .flatMap(l -> l.stream())\n .collect(Collectors.toList())\n .toArray(new Pessoal[0]);\n System.out.println(Arrays.toString(teste));\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8391698/" ]
74,374,477
<p>I am creating a release build with an already created Keystore file. Placed the file in android/app/AlZarooniKS. when executing a build apk from the android studio it gives the error in assembleRelease but works fine on assembleDebug. I received the following exception.</p> <pre><code>* What went wrong: Execution failed for task ':app:packageRelease'. &gt; A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable &gt; com.android.ide.common.signing.KeytoolException: Failed to read key AlZarooniKS from store &quot;/Users/hammas/Desktop/parking/android/app/AlZarooniKS&quot;: Cannot recover key * Try: &gt; Run with --stacktrace option to get the stack trace. &gt; Run with --info or --debug option to get more log output. &gt; Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 15s Running Gradle task 'assembleRelease'... 16.6s Gradle task assembleRelease failed with exit code 1 </code></pre> <p>My key.properties file</p> <pre><code>storePassword=xxx keyPassword=xxx keyAlias=AlZarooniKS storeFile=/Users/hammas/Desktop/parking/android/app/AlZarooniKS </code></pre> <p>and this is the build.gradle file</p> <pre><code>def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -&gt; localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new FileNotFoundException(&quot;Flutter SDK not found. Define location with flutter.sdk in the local.properties file.&quot;) } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' // START: FlutterFire Configuration apply plugin: 'com.google.gms.google-services' // END: FlutterFire Configuration apply plugin: 'kotlin-android' apply from: &quot;$flutterRoot/packages/flutter_tools/gradle/flutter.gradle&quot; def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { compileSdkVersion localProperties.getProperty('flutter.compileSdkVersion').toInteger() ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId &quot;com.quaidtech.emirates_parking&quot; // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. minSdkVersion localProperties.getProperty('flutter.minSdkVersion').toInteger() targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } } flutter { source '../..' } dependencies { implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot; } </code></pre>
[ { "answer_id": 74374755, "author": "Melron", "author_id": 8920328, "author_profile": "https://Stackoverflow.com/users/8920328", "pm_score": 2, "selected": false, "text": "List<Pessoal> all= lista_de_docentes.stream()\n .flatMap(List::stream)\n .collect(Collectors.toList());\n\nfor (int i =0; i < all.size(); i++)\n teste[i] = all.get(i);\n" }, { "answer_id": 74374800, "author": "Abra", "author_id": 2164365, "author_profile": "https://Stackoverflow.com/users/2164365", "pm_score": 3, "selected": true, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class Pessoal {\n\n public static void main(String[] args) {\n ArrayList<Pessoal> lista_de_profs = new ArrayList<>();\n ArrayList<Pessoal> lista_de_infos = new ArrayList<>();\n ArrayList<ArrayList<Pessoal>> lista_de_docentes = new ArrayList<>();\n lista_de_docentes.add(lista_de_profs); \n lista_de_docentes.add(lista_de_infos);\n Pessoal[] teste = lista_de_docentes.stream()\n .flatMap(l -> l.stream())\n .collect(Collectors.toList())\n .toArray(new Pessoal[0]);\n System.out.println(Arrays.toString(teste));\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15407909/" ]
74,374,484
<p>So I have the following dataframe:</p> <p>and what I want is to find the combination of genes that are present together the most.</p> <pre><code> sample genea geneb genec gened genee genef 1 1 1 1 1 0 0 0 2 2 1 1 1 0 0 0 3 3 1 0 0 1 1 1 4 4 0 0 0 0 0 0 5 5 1 0 1 1 1 1 6 6 0 0 0 0 0 0 </code></pre> <p>so in this case, my desired output would be: gene a + c = 3 samples overlap.</p> <p><code>test[sort.list(colSums(test[,-1]), decreasing=TRUE)[1:15] +1])</code> gives me a list with most 1 values per gene. But I am getting stuck with this.</p> <p>How do I approach this.</p>
[ { "answer_id": 74374598, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "comb <- combn(colnames(df[-1]), m = 2)\noverlap <- sapply(1:ncol(comb), \\(i) sum(rowSums(df[comb[, i]]) == 2))\n\nlist(max.overlap = max(overlap),\n wm = df[comb[, which.max(overlap)]])\n\n# $max.overlap\n# [1] 3\n# \n# $wm\n# genea genec\n# 1 1 1\n# 2 1 1\n# 3 1 0\n# 4 0 0\n# 5 1 1\n# 6 0 0\n" }, { "answer_id": 74374663, "author": "Basti", "author_id": 15368235, "author_profile": "https://Stackoverflow.com/users/15368235", "pm_score": 1, "selected": false, "text": "ComplexUpset" }, { "answer_id": 74374891, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 3, "selected": true, "text": "crossprod()" }, { "answer_id": 74374949, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 1, "selected": false, "text": "test <- data.frame(sample = 1:6, \n genea = c(1L, 1L, 1L, 0L, 1L, 0L), \n geneb = c(1L, 1L, 0L, 0L, 0L, 0L), \n genec = c(1L, 1L, 0L, 0L, 1L, 0L), \n gened = c(0L, 0L, 1L, 0L, 1L, 0L), \n genee = c(0L, 0L, 1L, 0L, 1L, 0L), \n genef = c(0L, 0L, 1L, 0L, 1L, 0L))\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19254600/" ]
74,374,492
<p>I have a azure function app in powershell, dedicated to kubernetes functions.</p> <p>There are multiple functions but on each of them, the first thing we do is something like this.</p> <pre><code> az login --service-principal -u $usr -p $pwd --tenant $tenant $config = $HOME + &quot;/.kube/$tenant&quot;; az account set --subscription $subscription az aks get-credentials --overwrite-existing --name $cluster --resource-group $rg --admin --file $config kubectl config set-context --current --namespace=$tenant </code></pre> <p>This sets the contexts we will be working with on our next kubectl commands.</p> <p>We do it, because we have multiple clusters on multiple regions, so everytime we get a call on the function app, we need to connect to the given cluster to work on it.</p> <p>The problem with this is when we get 2 requests at exactly the same time for 2 different clusters and the earliest call will get its context overriden and be executing kubectl commands on the incorrect cluster. Is there a way to isolate each call or a solution to this?</p>
[ { "answer_id": 74434809, "author": "YwH", "author_id": 3781502, "author_profile": "https://Stackoverflow.com/users/3781502", "pm_score": 0, "selected": false, "text": "jobs" }, { "answer_id": 74445268, "author": "Kristin", "author_id": 2832479, "author_profile": "https://Stackoverflow.com/users/2832479", "pm_score": 2, "selected": true, "text": "--context" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1383442/" ]
74,374,597
<p>I am attempting to develop a vending machine in C++ in which the user can insert as many 50 cent, 20 cent, and 10 cent coins as they would like to then move on to the 'purchase' of a product.</p> <p>So far, my primitive code runs smoothly; the issue I am currently facing is that I can only 'insert' coins into the vending machine once, even though I think the 'while' condition in the 'do/while' statement is being executed.</p> <p>Below you can find my code:</p> <p>`</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int productid; string order, finished; int amount; cout &lt;&lt; &quot;Welcome to the coffee machine! We have a variety of beverages we can offer. \n Here is our selection: \n 1) Coffee- 50 cents \n 2) Tea- 60 cents \n 3) Cappuccino- 80 cents\n&quot;; cout &lt;&lt; &quot;Please select your drink of choice by entering its ID: (1, 2, or 3)&quot;; cin &gt;&gt; productid; if (productid != 1 &amp;&amp; productid != 2 &amp;&amp; productid != 3){ cout &lt;&lt; &quot;That is an invalid entry; please try again. \n&quot;; cin &gt;&gt; productid; } cout &lt;&lt; &quot;Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n &quot;; cout &lt;&lt; &quot;When finished, please input '0'. &quot;; cin &gt;&gt; amount; if (amount != 50 &amp;&amp; amount != 20 &amp;&amp; amount != 10 &amp;&amp; amount != 0){ cout &lt;&lt; &quot;That is an invalid coin; please insert coins again.\n&quot;; cin &gt;&gt; amount; } do { amount += amount; } while (amount != 0); return 0; } </code></pre> <p>`</p> <p>I was expecting to be able to insert coins until I input '0', but the code terminal says 'Process finished with exit code 0' after I insert coins once, thereby not allowing me to continue to insert coins.</p> <p>If anyone has any suggestions as to how I could fix this so that the user can continuously insert coins until they input '0' I would greatly appreciate it.</p> <p>Please feel free to leave any suggestions as to how to proceed as well.</p> <p>Thank you</p>
[ { "answer_id": 74374645, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 3, "selected": true, "text": "do { ... } while(...);" }, { "answer_id": 74374742, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 2, "selected": false, "text": " do {\n amount += amount;\n }\n while (amount != 0);\n" }, { "answer_id": 74374815, "author": "emir", "author_id": 18711585, "author_profile": "https://Stackoverflow.com/users/18711585", "pm_score": -1, "selected": false, "text": "amount += amount;" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458815/" ]
74,374,611
<p>I want to filter a list of strings that includes any specific string with using list comprehension. I tried following the code, but it didn't work.</p> <pre><code>ignore_paths = ['.ipynb_checkpoints', 'New', '_calibration', 'images'] A = [x for x in lof1 if ignore_paths not in x] </code></pre> <p>but when I try with one string, it will work:</p> <pre><code>A = [x for x in lof1 if 'images' not in x] </code></pre> <p>in fact, I want to define a list of a forbidden path (or string) and check if there is a certain path that exists, then ignore that.</p> <p>I can do that with normal for and if loop and check one by one, but it is not fast. I am looking for a fast way because I need to check around 150k paths.</p> <p>Thanks</p> <p>EDIT: To make it clear, if I had a list of files as below:</p> <pre><code>lof1 = ['User/images/20210701_151111_G1100_E53100_r121_g64_b154_WBA0_GA0_EA0_6aa87af_crop.png', 'User/images/16f48a97-7111-4f66-92cc-dc7329e7ec92.png', 'User/images/image_2022_06_21-11_41_04_AM.png'] </code></pre> <p>I need to return an empty list since all of the elements contain <code>'images'</code></p>
[ { "answer_id": 74374655, "author": "Ron Serruya", "author_id": 2126254, "author_profile": "https://Stackoverflow.com/users/2126254", "pm_score": 1, "selected": false, "text": "allowed = set(lof1) - set(ignore_paths)\n" }, { "answer_id": 74374666, "author": "Harsha Biyani", "author_id": 3457761, "author_profile": "https://Stackoverflow.com/users/3457761", "pm_score": 0, "selected": false, "text": "A = [x for x in lof1 if x not in ignore_paths]\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5459388/" ]
74,374,624
<p><a href="https://i.stack.imgur.com/aRkvl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aRkvl.jpg" alt="What I want to achieve" /></a></p> <p>Hello everyone, I'm trying to setup the main content of the homepage as shown in the image but can't really figure a few things.</p> <p>Somehow everything I try results in the image to overflow the container and be as big as the page. I don't want to set a fixed size for the image, but rather have it proportional to the view height and width</p> <p>This is my code right now:</p> <pre><code>&lt;section class=&quot;main&quot;&gt; &lt;div class=&quot;main-left&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;img src=&quot;assets/images/wine.png&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;main-right&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;img src=&quot;assets/images/oil.png&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <pre><code> .main { display: flex; background-color: #f1eee9; height: 100%; } .main-left, .main-right { display: flex; flex-direction: row; } .main-left { background-color: #111; width: 50%; } .main-right { background-color: #1f1f1f; width: 50%; } .container { display: flex; justify-content: center; align-items: center; width: 80vw; height: 80vw; } .container img { display: block; width: 100%; height: 100%; } </code></pre> <p>I haven't yet added the text so it would be REALLY helpful if you could suggest how to do that as well..</p>
[ { "answer_id": 74374746, "author": "HmBloqued", "author_id": 17183809, "author_profile": "https://Stackoverflow.com/users/17183809", "pm_score": 2, "selected": true, "text": "object-fit: cover;" }, { "answer_id": 74374962, "author": "N.SH", "author_id": 11814486, "author_profile": "https://Stackoverflow.com/users/11814486", "pm_score": 0, "selected": false, "text": "<section class=\"main\">\n \n <div class=\"main-left\">\n <img src=\"assets/images/wine.png\">\n </div>\n\n <div class=\"main-right\">\n <img src=\"assets/images/oil.png\">\n </div>\n\n </section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458854/" ]
74,374,640
<p>There is a table like this. How can I change all the values where the column &quot;Agree, Disagree&quot; is in &quot;Disagree&quot; of &quot;Strongly disagree&quot; to negative numbers?</p> <p>It should be done without referring to the column names. The replacements to negative numbers should be applied to all columns, except the &quot;Agree, Disagree&quot; column.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Agree, Disagree</th> <th style="text-align: center;">Question A</th> <th style="text-align: center;">Question B</th> <th style="text-align: center;">Question C</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Strongly agree</td> <td style="text-align: center;">1</td> <td style="text-align: center;">1</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: center;">Agree</td> <td style="text-align: center;">1</td> <td style="text-align: center;">3</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">Neutral</td> <td style="text-align: center;">1</td> <td style="text-align: center;">0</td> <td style="text-align: center;">3</td> </tr> <tr> <td style="text-align: center;">Disagree</td> <td style="text-align: center;">2</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">Strongly disagree</td> <td style="text-align: center;">1</td> <td style="text-align: center;">2</td> <td style="text-align: center;">1</td> </tr> </tbody> </table> </div> <p>The outcome should be:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Agree, Disagree</th> <th style="text-align: center;">Question A</th> <th style="text-align: center;">Question B</th> <th style="text-align: center;">Question C</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Strongly agree</td> <td style="text-align: center;">1</td> <td style="text-align: center;">1</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: center;">Agree</td> <td style="text-align: center;">1</td> <td style="text-align: center;">3</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">Neutral</td> <td style="text-align: center;">1</td> <td style="text-align: center;">0</td> <td style="text-align: center;">3</td> </tr> <tr> <td style="text-align: center;">Disagree</td> <td style="text-align: center;">-2</td> <td style="text-align: center;">0</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">Strongly disagree</td> <td style="text-align: center;">-1</td> <td style="text-align: center;">-2</td> <td style="text-align: center;">-1</td> </tr> </tbody> </table> </div> <p>Thanks in advance!</p>
[ { "answer_id": 74374746, "author": "HmBloqued", "author_id": 17183809, "author_profile": "https://Stackoverflow.com/users/17183809", "pm_score": 2, "selected": true, "text": "object-fit: cover;" }, { "answer_id": 74374962, "author": "N.SH", "author_id": 11814486, "author_profile": "https://Stackoverflow.com/users/11814486", "pm_score": 0, "selected": false, "text": "<section class=\"main\">\n \n <div class=\"main-left\">\n <img src=\"assets/images/wine.png\">\n </div>\n\n <div class=\"main-right\">\n <img src=\"assets/images/oil.png\">\n </div>\n\n </section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9308858/" ]
74,374,656
<pre><code>create table test(id number,col timestamp(6)); insert into test values(1,TO_TIMESTAMP('2022-11-09 06:14:00.742000000', 'YYYY-MM-DD HH24:MI:SS.FF')); insert into test values(2,TO_TIMESTAMP('2022-11-07 09:14:00.742000000', 'YYYY-MM-DD HH24:MI:SS.FF')); Database: Oracle Live </code></pre> <p>I have a requirement where I need to check with weekdays by comparing the date timestamp column.</p> <ol> <li>First I need to check if the <code>col</code> (For e.g 09-Nov-2022) lies between Tuesday &amp; Sunday if it does then need to display next Monday date and time(14-Nov-2022 09:14:00.742000000').</li> </ol> <p>2.If the <code>col</code> lies on Monday(14-Nov-2022) then need to check time if it is <code>&gt;8am</code> then need to display next monday date and time(21-Nov-2022 09:14:00.742000000').</p> <p>My attempt:</p> <p><code>trunc(col,'IW')</code> this is not returning the start week of the day i.e Monday but ideally it should return MOnday which is not coming in my attempt.</p> <pre><code>select case when trunc(col) between trunc(col,'IW')+1 and trunc(col,'IW')+6 then --need to display next monday date &amp; time when trunc(col) = trunc(col,'IW') --and time is after 8am then --need to display next monday date &amp; time from test; </code></pre>
[ { "answer_id": 74375069, "author": "ekochergin", "author_id": 6033601, "author_profile": "https://Stackoverflow.com/users/6033601", "pm_score": 1, "selected": false, "text": "select \n case \n when to_char(col, 'Dy') = 'Mon' then\n case\n when col > (trunc(col) + 8/24) then \n col + 7\n else col end\n else -- since it's not Mon, it lays between Tue and Sun\n col + to_number(TRUNC(col, 'iw') + 7 - trunc(col))\n end\n from test\n" }, { "answer_id": 74375158, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 0, "selected": false, "text": "between" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17266973/" ]
74,374,670
<p>I'm trying to run this code but I'm getting an error msg ---&gt; &quot;NameError: name 'generateRandom' is not defined&quot;</p> <p>Can anyone help me please?</p> <pre><code> `import numpy as np class Mul: def __init__ (self,ra_result=None,rb_result=None): self.ra_result = ra_result self.rb_result = rb_result def generateRandom(): return np.random.randint(0,2**32), np.random.randint(0,2**32) def Multi_test(self): self.ra_result,self.rb_result= generateRandom() print(&quot;expected_output (python) = &quot;) print(&quot;ra=&quot;,self.ra_result,&quot;rb=&quot;,self.rb_result,&quot; (ra*rb)=&quot;) return self.ra_result*self.rb_result object = Mul() object.Multi_test()` </code></pre>
[ { "answer_id": 74375069, "author": "ekochergin", "author_id": 6033601, "author_profile": "https://Stackoverflow.com/users/6033601", "pm_score": 1, "selected": false, "text": "select \n case \n when to_char(col, 'Dy') = 'Mon' then\n case\n when col > (trunc(col) + 8/24) then \n col + 7\n else col end\n else -- since it's not Mon, it lays between Tue and Sun\n col + to_number(TRUNC(col, 'iw') + 7 - trunc(col))\n end\n from test\n" }, { "answer_id": 74375158, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 0, "selected": false, "text": "between" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20458788/" ]
74,374,686
<p>The following example I want column to be equal width and spacing. But I don't want to use <code>width, min-width, max-width</code> property for any columns.</p> <p>Anyone help me to achieve this by using flex or any other method.</p> <p><a href="https://i.stack.imgur.com/xo56M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xo56M.png" alt="img" /></a> <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>.d-flex { display: flex; } .d-flex .col { margin: 5px; background: #7adaff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="d-flex"&gt; &lt;div class="col"&gt; Lorem Ipsum is simply dummy text of the printing and typesetting industry &lt;/div&gt; &lt;div class="col"&gt; Lorem Ipsum is simply dummy tex &lt;/div&gt; &lt;div class="col"&gt; Lorem Ipsum &lt;/div&gt; &lt;div class="col"&gt; Lorem Ipsum &lt;/div&gt; &lt;div class="col"&gt; Lorem Ipsum is simply dummy text of the printing and typesetting industryLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>If you have any questions kindly drop your comment.</p>
[ { "answer_id": 74374848, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 3, "selected": true, "text": "width" }, { "answer_id": 74375818, "author": "Rene van der Lende", "author_id": 2015909, "author_profile": "https://Stackoverflow.com/users/2015909", "pm_score": 0, "selected": false, "text": "flex" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6060849/" ]
74,374,799
<p>I was trying to update a custom field on a Jira ticket using Jira API, following this <a href="https://developer.atlassian.com/server/jira/platform/jira-rest-api-example-edit-issues-6291632/" rel="nofollow noreferrer">Jira Documentation</a>. however, I am getting the below error.</p> <blockquote> <p>{'errorMessages': ['Can not instantiate value of type [simple type, class com.atlassian.jira.rest.v2.issue.IssueUpdateBean] from JSON String; no single-String constructor/factory method']}</p> </blockquote> <p>this is my code:</p> <pre><code>data = {'update': {'customfield_25305': [{'set': [{'value': '1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9'}, {'value': 'c6f1e31ce0138cba658f769accaac729bebc42d6'}]}]}} data = json.dumps(json.dumps(data)) #because the API accepts only strings enclosed in double quotes upload = requests.put(url, headers=headers, data=data) print(upload.json()) </code></pre> <p>as per the documentation, I tried &quot;/editmeta&quot; the custom field I am trying to update is editable and has the following attributes.</p> <blockquote> <p>{'required': False, 'schema': {'type': 'string', 'custom': 'com.atlassian.jira.plugin.system.customfieldtypes:textfield', 'customId': 25305}, 'name': 'Commit ID(s)', 'fieldId': 'customfield_25305', 'operations': ['set']}</p> </blockquote> <p>Not sure what I am doing wrong here, any help would be appreciated!</p> <p>Tried <a href="https://developer.atlassian.com/server/jira/platform/jira-rest-api-example-edit-issues-6291632/" rel="nofollow noreferrer">jira documentation</a></p> <p>and searched through the Jira community none of the answers helped, everything points to malformed data but the data that I am passing is as per documentation.</p> <p>the end result would be a 204 status code.</p>
[ { "answer_id": 74374848, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 3, "selected": true, "text": "width" }, { "answer_id": 74375818, "author": "Rene van der Lende", "author_id": 2015909, "author_profile": "https://Stackoverflow.com/users/2015909", "pm_score": 0, "selected": false, "text": "flex" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8081611/" ]
74,374,834
<p>given the following dataset, how do I go about setting the outline of the boxes to black (or any other colour I want), while customly colouring the jittered points? I know how to do this in a simple boxpot, where dodging due to two subgroups is not necesary, but run into grouping issues if I try to mess with the code shown below.</p> <pre><code>Line &lt;- c(&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;) FC &lt;- c(2, -1, 3, -0.5, 2.1, 0, 2.2, -2, 1.8, -0.1, 2, -1) TM &lt;- c(&quot;control&quot;, &quot;exp&quot;, &quot;control&quot;, &quot;exp&quot;, &quot;control&quot;, &quot;exp&quot;, &quot;control&quot;, &quot;exp&quot;, &quot;control&quot;, &quot;exp&quot;, &quot;control&quot;, &quot;exp&quot;) df1 &lt;- data.frame(Line, FC, TM) head(df1) library(ggplot2) cbpallette=c(&quot;#EF9F26&quot;, &quot;#082F6D&quot;) df1 %&gt;% ggplot(aes(x=Line,y=FC, color=TM)) + stat_boxplot(geom = 'errorbar', width=0.15, position = position_dodge(width=0.6)) + geom_boxplot(outlier.shape=NA, width=0.4, position = position_dodge(width=0.6)) + geom_point(position=position_jitterdodge(dodge.width = 0.6, jitter.width = 0.1), alpha=0.4) + theme_classic() + scale_color_manual(values = cbpallette) + scale_y_continuous(limits=c(-3, 3), breaks=c(-3, -2, -1, 0, 1, 2, 3)) + theme(axis.ticks.length = unit(-0.1, &quot;cm&quot;)) </code></pre> <p><a href="https://i.stack.imgur.com/d6vg8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d6vg8.png" alt="Example" /></a></p>
[ { "answer_id": 74374848, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 3, "selected": true, "text": "width" }, { "answer_id": 74375818, "author": "Rene van der Lende", "author_id": 2015909, "author_profile": "https://Stackoverflow.com/users/2015909", "pm_score": 0, "selected": false, "text": "flex" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13011601/" ]
74,374,837
<p>I've defined the following JavaScript function</p> <pre class="lang-js prettyprint-override"><code>async isDataValid (externalValidation = true) { const isValid = (await this.v$.$validate()) &amp;&amp; externalValidation // other stuff not relevant to my question happens here return isValid } </code></pre> <p>AFAIK, I need to define this as an <code>async</code> function in order to await the result of <code>this.v$.$validate()</code>.</p> <p>Because <code>isDataValid</code> is itself <code>async</code>, I thought I need to use <code>await</code> whenever I call it, but when I did the following:</p> <pre><code>const result = await this.isDataValid() </code></pre> <p>My IDE marked this with a warning</p> <blockquote> <p>Redundant 'await' for a non-promise type</p> </blockquote> <p>So it seems my IDE is saying that <code>await</code> only needs to be used if an <code>async</code> function returns a promise i.e. there is no need to use <code>await</code> with <code>isDataValid</code> because it returns a boolean.</p> <p>Does <code>await</code> need to be used when calling all <code>async</code> functions, or only those that return a promise?</p> <h2>Update</h2> <p>I am using JavaScript, not TypeScript</p>
[ { "answer_id": 74374895, "author": "Ritik Banger", "author_id": 17632251, "author_profile": "https://Stackoverflow.com/users/17632251", "pm_score": 0, "selected": false, "text": "await" }, { "answer_id": 74374961, "author": "Tushar Shahi", "author_id": 10140124, "author_profile": "https://Stackoverflow.com/users/10140124", "pm_score": 1, "selected": false, "text": "async" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786956/" ]
74,374,855
<p>so I do have this NumPy array result(final), and I want to reduce it, I mean, if the value is repeated, then I want to delete the first value and maintain the second,third value repeated and so on...</p> <pre><code>import hmac import hashlib import time from argparse import _MutuallyExclusiveGroup from tkinter import * import pandas as pd import base64 import matplotlib.pyplot as plt import numpy as np key=&quot;800070FF00FF08012&quot; key=bytes(key,'utf-8') collision=[] for x in range(1,1000001): msg=bytes(f'{x}','utf-8') digest = hmac.new(key, msg,&quot;sha256&quot;).digest() code = base64.b64encode(digest).decode('utf-8') code=code[:6] key=key.replace(key,digest) collision.append(code) df=pd.DataFrame(collision) df=df[df.duplicated(keep=False)] df_index=df.index.to_numpy() df=df.values.flatten() final=np.stack((df_index,df),axis=1) Results of the variable &quot;final&quot;: I HAVE: [[14093 'JRp1kX'] [43985 'KGlW7X'] [59212 'pU97Tr'] [90668 'ecTjTB'] [140615 'JRp1kX'] [218480 '25gtjT'] [344174 'dtXg6E'] [380467 'DdHQ3M'] [395699 'vnFw/c'] [503504 'dtXg6E'] [531073 'KGlW7X'] [633091 'ecTjTB'] [671091 'vnFw/c'] [672111 '25gtjT'] [785568 'pU97Tr'] [991540 'DdHQ3M'] [991548 'JRp1kX']] And I WANT TO HAVE: [[140615 'JRp1kX'] [503504 'dtXg6E'] [531073 'KGlW7X'] [633091 'ecTjTB'] [671091 'vnFw/c'] [672111 '25gtjT'] [785568 'pU97Tr'] [991540 'DdHQ3M'] [991548 'JRp1kX']] </code></pre> <p>Eliminating the first values that were repeated in the array. Does someone have some code that could work for my case?</p> <p>In more simple terms it would be, if you have this list [1,2,3,4,5,1,3,5,5] I would like to have [2,4,1,3,5,5]</p>
[ { "answer_id": 74375026, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 0, "selected": false, "text": "for" }, { "answer_id": 74375142, "author": "Sabuhi Khalili", "author_id": 10831645, "author_profile": "https://Stackoverflow.com/users/10831645", "pm_score": 0, "selected": false, "text": "df=pd.DataFrame(collision)\n# ... your code ends here\nremoved_already=[]\nfor idx in df[df.duplicated(keep=False)].index:\n if df.loc[idx][0] not in removed_already:\n removed_already.append(df.loc[idx][0])\n df.drop(index=idx, inplace=True)\n# your code continues\ndf_index=df.index.to_numpy()\ndf=df.values.flatten()\nfinal=np.stack((df_index,df),axis=1)\n" }, { "answer_id": 74375619, "author": "w-m", "author_id": 463796, "author_profile": "https://Stackoverflow.com/users/463796", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame([1, 2, 3, 4, 5, 1, 3, 5, 5])\n\n# keep the unique rows\nunique_mask = ~df.duplicated(keep=False)\n\n# keep the repeated rows (skipping the first for each non-unique)\nrepeated_mask = df.duplicated()\n\ndf.loc[unique_mask | repeated_mask]\n\n 0\n1 2\n3 4\n5 1\n6 3\n7 5\n8 5\n" }, { "answer_id": 74376050, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 1, "selected": true, "text": "final" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16306538/" ]
74,374,878
<p>I have a v-textarea, I write something to area and if I do not any action, in v-textarea context must be cleared automatic after a certain time (2 minutes). How can I do it?</p> <p><a href="https://i.stack.imgur.com/16EAj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/16EAj.png" alt="For example I want to remove Hello' 2 minutes later." /></a></p> <pre><code>&lt;v-textarea v-model.trim=&quot;text&quot; clearable :label=&quot;modeLabel&quot; &gt; </code></pre>
[ { "answer_id": 74375026, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 0, "selected": false, "text": "for" }, { "answer_id": 74375142, "author": "Sabuhi Khalili", "author_id": 10831645, "author_profile": "https://Stackoverflow.com/users/10831645", "pm_score": 0, "selected": false, "text": "df=pd.DataFrame(collision)\n# ... your code ends here\nremoved_already=[]\nfor idx in df[df.duplicated(keep=False)].index:\n if df.loc[idx][0] not in removed_already:\n removed_already.append(df.loc[idx][0])\n df.drop(index=idx, inplace=True)\n# your code continues\ndf_index=df.index.to_numpy()\ndf=df.values.flatten()\nfinal=np.stack((df_index,df),axis=1)\n" }, { "answer_id": 74375619, "author": "w-m", "author_id": 463796, "author_profile": "https://Stackoverflow.com/users/463796", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame([1, 2, 3, 4, 5, 1, 3, 5, 5])\n\n# keep the unique rows\nunique_mask = ~df.duplicated(keep=False)\n\n# keep the repeated rows (skipping the first for each non-unique)\nrepeated_mask = df.duplicated()\n\ndf.loc[unique_mask | repeated_mask]\n\n 0\n1 2\n3 4\n5 1\n6 3\n7 5\n8 5\n" }, { "answer_id": 74376050, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 1, "selected": true, "text": "final" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19697316/" ]
74,374,885
<p>I have the following case in typescript:</p> <pre><code>type RecordKeys = 1 | 2 | 3 type RecordValues = &quot;one&quot; | &quot;two&quot; | &quot;three&quot; function test(param: RecordKeys ): RecordValues { switch(param) { case(1): { return 'one' } case(2): { return 'two' } case(3): { return &quot;three&quot; } } } </code></pre> <p>Is there any way to correctly type this function to ensure that what is returned from this function corresponds to an actual map? For example : if param = 1 then &quot;one&quot; will be returned if param = 2 then &quot;two&quot; will be returned and so on.</p>
[ { "answer_id": 74374928, "author": "Moudi", "author_id": 16402009, "author_profile": "https://Stackoverflow.com/users/16402009", "pm_score": 2, "selected": false, "text": "const testMap: Record<number, string> = {\n 1: 'one',\n 2: 'two',\n 3: 'three'\n}\n\n// use the hashmap to get the value\nfunction test2(param: number): String {\n return testMap[param]\n}\n" }, { "answer_id": 74375334, "author": "sotiristherobot", "author_id": 12046630, "author_profile": "https://Stackoverflow.com/users/12046630", "pm_score": 1, "selected": false, "text": "type RecordKeys = 1 | 2 | 3\n\nfunction test(param: 1): \"one\" \nfunction test(param: 2): \"two\" \nfunction test(param: 3): \"three\" \n\nfunction test(param: RecordKeys) {\n switch(param){\n case(1): {\n return \"one\"\n }\n case(2): {\n return \"two\"\n }\n case(3): {\n return \"three\"\n }\n }\n}\n" }, { "answer_id": 74375844, "author": "leetwinski", "author_id": 5400548, "author_profile": "https://Stackoverflow.com/users/5400548", "pm_score": 0, "selected": false, "text": "test" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12046630/" ]
74,374,892
<p>I have a an enum WeekDays, with Flag attribute on top,</p> <pre><code>[Flags] public enum WeekDays { None = 0, Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64 } </code></pre> <p>I want to use this enum as a list in another model. The issue I am facing is while mapping a list of enum from FE to map to an int variable to store in database column. I'm not sure how to do it. what I was trying so far i:</p> <pre><code>int daysBit; var settings = await _globalContext.settingsModel.SingleOrDefaultAsync(x =&gt; x.id == request.id); if (adminEmailSettingsFromDb == null) { foreach (var day in request.DaysOfWeek) { daysBit |= (day)WeekDays; } var exampleVariable = new settingsModel { DaysOfWeek = daysBit, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; } </code></pre>
[ { "answer_id": 74375500, "author": "Alina", "author_id": 14975190, "author_profile": "https://Stackoverflow.com/users/14975190", "pm_score": 1, "selected": true, "text": "WeekDays daysBit=WeekDays.None;\nforeach (var day in request.DaysOfWeek)\n{\n daysBit |= day;\n}\n" }, { "answer_id": 74375523, "author": "JonasH", "author_id": 12342238, "author_profile": "https://Stackoverflow.com/users/12342238", "pm_score": 1, "selected": false, "text": "var dayBit = request.DaysOfWeek.Aggregate(WeekDays.None, (a, b) => a|b);\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14975190/" ]
74,374,893
<p>how could I make my function clear the list and return the inital list on the first execution, and then display a empty list on the second run? I have tried using. Kind regards</p> <pre><code>def remove(): items = [&quot;car&quot;, &quot;plane&quot;, &quot;bus&quot;] if len(items) != 0: return items and items.clear() print(remove()) print(remove()) </code></pre> <pre><code>First Print expected output: [&quot;car&quot;, &quot;plane&quot;, &quot;bus&quot;] Second Print expected output: [] </code></pre>
[ { "answer_id": 74375052, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "items" }, { "answer_id": 74375071, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 1, "selected": false, "text": "def remove(items = [\"car\", \"plane\", \"bus\"]):\n rv = items.copy()\n items.clear()\n return rv\n\nprint(remove())\nprint(remove())\n" }, { "answer_id": 74375072, "author": "Icare", "author_id": 19835359, "author_profile": "https://Stackoverflow.com/users/19835359", "pm_score": 0, "selected": false, "text": "items = [\"car\", \"plane\", \"bus\"]\n\ndef remove():\n global items\n print(items)\n if len(items) != 0:\n items.clear()\n return() \n \n \nremove()\nremove()\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20430652/" ]
74,374,939
<p>Hello in my monopoly game i need to make sure no inputted player names are the same to avoid confusion using an arraylist in java any way how to do it so only one player can have one name</p> <pre><code>public class Player { private ArrayList&lt;Property&gt; properties = new ArrayList&lt;Property&gt;(); private final String name; private int position; private int money = 0; public boolean inJail = false; public int outOfJailCards = 0; public int turnsInJail = 0; public Player(String name){ this.name = name; position = 0; } public String getName() { return name; } </code></pre> <pre><code>// in monopoly.java static ArrayList&lt;Player&gt; createPlayers(int numPlayers){ ArrayList&lt;Player&gt; players = new ArrayList&lt;&gt;(); for(int i = 1; i &lt;= numPlayers; i++){ System.out.print(&quot;Player &quot; + i + &quot; name: &quot;); players.add(new Player(Input.read())); } return players; } } </code></pre> <pre><code> import java.util.List; import java.util.Scanner; public class Input { public static String read(){ Scanner scanner = new Scanner(System.in); return scanner.nextLine(); } </code></pre> <p><a href="https://i.stack.imgur.com/dA2OL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dA2OL.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74375052, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "items" }, { "answer_id": 74375071, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 1, "selected": false, "text": "def remove(items = [\"car\", \"plane\", \"bus\"]):\n rv = items.copy()\n items.clear()\n return rv\n\nprint(remove())\nprint(remove())\n" }, { "answer_id": 74375072, "author": "Icare", "author_id": 19835359, "author_profile": "https://Stackoverflow.com/users/19835359", "pm_score": 0, "selected": false, "text": "items = [\"car\", \"plane\", \"bus\"]\n\ndef remove():\n global items\n print(items)\n if len(items) != 0:\n items.clear()\n return() \n \n \nremove()\nremove()\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17492033/" ]
74,374,960
<p>The Confluent AvroDeserializer requires the <code>schema_str</code>. However, I do not want to supply the schema, I just need to retrieve it from the registry, and that's it. What am I missing?</p> <pre><code>classconfluent_kafka.schema_registry.avro.AvroDeserializer(schema_str, schema_registry_client, from_dict=None) </code></pre> <p>Doc: <a href="https://docs.confluent.io/5.5.0/clients/confluent-kafka-python/index.html#avrodeserializer" rel="nofollow noreferrer">https://docs.confluent.io/5.5.0/clients/confluent-kafka-python/index.html#avrodeserializer</a></p>
[ { "answer_id": 74375052, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "items" }, { "answer_id": 74375071, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 1, "selected": false, "text": "def remove(items = [\"car\", \"plane\", \"bus\"]):\n rv = items.copy()\n items.clear()\n return rv\n\nprint(remove())\nprint(remove())\n" }, { "answer_id": 74375072, "author": "Icare", "author_id": 19835359, "author_profile": "https://Stackoverflow.com/users/19835359", "pm_score": 0, "selected": false, "text": "items = [\"car\", \"plane\", \"bus\"]\n\ndef remove():\n global items\n print(items)\n if len(items) != 0:\n items.clear()\n return() \n \n \nremove()\nremove()\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523587/" ]
74,374,999
<p>I have a dataframe that looks like this:</p> <pre><code>dat &lt;- data.frame(T1 = c('s', 's', 'm', 'l', 'm', 'xl'), T2 = c('s', 's', 'm', 'l', 'm', 'xl'), T3 = c('m', 's', 'm', 'l', 'l', 'xxl'), T4 = c('m', 'm', 'm', 'l', 'l', 'xxl'), T5 = c('m', 'm', 'm', 'xl', 'l', 'xl')) </code></pre> <p>Now, I would like to convert these characters into numbers (1-5). Is there some way to do this in a few lines for the whole data frame. If I have to ifelse() statements for each column and each character, I use up a whole lot of lines. Thank you in advance.</p>
[ { "answer_id": 74375054, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 3, "selected": true, "text": "ifelse" }, { "answer_id": 74375076, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 3, "selected": false, "text": "match" }, { "answer_id": 74375090, "author": "Tom Hoel", "author_id": 17213355, "author_profile": "https://Stackoverflow.com/users/17213355", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\ndf %>% \n mutate(across(everything(), ~ factor(.x, levels = c(\"s\", \"m\", \"l\", \"xl\", \"xxl\")) %>% as.integer()))\n\n# A tibble: 6 x 5\n T1 T2 T3 T4 T5\n <int> <int> <int> <int> <int>\n1 1 1 2 2 2\n2 1 1 1 2 2\n3 2 2 2 2 2\n4 3 3 3 3 4\n5 2 2 3 3 3\n6 4 4 5 5 4\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74374999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14487498/" ]
74,375,016
<p>I have just moved servers after a crash and PHP has been upgraded from 7.4 to 8.1 and I am getting the below error message when trying to submit a registration form;</p> <blockquote> <p>Fatal error: Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count</p> </blockquote> <p>I have checked the table names, the amount of ?'s and insert query both add up to 37 as per the database.</p> <p>I know it's something simple, but can't spot the error, been looking at the code for 3 hours and hopefully a fresh pair of eyes can see something :)</p> <p>My code is</p> <pre><code>$folder = &quot;uploads/&quot;; $image = $_FILES['image']['name']; $path = $folder . uniqid().$image ; $target_file= $folder.basename($_FILES[&quot;image&quot;][&quot;name&quot;]); $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $allowed = array('jpeg','png','PNG','JPG' ,'jpg','gif'); $filename = $_FILES['image']['name']; $ext=pathinfo($filename, PATHINFO_EXTENSION); if(!in_array($ext,$allowed) ) { $msg = &quot;Sorry, only JPG, JPEG, PNG &amp; GIF files are allowed.&quot;; // var_dump($msg); } else{ move_uploaded_file( $_FILES['image'] ['tmp_name'], $path); // var_dump($path); $imageSource = $path; } $id = isset($_POST['id']) &amp;&amp; !empty($_POST['id']) &amp;&amp; $_POST['id'] != 'auto' ? $_POST['id'] : NULL; $status = $_POST['status']; $learner_id = $_POST['learner_id']; $title = $_POST['title']; $name = $_POST['name']; $last_name = $_POST['last_name']; $sex = $_POST['sex']; $dob = $_POST['dob']; $house_number = $_POST['house_number']; $address_line_one = $_POST['address_line_one']; $address_line_two = $_POST['address_line_two']; $city_town = $_POST['city_town']; $country = $_POST['country']; $postcode = $_POST['postcode']; $postcode_enrolment = $_POST['postcode_enrolment']; $phone = $_POST['phone']; $mobile_number = $_POST['mobile_number']; $email_address = $_POST['email_address']; $ethnic_origin = $_POST['ethnic_origin']; $ethnicity = $_POST['ethnicitys']; $health_problem = $_POST['health_problem']; $health_disability_problem_if_yes = isset($_POST['health_disability_problem_if_yes']) ? json_encode($_POST['health_disability_problem_if_yes']) : ''; $lldd = $_POST['lldd']; $education_health_care_plan = $_POST['education_health_care_plan']; $health_problem_start_date = $_POST['health_problem_start_date']; $education_entry = $_POST['education_entry']; $emergency_contact_details = $_POST['emergency_contact_details']; $employment_paid_status = $_POST['employment_paid_status']; $employment_date = $_POST['employment_date']; $unemployed_month = $_POST['unemployed_month']; $education_training_prior = $_POST['education_training_prior']; $education_claiming = $_POST['education_claiming']; $claiming_if_yes = $_POST['claiming_if_yes']; $household_situation = $_POST['household_situation']; $stmt = $pdo-&gt;prepare('INSERT INTO contacts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); $result = $stmt-&gt;execute([$id, $status, $path, date(&quot;Y/m/d&quot;), $learner_id, $title, $name, $last_name, $sex, $dob, $house_number, $address_line_one, $address_line_two, $city_town, $country, $postcode, $postcode_enrolment, $phone, $mobile_number, $email_address, $ethnic_origin, $ethnicity, $health_problem, $health_disability_problem_if_yes, $lldd, $education_health_care_plan, $health_problem_start_date, $education_entry, $emergency_contact_details, $employment_paid_status, $employment_date, $unemployed_month, $education_training_prior, $education_claiming, $claiming_if_yes, $household_situation, null]); </code></pre> <p>I know this code is slightly older, but a new system is been built but not ready till later next year.</p> <p>Database</p> <pre><code> `id` int(11) NOT NULL, `status` varchar(20) NOT NULL DEFAULT 'Referral' COMMENT 'status is Referral,InProgress,S2,S3,NoContact,Old,Declined', `image` varchar(225) DEFAULT NULL, `datemovedin` date DEFAULT NULL, `learner_id` varchar(100) DEFAULT NULL, `title` varchar(225) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, `last_name` varchar(50) DEFAULT NULL, `sex` varchar(50) DEFAULT NULL, `dob` varchar(50) DEFAULT NULL, `house_number` varchar(225) DEFAULT NULL, `address_line_one` varchar(225) DEFAULT NULL, `address_line_two` varchar(225) DEFAULT NULL, `city_town` varchar(50) DEFAULT NULL, `country` varchar(50) DEFAULT NULL, `postcode` varchar(50) DEFAULT NULL, `postcode_enrolment` varchar(50) DEFAULT NULL, `phone` varchar(50) DEFAULT NULL, `mobile_number` varchar(50) DEFAULT NULL, `email_address` varchar(225) DEFAULT NULL, `ethnic_origin` varchar(225) DEFAULT NULL, `ethnicitys` varchar(225) DEFAULT NULL, `health_problem` varchar(225) DEFAULT NULL, `health_disability_problem_if_yes` text DEFAULT NULL, `lldd` text DEFAULT NULL, `education_health_care_plan` varchar(225) DEFAULT NULL, `health_problem_start_date` varchar(225) DEFAULT NULL, `education_entry` varchar(225) DEFAULT NULL, `emergency_contact_details` varchar(225) DEFAULT NULL, `employment_paid_status` varchar(225) DEFAULT NULL, `employment_date` varchar(225) DEFAULT NULL, `unemployed_month` varchar(225) DEFAULT NULL, `education_training_prior` varchar(225) DEFAULT NULL, `education_claiming` varchar(225) DEFAULT NULL, `claiming_if_yes` varchar(225) DEFAULT NULL, `household_situation` varchar(225) DEFAULT NULL, `mentor` int(11) DEFAULT NULL </code></pre>
[ { "answer_id": 74375092, "author": "Tural Rzaxanov", "author_id": 9922647, "author_profile": "https://Stackoverflow.com/users/9922647", "pm_score": -1, "selected": false, "text": " $stmt = $pdo->prepare('INSERT INTO contacts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n $result = $stmt->execute([$id, $status, $path, date(\"Y/m/d\"), $learner_id, $title, $name, $last_name, $sex, $dob, $house_number, $address_line_one, $address_line_two, $city_town, $country, $postcode, $postcode_enrolment, $phone, $mobile_number, $email_address, $ethnic_origin, $ethnicity, $health_problem, $health_disability_problem_if_yes, $lldd, $education_health_care_plan, $health_problem_start_date, $education_entry, $emergency_contact_details, $employment_paid_status, $employment_date, $unemployed_month, $education_training_prior, $education_claiming, $claiming_if_yes, $household_situation, null]);\n" }, { "answer_id": 74375296, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 3, "selected": true, "text": "$stmt = $pdo->prepare('INSERT INTO contacts (id, status, .... the rest of the columns here) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,375,035
<p>I am trying to convert a json response from REST API into a <code>DataTable</code>. The following is my code.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RestSharp; using Newtonsoft.Json; using System.Data; namespace RestDemo1 { class Program { static void Main(string[] args) { getEmployeeData(); } public static void getEmployeeData() { var client = new RestClient(&quot;https://crmscf.vidyasystems.com/api/gen/items.php&quot;); var request = new RestRequest(&quot;items&quot;); var response = client.Execute(request); string vJ = &quot;&quot;; if (response.StatusCode == System.Net.HttpStatusCode.OK) { string rawResponse = response.Content; DataTable tester = (DataTable)JsonConvert.DeserializeObject(rawResponse, (typeof(DataTable))); } } public class Rootobject { public int success { get; set; } public Item[] items { get; set; } public class Item { public string ItemID { get; set; } public string ItemName { get; set; } public string ItemDesc { get; set; } public string MRP { get; set; } public string Rate { get; set; } public string Unit { get; set; } public string Weight { get; set; } public string ItemGroup { get; set; } } } } } </code></pre> <p>When I try get the data into a table format, I get error:</p> <pre><code>DataTable tester = (DataTable)JsonConvert.DeserializeObject(rawResponse, (typeof(DataTable))); </code></pre> <blockquote> <p>Error message- Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.'</p> </blockquote>
[ { "answer_id": 74375092, "author": "Tural Rzaxanov", "author_id": 9922647, "author_profile": "https://Stackoverflow.com/users/9922647", "pm_score": -1, "selected": false, "text": " $stmt = $pdo->prepare('INSERT INTO contacts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n $result = $stmt->execute([$id, $status, $path, date(\"Y/m/d\"), $learner_id, $title, $name, $last_name, $sex, $dob, $house_number, $address_line_one, $address_line_two, $city_town, $country, $postcode, $postcode_enrolment, $phone, $mobile_number, $email_address, $ethnic_origin, $ethnicity, $health_problem, $health_disability_problem_if_yes, $lldd, $education_health_care_plan, $health_problem_start_date, $education_entry, $emergency_contact_details, $employment_paid_status, $employment_date, $unemployed_month, $education_training_prior, $education_claiming, $claiming_if_yes, $household_situation, null]);\n" }, { "answer_id": 74375296, "author": "dvicemuse", "author_id": 1155184, "author_profile": "https://Stackoverflow.com/users/1155184", "pm_score": 3, "selected": true, "text": "$stmt = $pdo->prepare('INSERT INTO contacts (id, status, .... the rest of the columns here) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');\n\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12858964/" ]
74,375,060
<p>I don't know what is <code>it</code> in Textfield's onValueChange using Jetpack compose.</p> <pre><code>val usernameState = rememberSaveable { mutableStateOf(TextFieldValue())} TextField( value = usernameState.value, onValueChange = {usernameState.value = it} ) </code></pre> <p>Is <code>it</code> the argument in lambda function? I think every time the textfield's value changes, the lambda function is called. So if we don't use the omission using <code>it</code>, what do we write in the lambda function. Please teach me. Thank you.</p>
[ { "answer_id": 74375156, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 3, "selected": false, "text": "it" }, { "answer_id": 74385172, "author": "zjmo", "author_id": 14507326, "author_profile": "https://Stackoverflow.com/users/14507326", "pm_score": 1, "selected": false, "text": "It" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16375313/" ]
74,375,075
<p>Let's say I have a large set of Helm charts, in which I want to edit every <code>deployment.yaml</code> file in the <code>templates</code> directory of each chart, which doing manually is a tedious task.</p> <p>I've tried to use Python's <code>pyyaml</code> and <code>benedict</code> to do something like this:</p> <pre><code>content = read_file() # reads the deployment.yaml file deployment = yaml.unsafe_load(content) deployment = benedict(deployment) </code></pre> <p>But I get this:</p> <pre><code>yaml.parser.ParserError: while parsing a flow node expected the node content, but found '-' in &quot;&lt;unicode string&gt;&quot;, line 3, column 4: {{- include &quot;something.labels&quot; ... </code></pre> <p>I suppose that since the <code>deployment.yaml</code> which is a Helm template is not a valid YAML, pyyaml can't decode it.</p> <p>Does anyone know another way?</p>
[ { "answer_id": 74375156, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 3, "selected": false, "text": "it" }, { "answer_id": 74385172, "author": "zjmo", "author_id": 14507326, "author_profile": "https://Stackoverflow.com/users/14507326", "pm_score": 1, "selected": false, "text": "It" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12176460/" ]
74,375,079
<p>Here is an example of the problem with the result list as what I am aiming to obtain.</p> <p>states = [&quot;Montana&quot;, &quot;New York&quot;, &quot;Iowa&quot;, &quot;Alabama&quot;, &quot;Washington D.C.&quot;] text = &quot;Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montana more than New York.&quot;</p> <p>result = [Montana, Montana, New York]</p> <p>One crude way I am looking at this is to do an intersection of the two but it is unable to handle duplicates and two word states like &quot;New York&quot;.</p> <pre><code>state_lower = [x.lower() for x in states] set(state_lower).intersection(text.lower().split()) </code></pre> <p>I am looking for the fastest way to perform this operation as each text can be very long (4,000+ words) and I have millions of texts to go through. Also, I would like to keep the spaces in the original text. Thank you in advance.</p>
[ { "answer_id": 74375154, "author": "Talha Tayyab", "author_id": 13086128, "author_profile": "https://Stackoverflow.com/users/13086128", "pm_score": 0, "selected": false, "text": "states = [\"Montana\", \"New York\", \"Iowa\", \"Alabama\", \"Washington D.C.\"]\ntext = \"Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montana more than New York.\"\nfor x in states:\n print(text.count(x),x)\n2 Montana\n1 New York\n0 Iowa\n0 Alabama\n0 Washington D.C.\n" }, { "answer_id": 74375168, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "states = [\"Montana\", \"New York\", \"Iowa\", \"Alabama\", \"Washington D.C.\"]\ntext = \"Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montana more than New York.\"\n\nfor state in states:\n if state.lower() in text.lower():\n for i in range(text.count(state))\n new_list.append(state)\n\nprint(new_list)\n" }, { "answer_id": 74375205, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "pip install flashtext\n" }, { "answer_id": 74375289, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "import re\n\nregex = '|'.join(map(re.escape, states))\n\nout = re.findall(regex, text)\n" }, { "answer_id": 74375558, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 0, "selected": false, "text": "wanted_countries = ['Montana', 'New York', 'Iowa', 'Alabama', 'Washington D.C.']\n\ndef filter_non_wanted(my_list):\n return_list = list()\n\n for INDEX, i in enumrate(my_list.split(' ')):\n if i == 'New' and my_list[INDEX+1] == 'York':\n return_list.append('New York') \n elif i in wanted_countries:\n return_list.append(i)\n\n #-- second possibility, more flexible --#\n\n if ' '.join([i, my_list[INDEX+1]]) in wanted_countries:\n return_list.append(' '.join([i, my_list[INDEX+1]]))\n elif i in wanted_countries:\n return_list.append(i)\n return return_list\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9338066/" ]
74,375,093
<p>I have two arrays and need to multiply, ex 4.56… with 0.134. It can be pushed to the second array, it can also be added to a new.</p> <p>First array:</p> <pre><code>[[2022-09-01T00:00:00, 4.56255004875], [2022-09-01T01:00:00, 4.50295013375], [2022-09-01T02:00:00, 4.52136261], [2022-09-01T03:00:00, 4.46261261], [2022-09-01T04:00:00, 4.6035501100000005], [2022-09-01T05:00:00, 4.95328735375] </code></pre> <p>Second array</p> <pre><code>[[0.134], [0.132], [0.126], [0.129], [0.128], [0.145], [0.495], [1.837], [0.683], [0.125], [0.124], [0.128], [1.148], [0.39], [0.272], [0.479], [0.439] </code></pre> <p>Trying googling answers, with no luck.</p>
[ { "answer_id": 74375154, "author": "Talha Tayyab", "author_id": 13086128, "author_profile": "https://Stackoverflow.com/users/13086128", "pm_score": 0, "selected": false, "text": "states = [\"Montana\", \"New York\", \"Iowa\", \"Alabama\", \"Washington D.C.\"]\ntext = \"Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montana more than New York.\"\nfor x in states:\n print(text.count(x),x)\n2 Montana\n1 New York\n0 Iowa\n0 Alabama\n0 Washington D.C.\n" }, { "answer_id": 74375168, "author": "user99999", "author_id": 20070120, "author_profile": "https://Stackoverflow.com/users/20070120", "pm_score": 0, "selected": false, "text": "states = [\"Montana\", \"New York\", \"Iowa\", \"Alabama\", \"Washington D.C.\"]\ntext = \"Montana is big sky country where great ski slopes can be found. Avid skiers will enjoy Montana more than New York.\"\n\nfor state in states:\n if state.lower() in text.lower():\n for i in range(text.count(state))\n new_list.append(state)\n\nprint(new_list)\n" }, { "answer_id": 74375205, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "pip install flashtext\n" }, { "answer_id": 74375289, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "import re\n\nregex = '|'.join(map(re.escape, states))\n\nout = re.findall(regex, text)\n" }, { "answer_id": 74375558, "author": "JohnyCapo", "author_id": 19335841, "author_profile": "https://Stackoverflow.com/users/19335841", "pm_score": 0, "selected": false, "text": "wanted_countries = ['Montana', 'New York', 'Iowa', 'Alabama', 'Washington D.C.']\n\ndef filter_non_wanted(my_list):\n return_list = list()\n\n for INDEX, i in enumrate(my_list.split(' ')):\n if i == 'New' and my_list[INDEX+1] == 'York':\n return_list.append('New York') \n elif i in wanted_countries:\n return_list.append(i)\n\n #-- second possibility, more flexible --#\n\n if ' '.join([i, my_list[INDEX+1]]) in wanted_countries:\n return_list.append(' '.join([i, my_list[INDEX+1]]))\n elif i in wanted_countries:\n return_list.append(i)\n return return_list\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450996/" ]
74,375,121
<p>Im trying to createa a <code>@composable function</code> that is able to keep track of all its children. The first Parent <code>TextExecutionOrder</code> should be able to tell that it has 3 Children of the same composable function <code>TestExecutionOrder(&quot;2&quot;)</code>, <code>TestExecutionOrder(&quot;3&quot;)</code> and <code>TestExecutionOrder(&quot;10&quot;)</code>.</p> <pre><code>@Preview @Composable fun test() { TestExecutionOrder(&quot;1&quot;) { TestExecutionOrder(&quot;2&quot;) { TestExecutionOrder(&quot;15&quot;) {} TestExecutionOrder(&quot;5&quot;) { TestExecutionOrder(&quot;6&quot;) {} TestExecutionOrder(&quot;7&quot;) {} } } TestExecutionOrder(&quot;3&quot;) {} TestExecutionOrder(&quot;10&quot;) {} } } </code></pre> <p>For Example the above Code could have a datastructure like a <code>Stack</code>, <code>CircularArray</code> or anything else where it stores the following.</p> <ul> <li>Parent{1} -&gt; Childs{2,3,10}</li> <li>Parent{2} -&gt; Childs{15,5}</li> <li>Parent{15} -&gt; Childs{}</li> <li>Parent{5} -&gt; Childs{6,7}</li> <li>Parent{6} -&gt; Childs{}</li> <li>Parent{7} -&gt; Childs{}</li> <li>Parent{3} -&gt; Childs{}</li> <li>Parent{10} -&gt; Childs{}</li> </ul> <p>v</p> <pre><code>data class Faaa(val name: String)//val size : IntSize,val pos: Offset) @Composable fun TestExecutionOrder( text: String, arr: CircularArray&lt;Faaa&gt;, stack: Stack&lt;CircularArray&lt;Faaa&gt;&gt;, content: @Composable () -&gt; Unit, ) { //TODO content() } </code></pre> <p>In <code>QML</code> I would be able to iterate through the children elements of a parent and then be able to add all Items that are an instance of TestExecutionOrder inside my desired data structure.</p> <p>I tried to use <code>State-hoisting</code> where my <code>Stack</code> data structure is at top of my test() function and then passed through all children. Where each children will only get the <code>stack().peek()</code> reference of the current circular array but Kotlin is pass by value so this also doesn't work.</p> <h3>Pass By Reference Solution that obv doesnt work :D</h3> <pre><code>@Composable fun TestExecutionOrder( text: String, arr: CircularArray&lt;Faaa&gt;, stack: Stack&lt;CircularArray&lt;Faaa&gt;&gt;, content: @Composable () -&gt; Unit, ) { arr.addLast(Faaa(text)) // Same reference for all children stack.push(CircularArray&lt;Faaa&gt;()) // create new circularArray for new children content() } data class Faaa(val name: String)//val size : IntSize,val pos: Offset) @Preview @Composable fun test() { val stack = Stack&lt;CircularArray&lt;Faaa&gt;&gt;() stack.push(CircularArray&lt;Faaa&gt;()) TestExecutionOrder(&quot;1&quot;,stack.peek(),stack) { var referenceCir = stack.peek() TestExecutionOrder(&quot;2&quot;,referenceCir,stack) { var referenceCir2 = stack.peek() TestExecutionOrder(&quot;15&quot;,referenceCir2,stack) {} TestExecutionOrder(&quot;5&quot;,referenceCir2,stack) { var referenceCir3 = stack.peek() TestExecutionOrder(&quot;6&quot;,referenceCir3,stack) {} TestExecutionOrder(&quot;7&quot;,referenceCir3,stack) {} } } TestExecutionOrder(&quot;3&quot;,referenceCir,stack) {} TestExecutionOrder(&quot;10&quot;,referenceCir,stack) {} } } </code></pre> <p>I am assuming I am overthinking this stuff because I came from a QML/C++ Environment. How can one achieve this kind of stuff?</p> <p>The Goal is to make this thing self managing I wrap my <code>composable function</code> around other functions and it automatically knows how many children of the same type it has without me explicitly passing it as a parameter.</p> <h3>EDIT1: Im aware that compose function can <a href="https://developer.android.com/jetpack/compose/mental-model#any-order" rel="nofollow noreferrer">execute in any order</a></h3>
[ { "answer_id": 74432550, "author": "Ojav", "author_id": 9370018, "author_profile": "https://Stackoverflow.com/users/9370018", "pm_score": 0, "selected": false, "text": "Tree DataStructure" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9370018/" ]
74,375,182
<p>There is a problem with odd numbers. When I run the function on even numbers, the code works.</p> <pre><code> #recursive demo function1 #Even nums def evenNum(num): if num % 2 != 0: print(&quot;enter a even number&quot;) if num == 2: return num else: return evenNum(num-2) evenNum(5) </code></pre> <pre><code> output : Canceled future for execute_request message before replies were done </code></pre>
[ { "answer_id": 74375224, "author": "maciek97x", "author_id": 10626495, "author_profile": "https://Stackoverflow.com/users/10626495", "pm_score": 2, "selected": false, "text": "if" }, { "answer_id": 74385641, "author": "Sefa_Kurtuldu", "author_id": 20092321, "author_profile": "https://Stackoverflow.com/users/20092321", "pm_score": 0, "selected": false, "text": "#recursive function1\n#positive Even nums\ndef evenNum(num):\n print(num)\n if num % 2 != 0:\n return print(\"enter an even number\")\n elif num == 2:\n pass\n else:\n return evenNum(abs(num)-2) \nevenNum(5)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20092321/" ]
74,375,192
<p>I am working on a binary image segmentation problem using Tensorflow Keras. The masks are in grayscale and images are in RGB. I need to convert the grayscale masks to binary and store them in a Numpy array. The following is the code:</p> <pre><code> from tensorflow.keras.preprocessing.image import load_img,ImageDataGenerator from skimage.transform import resize import os from tqdm import tqdm im_height,im_width = 256,256 threshold = 150 ids_test = next(os.walk(&quot;data/test/image&quot;))[2] # list of names all images in the given path print(&quot;No. of images = &quot;, len(ids_test)) X_ts = np.zeros((len(ids_test), im_height, im_width, 3), dtype=np.float32) Y_ts = np.zeros((len(ids_test), im_height, im_width, 1), dtype=np.float32) for n, id_ in tqdm(enumerate(ids_test), total=len(ids_test)): img = load_img(&quot;data/test/image/&quot;+id_, color_mode = &quot;rgb&quot;) x_img = img_to_array(img) x_img = resize(x_img, (im_height, im_width,3), mode = 'constant', preserve_range = True) # Load masks mask = img_to_array(load_img(&quot;data/test/label/&quot;+id_, color_mode = &quot;grayscale&quot;)) #grayscale binarized = 1.0 * (mask &gt; threshold) mask = resize(binarized, (im_height,im_width,1), mode = 'constant', preserve_range = True) # Save images X_ts[n] = x_img/255.0 Y_ts[n] = mask </code></pre>
[ { "answer_id": 74375224, "author": "maciek97x", "author_id": 10626495, "author_profile": "https://Stackoverflow.com/users/10626495", "pm_score": 2, "selected": false, "text": "if" }, { "answer_id": 74385641, "author": "Sefa_Kurtuldu", "author_id": 20092321, "author_profile": "https://Stackoverflow.com/users/20092321", "pm_score": 0, "selected": false, "text": "#recursive function1\n#positive Even nums\ndef evenNum(num):\n print(num)\n if num % 2 != 0:\n return print(\"enter an even number\")\n elif num == 2:\n pass\n else:\n return evenNum(abs(num)-2) \nevenNum(5)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7575552/" ]
74,375,210
<p>I have been able to successfully map a dictionary to a dataframe column using two categorical variables as keys, but I can't figure out how to do it if one of my target values should satisfy a condition rather than equal a value.</p> <p>For example, consider the following dataframe:</p> <pre><code>df = pd.DataFrame({'F1': ['Y', 'N', 'N', 'N'], 'F2': ['HB', 'CP', '4D', 'CV'], 'F3': [10000, 5000, 15000, 2000]}) df['F12T'] = df[['F1','F2']].apply(tuple, axis=1) df['F13T'] = df[['F1','F3']].apply(tuple, axis=1) </code></pre> <p>You get:</p> <pre><code> F1 F2 F3 F12T F13T 0 Y HB 10000 (Y, HB) (Y, 10000) 1 N CP 5000 (N, CP) (N, 5000) 2 N 4D 15000 (N, 4D) (N, 15000) 3 N CV 2000 (N, CV) (N, 2000) </code></pre> <p>Now to map on two categorical variables, easy, using <code>.map()</code>:</p> <pre><code>dict1 = {('Y', 'HB'): 1.1} df[&quot;R1&quot;] = df[&quot;F12T&quot;].map(dict1) print(df) F1 F2 F3 F12T F13T R1 0 Y HB 10000 (Y, HB) (Y, 10000) 1.1 1 N CP 5000 (N, CP) (N, 5000) NaN 2 N 4D 15000 (N, 4D) (N, 15000) NaN 3 N CV 2000 (N, CV) (N, 2000) NaN </code></pre> <p>But now what I'd like to do is make a new column and create that 1.1 value where F1 = N and F3 &gt; 2000 and F3 &lt; 15000 - essentially add a 1.1 to row 2.</p> <p>The dictionary I'd want to map I guess would look something like:</p> <pre><code>dict2 = {('N', '[2001, 15000)'): 1.1} </code></pre> <p>Which I'd like to result in:</p> <pre><code> F1 F2 F3 F12T F13T R1 R2 0 Y HB 10000 (Y, HB) (Y, 10000) 1.1 NaN 1 N CP 5000 (N, CP) (N, 5000) NaN 1.1 2 N 4D 15000 (N, 4D) (N, 15000) NaN NaN 3 N CV 2000 (N, CV) (N, 2000) NaN NaN </code></pre> <p>Any ideas would be greatly appreciated, thanks</p> <p><strong>EDIT: To be clear, I need to use a dictionary for this application due to downstream requirements, not loc or where etc. please!</strong></p>
[ { "answer_id": 74375224, "author": "maciek97x", "author_id": 10626495, "author_profile": "https://Stackoverflow.com/users/10626495", "pm_score": 2, "selected": false, "text": "if" }, { "answer_id": 74385641, "author": "Sefa_Kurtuldu", "author_id": 20092321, "author_profile": "https://Stackoverflow.com/users/20092321", "pm_score": 0, "selected": false, "text": "#recursive function1\n#positive Even nums\ndef evenNum(num):\n print(num)\n if num % 2 != 0:\n return print(\"enter an even number\")\n elif num == 2:\n pass\n else:\n return evenNum(abs(num)-2) \nevenNum(5)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12354472/" ]
74,375,231
<p>In a codebase I am working on, most functions takes as arguments several std::string. These strings represent different things, and I would like to define several classes to detect inconsistencies at compile time if possible.</p> <p>Here is an example of problematic code:</p> <pre><code>void displayIdentity(const std::string &amp;firstName, const std::string &amp;lastName) { std::cout &lt;&lt; &quot;First name = &quot; &lt;&lt; firstName &lt;&lt; &quot;\t; &quot; &lt;&lt; &quot;Last name = &quot; &lt;&lt; lastName &lt;&lt; std::endl; } const std::string firstName = &quot;John&quot;; const std::string lastName = &quot;Doe&quot;; displayIdentity(lastName, firstName); // clearly, it should have been // displayIdentity(firstName, lastName) </code></pre> <p>The current solution I am using is to use different classes defined using template:</p> <pre><code>template &lt;typename NAME&gt; class TypedString : public std::string { public: explicit TypedString(const char* s) : std::string{s} {} explicit TypedString(const std::string&amp; s) : std::string{s} {} }; </code></pre> <p>Then it becomes possible to detect inconsistency at compile time:</p> <pre><code>const FirstName firstName2{&quot;John&quot;}; const LastName lastName2{&quot;Doe&quot;}; displayIdentity2(firstName2, lastName2); // displayIdentity2(lastName2, firstName2); // error: invalid initialization of reference of type // 'const FirstName&amp;' from expression of type 'LastName' //const LastName lastName3{firstName2}; // error: invalid initialization, as expected const LastName lastName3{std::string(firstName2)}; // but conversion can to requested explicitly </code></pre> <p>I have started using this code, and it works as expected and helps me detect inconsistencies.</p> <p>I have read <a href="https://stackoverflow.com/questions/6006860/why-should-one-not-derive-from-c-std-string-class">on this post</a> that we should not inherit from std::string because it's destructor is not virtual.</p> <p>As the TypedString class is empty, it's destructors should be equivalent to the std::string destructor, so I don't see this as problem. Same things for methods, I don't care if std::string methods are called when using polymorphism, because I want TypedString to behave exactly like a string, except for construction/conversion...</p> <p>Am I correct? Or should I use a more verbose solution (using composition <a href="https://stackoverflow.com/questions/34287842/strongly-typed-using-and-typedef">as done here</a>) to solve my problem?</p>
[ { "answer_id": 74375287, "author": "lorro", "author_id": 6292621, "author_profile": "https://Stackoverflow.com/users/6292621", "pm_score": 0, "selected": false, "text": "std::string" }, { "answer_id": 74376464, "author": "Miles Budnek", "author_id": 4151599, "author_profile": "https://Stackoverflow.com/users/4151599", "pm_score": 2, "selected": false, "text": "delete" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15175771/" ]
74,375,240
<p>I have a lambda that ignores its <code>int</code> parameter and always returns a constant. If I mark it <code>consteval</code>, compilation fails because. The compiler complains about invoking the <code>consteval</code> lambda with a non-const parameter. But what does the parameter has to do with the lambda?</p> <p>From <a href="https://godbolt.org/z/q5Ecr18o7" rel="nofollow noreferrer">CompilerExplorer</a>:</p> <blockquote> <p>source:3:16: error: the value of 'i' is not usable in a constant expression 5 | lambda(i);</p> </blockquote> <pre><code>void bar (auto lambda, int start, int end) { for (int i=start; i&lt;end; ++i) { lambda(i); } } int main( ) { auto foo = [] (int) consteval { return 2;}; bar(foo, 1, 9); return 0; } </code></pre>
[ { "answer_id": 74375326, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 2, "selected": false, "text": "int&" }, { "answer_id": 74375572, "author": "Ayxan Haqverdili", "author_id": 10147399, "author_profile": "https://Stackoverflow.com/users/10147399", "pm_score": 0, "selected": false, "text": "#include <type_traits>\n\nvoid bar(auto lambda, int start, int end) {\n for (int i = start; i < end; ++i) {\n if constexpr (std::is_invocable_v<decltype(lambda)>) {\n lambda();\n } else {\n lambda(i);\n }\n }\n}\n\nint main() {\n bar([] () consteval { return 2; }, 1, 9);\n bar([](int) { return 2; }, 1, 9);\n\n return 0;\n}\n" }, { "answer_id": 74481177, "author": "303", "author_id": 7107236, "author_profile": "https://Stackoverflow.com/users/7107236", "pm_score": 0, "selected": false, "text": "bar" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292792/" ]
74,375,268
<p>I've installed pypy3 on Mac, and would like to use it to speed up a python script to analyse a live video feed. I've tried to install opencv-python with pip and pip_pypy3, but get the following error:</p> <pre><code>Building wheels for collected packages: opencv-python Building wheel for opencv-python (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for opencv-python (pyproject.toml) did not run successfully. │ exit code: 1 ╰─&gt; [9 lines of output] Traceback (most recent call last): File &quot;/private/var/folders/7v/1cg_j6kd34l4k8zgvj782ndc0000gn/T/pip-build-env-nymhzjmp/overlay/site-packages/skbuild/setuptools_wrap.py&quot;, line 612, in setup cmkr = cmaker.CMaker(cmake_executable) File &quot;/private/var/folders/7v/1cg_j6kd34l4k8zgvj782ndc0000gn/T/pip-build-env-nymhzjmp/overlay/site-packages/skbuild/cmaker.py&quot;, line 148, in __init__ self.cmake_version = get_cmake_version(self.cmake_executable) File &quot;/private/var/folders/7v/1cg_j6kd34l4k8zgvj782ndc0000gn/T/pip-build-env-nymhzjmp/overlay/site-packages/skbuild/cmaker.py&quot;, line 105, in get_cmake_version ) from err Problem with the CMake installation, aborting build. CMake executable is cmake [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for opencv-python Failed to build opencv-python ERROR: Could not build wheels for opencv-python, which is required to install pyproject.toml-based projects </code></pre> <p>Any idea how I can get around this error? Thanks!</p> <p>(The advice from people who have previously had this problem is rather confusing...)</p>
[ { "answer_id": 74375452, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "Mac" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19626801/" ]
74,375,282
<h2>Background</h2> <p>I have a MySQL server running on a remote machine and am trying to debug a Django application running locally that connects to that remote database. Our team does this by forwarding the remote port 3306 to the local port 3308 using <a href="https://www.putty.org/" rel="nofollow noreferrer">PuTTY</a>. I found out recently that you can do this within VS Code as well using the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh" rel="nofollow noreferrer">Remote - SSH</a> VS Code extension created by Microsoft.</p> <p>After the SSH connection is configured, this is done by adding the port to the ports tab as shown below: <a href="https://i.stack.imgur.com/amNBl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/amNBl.png" alt="enter image description here" /></a></p> <p>An alternative, described in the <a href="https://code.visualstudio.com/docs/remote/ssh" rel="nofollow noreferrer">Remote - SSH docs</a>, is to add the port to the ssh config file. This opens the port automatically every time an SSH connection is made:</p> <p><a href="https://i.stack.imgur.com/r80Fw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r80Fw.png" alt="enter image description here" /></a></p> <h2>The Problem</h2> <p>The trouble with both of these methods is it seems that the SSH connection cannot be made without the entire VS Code window turning into an &quot;SSH Window&quot; that is connected to the remote machine. Since I am working on a the Django application locally, this means I then need a second window open just to forward the port.</p> <p>I would really like to be able forward a port in the same window that I am working on the local Django application. I would prefer doing it with the Remote - SSH extension, but am open to other methods. Bonus points if the tunnel is created automatically when I open the Django app repo in VS Code.</p> <p>I tried searching for extensions that would do this and seeing if the Remote - SSH can connect without a dedicated window, but I couldn't find anything.</p>
[ { "answer_id": 74522194, "author": "evanstjabadi", "author_id": 13271830, "author_profile": "https://Stackoverflow.com/users/13271830", "pm_score": 1, "selected": false, "text": "ssh ubuntu@hostaddress -L 3308:127.0.0.1:3306" }, { "answer_id": 74522867, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "Host MyServer\n HostName host.address.com\n IdentityFile C:\\Users\\user\\identityFile\n User ubuntu\n LocalForward 127.0.0.1:3308 127.0.0.1:3306\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3593621/" ]
74,375,285
<p>I am currently trying to install the Android Emulator via the Android SDK and Tools dialog. But I am receiving the Error Message:</p> <p>Operation Failed: Installing Android Emulatorv31.2.10 &quot;Specified argument was out of the range of valid values&quot;.</p> <p>I removed all set up devices so far still no success. As for SDK Build Tools I have 33, 32 and 31 installed and Platforms as well 33, 32, 31</p> <p>Log:</p> <pre><code>[2022-11-09 13:53:41.5] WARNING: [Resiliency.Polly.Policies]: Delegate has thrown System.Threading.Tasks.TaskCanceledException: A task was canceled. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at Xamarin.Installer.AndroidSDK.Manager.Helper.&lt;CheckIfNetworkAvailable&gt;d__38.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Polly.Retry.AsyncRetryEngine.&lt;ImplementationAsync&gt;d__0`1.MoveNext(), retrying... [2022-11-09 13:53:42.6] ACTION: Install start component emulator [2022-11-09 13:53:42.6] EXCEPTION: Downloading Android Emulator v31.2.10 failed, Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. at Xamarin.Installer.AndroidSDK.MonitorWithTotalProgress.set_SubComponentsCount(Int32 value) at Xamarin.Installer.AndroidSDK.Manager.AndroidSDKComponent.&lt;Install&gt;d__66.MoveNext() [2022-11-09 13:53:42.6] ACTION: Install result InstallationError component emulator [2022-11-09 13:53:42.6] ACTION: ApplySdkComponentChanged uninstall:[] install:[emulator] </code></pre>
[ { "answer_id": 74522194, "author": "evanstjabadi", "author_id": 13271830, "author_profile": "https://Stackoverflow.com/users/13271830", "pm_score": 1, "selected": false, "text": "ssh ubuntu@hostaddress -L 3308:127.0.0.1:3306" }, { "answer_id": 74522867, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 3, "selected": true, "text": "Host MyServer\n HostName host.address.com\n IdentityFile C:\\Users\\user\\identityFile\n User ubuntu\n LocalForward 127.0.0.1:3308 127.0.0.1:3306\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/709672/" ]
74,375,323
<p>Hi I have a pandas dataframe that looks roughly like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Item</th> <th>Sales</th> </tr> </thead> <tbody> <tr> <td>01-01-2022</td> <td>iphone</td> <td>$20</td> </tr> <tr> <td>02-01-2022</td> <td>iphone</td> <td>$40</td> </tr> <tr> <td>01-02-2022</td> <td>iphone</td> <td>$40</td> </tr> <tr> <td>02-02-2022</td> <td>macbook</td> <td>$20</td> </tr> <tr> <td>03-02-2022</td> <td>macbook</td> <td>$40</td> </tr> <tr> <td>04-02-2022</td> <td>macbook</td> <td>$50</td> </tr> </tbody> </table> </div> <p>I am trying to get the count per item per month in a format like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Item</th> <th>January</th> <th>February</th> </tr> </thead> <tbody> <tr> <td>iphone</td> <td>2</td> <td>1</td> </tr> <tr> <td>macbook</td> <td>0</td> <td>3</td> </tr> </tbody> </table> </div> <p>and in the end I want a column that takes the average of each column. So the final dataframe would look like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Item</th> <th>January</th> <th>February</th> <th>Average</th> </tr> </thead> <tbody> <tr> <td>iphone</td> <td>2</td> <td>1</td> <td>1,5</td> </tr> <tr> <td>macbook</td> <td>0</td> <td>3</td> <td>1,5</td> </tr> </tbody> </table> </div> <p>I have tried many pandas groupby functions but I can't seem to get it done. Can somebody help me?</p> <p>I tried to use pd.Grouper(freq='M') but that didn't work out so well. The months don't show up as columns but as rows per sales item. Any ideas?</p>
[ { "answer_id": 74375417, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "crosstab" }, { "answer_id": 74375666, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 1, "selected": false, "text": " Item Sales\nDate \n2022-01-01 iphone $20\n2022-02-01 iphone $40\n2022-01-02 iphone $40\n2022-02-02 macbook $20\n2022-03-02 macbook $40\n2022-04-02 macbook $50\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20459267/" ]
74,375,330
<p>When I call the function without the decorator a list of all files with the matching extension is returned. However, if I add the decorator <code>@get_time</code>, I do not get a return value from the function.</p> <pre><code>def get_time(func): from time import perf_counter from functools import wraps &quot;&quot;&quot;Times any function&quot;&quot;&quot; @wraps(func) def wrapper(*args, **kwargs): start_time = perf_counter() func(*args, **kwargs) end_time = perf_counter() total_time = round(end_time - start_time, 5) print(func.__name__) print(f&quot;Took {total_time} seconds&quot;) return wrapper def getListOfFiles(dirName, file_extension): &quot;&quot;&quot; Finds all files with matching file extension in given directory Parameters ---------- dirName : string Either a path from a single file or a path of a directory. file_extension : string, list of string The extension of the file type which should be taken into account. Can be one or more than one extension. Returns ------- list_of_files : list of string Returns list of all files &quot;&quot;&quot; import os extension_list = [] if isinstance(file_extension, str): extension_list.append(file_extension) if isinstance(file_extension, list): extension_list = file_extension # create a list of file and subdirectories # names in the given directory listOfFile = os.listdir(dirName) allFiles = list() # Iterate over all the entries for entry in listOfFile: # Create full path fullPath = os.path.join(dirName, entry) # If entry is a directory then get the list of files in this directory if os.path.isdir(fullPath): allFiles = allFiles + getListOfFiles(fullPath, extension_list) else: name, extension = os.path.splitext(fullPath) if any(extension in s for s in extension_list): allFiles.append(fullPath) return allFiles @get_time def get_list_of_files(path, file_type): &quot;&quot;&quot; Generates a list with all file path from a given path. Parameters ---------- path : string Either a path from a single file or a path of a directory. file_type : string, list of string The extension of the file type which should be taken into account. Can be one or more than one extension. Returns ------- list_of_files : list of string Returns the synchrony of the input spike trains. &quot;&quot;&quot; import os all_files = [] # check if path is a file or directory if os.path.isdir(path): all_files = getListOfFiles(path, file_type) else: all_files.append(path) return all_files if __name__ == '__main__': path = &quot;/mnt/HDD/Data/FrenchData/culture_du_29_11_2021_version_matlab_experience_1&quot; all_files = get_list_of_files(path, [&quot;.png&quot;]) print(all_files) </code></pre>
[ { "answer_id": 74375395, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 3, "selected": true, "text": "func()" }, { "answer_id": 74375404, "author": "matszwecja", "author_id": 9296093, "author_profile": "https://Stackoverflow.com/users/9296093", "pm_score": 2, "selected": false, "text": "wrapper" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19971373/" ]
74,375,340
<p>im trying o set a onChange Function when there is a change on the dropdown. onChange it should be forwarded to another Side (using Navbar in React)</p> <pre><code>import React from 'react'; import Select from 'react-select' import { Link } from &quot;react-router-dom&quot;; import '../index.css'; import { Navbar } from &quot;../components&quot;; import { BodyMain } from '../components'; function handleChange() { &lt;Link to=&quot;/check1&quot;&gt; &lt;/Link&gt; } const options = [ { value: 'Claire', label: 'Claire', }, { value: 'Coco', label: 'Coco' }, { value: 'Emma', label: 'Emma' }, { value: 'Leni', label: 'Leni' }, const hotel = () =&gt; { return( &lt;Select onChange={handleChange} options={options} /&gt; ) } export default hotel; </code></pre> <p>How can i bring that handleChange to life?</p> <p>Thank you</p> <p>As seen i tried to set the onChange right after the select, also on different positions such as in the const [option]</p> <p>Ive seen other documentations where they had a smaller im using the bigger one with it does make a colour change but i dont know where to go from here</p>
[ { "answer_id": 74375395, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 3, "selected": true, "text": "func()" }, { "answer_id": 74375404, "author": "matszwecja", "author_id": 9296093, "author_profile": "https://Stackoverflow.com/users/9296093", "pm_score": 2, "selected": false, "text": "wrapper" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19836017/" ]
74,375,348
<p>I am looking at some typescript code for the first time and I'm clear on what it does until the last line. I believe that is a Nullish coalescing operator but I don't understand why the regex result is written <strong>matches?.[1]</strong> when <strong>matches[1]</strong> appears to work. Can anyone help with this?</p> <pre><code>const titleRegex = /&lt;title(?:.*?)&gt;(.*?)&lt;\/title&gt;/ const extractTitle = (website: string): string =&gt; { const matches = titleRegex.exec(website) return matches?.[1] ?? '' } </code></pre>
[ { "answer_id": 74375395, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 3, "selected": true, "text": "func()" }, { "answer_id": 74375404, "author": "matszwecja", "author_id": 9296093, "author_profile": "https://Stackoverflow.com/users/9296093", "pm_score": 2, "selected": false, "text": "wrapper" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10020835/" ]
74,375,400
<p>I am new to python and jupyter notebook and I am using windows. Recently I installed Anaconda Navigator 2.3.1 and the python verson 3.9.13 on my computer. After entering the command <code>jupyter notebook</code> on the command-line, my browser doesn't open jupyter notebook, instead that showing me this error message:</p> <pre><code>(base) C:\Users\USER&gt;jupyter notebook Traceback (most recent call last): File &quot;D:\Anaconda3\anaconda3\Scripts\jupyter-notebook-script.py&quot;, line 6, in &lt;module&gt; from notebook.notebookapp import main File &quot;D:\Anaconda3\anaconda3\lib\site-packages\notebook\notebookapp.py&quot;, line 79, in &lt;module&gt; from .services.contents.manager import ContentsManager File &quot;D:\Anaconda3\anaconda3\lib\site-packages\notebook\services\contents\manager.py&quot;, line 17, in &lt;module&gt; from nbformat import sign, validate as validate_nb, ValidationError File &quot;C:\Users\USER\AppData\Roaming\Python\Python39\site-packages\nbformat\__init__.py&quot;, line 14, in &lt;module&gt; from . import v1 File &quot;C:\Users\USER\AppData\Roaming\Python\Python39\site-packages\nbformat\v1\__init__.py&quot;, line 19, in &lt;module&gt; from .nbjson import reads as reads_json, writes as writes_json File &quot;C:\Users\USER\AppData\Roaming\Python\Python39\site-packages\nbformat\v1\nbjson.py&quot;, line 19, in &lt;module&gt; from base64 import encodestring ImportError: cannot import name 'encodestring' from 'base64' (D:\Anaconda3\anaconda3\lib\base64.py) </code></pre> <p>I don't understand what should do now? And how to solve this issue! Please help..........</p>
[ { "answer_id": 74375563, "author": "OranShuster", "author_id": 2750734, "author_profile": "https://Stackoverflow.com/users/2750734", "pm_score": 3, "selected": true, "text": "base64.encodestring" }, { "answer_id": 74429150, "author": "Francis Massolin", "author_id": 20498971, "author_profile": "https://Stackoverflow.com/users/20498971", "pm_score": 0, "selected": false, "text": "pip3 install nbformat==5.1.3\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12904389/" ]
74,375,401
<p>I have a componet that contains a list of posts. I want to delete some posts. my problem is that the removed posts does not removed on the screen, even when I use <code>StateHasChanged()</code>.</p> <p>Here is <code>PostListComponent.razor</code> file</p> <pre class="lang-razor prettyprint-override"><code>@if (PostsList != null) { foreach (var post in PostsList) { if(post.IsDeleted != true) { &lt;div&gt; &lt;span @onclick=&quot;@(()=&gt;DeletePost(post.PostId))&quot; class=&quot;oi oi-trash&quot; style=&quot;cursor: pointer;&quot;&gt;&lt;/span&gt; &lt;p&gt;post.Content&lt;/p&gt; &lt;/div&gt; } } } </code></pre> <p>and <code>PostListComponent.cs</code> :</p> <pre class="lang-cs prettyprint-override"><code>public partial class PostListComponent : ComponentBase { [Parameter] public List&lt;PostContent&gt; PostsList { get; set; } protected void DeletePost(string postId) { PostsList.FirstOrDefault(p =&gt; p.PostId == postId).IsDeleted=true; InvokeAsync(StateHasChanged); } protected override async Task OnInitializedAsync() { DBContext _db; _db = DbFactory.CreateDbContext(); PostsList = _db.Posts.Where(s =&gt; (s.IsDeleted != true).ToList(); } } </code></pre>
[ { "answer_id": 74375563, "author": "OranShuster", "author_id": 2750734, "author_profile": "https://Stackoverflow.com/users/2750734", "pm_score": 3, "selected": true, "text": "base64.encodestring" }, { "answer_id": 74429150, "author": "Francis Massolin", "author_id": 20498971, "author_profile": "https://Stackoverflow.com/users/20498971", "pm_score": 0, "selected": false, "text": "pip3 install nbformat==5.1.3\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7826774/" ]
74,375,419
<p>I have a custom user store in my .NET Core 6 site. The corresponding user table in DB contains a field called <code>Lockout</code>.</p> <p>When a user signs in, I need that field to be used to forbid the user to login if that field is true.</p> <p>The <code>Login</code> action of the Account Controller has this code:</p> <pre><code> var result = await _signInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { var appUser = await _userManager.FindByNameAsync(model.Login); if (appUser.Roles == null || appUser.Roles.Count == 0) { await PerformLogOff(); return Json(&quot;ERROR: No tiene autorización para ingresar al sistema.&quot;); } else { returnUrl ??= Request.Path.ToString(); appUser.LastLoggedOn = DateTime.Now; if (!appUser.FirstLoggedOn.HasValue) appUser.FirstLoggedOn = appUser.LastLoggedOn; await _userManager.UpdateAsync(appUser); return Json(returnUrl); } } else if (result.IsLockedOut) return Json(&quot;ERROR: Su usuario está bloqueado.&quot;); else if (result.RequiresTwoFactor) return Json(&quot;ERROR: El usuario requiere autenticación de doble factor.&quot;); else return Json(&quot;ERROR: Nombre de usuario o contraseña incorrectos.&quot;); </code></pre> <p>When a user is locked out, I need <code>PasswordSignInAsync</code> to return <code>result.IsLockedOut</code>.</p> <p>How can I do it? Should I create a custom <code>SignInManager</code>? Notice that this has nothing to do with locking a user out when he fails to enter the password several times in login screen.</p> <p>Thanks Jaime</p>
[ { "answer_id": 74385720, "author": "Jason Pan", "author_id": 7687666, "author_profile": "https://Stackoverflow.com/users/7687666", "pm_score": 0, "selected": false, "text": "SignInManager.cs" }, { "answer_id": 74496457, "author": "jgasiorowski", "author_id": 2892208, "author_profile": "https://Stackoverflow.com/users/2892208", "pm_score": 0, "selected": false, "text": "result.IsLockedOut" }, { "answer_id": 74506563, "author": "MD Zand", "author_id": 5118861, "author_profile": "https://Stackoverflow.com/users/5118861", "pm_score": 2, "selected": false, "text": "var user = await _userManager.Users.Where(s => s.UserName == model.Username).FirstOrDefaultAsync();\n if (user != null)\n {\n if (!user.IsActive)\n {\n \n ModelState.AddModelError(\"\", \"User has been deactivated\");\n//Log the failure\n \n return View();\n }\n }\n" }, { "answer_id": 74523691, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "public class CustomSignInManager : SignInManager<ApplicationUser>\n{\n public CustomSignInManager(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<ApplicationUser>> logger) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger)\n {\n }\n \n public override async Task<SignInResult> PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)\n {\n var user = await UserManager.FindByNameAsync(userName);\n \n if (user != null && user.Lockout)\n {\n return SignInResult.LockedOut;\n }\n \n return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure);\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048588/" ]
74,375,450
<p><strong>Disclaimer: I am new to JS so this problem is probably pretty simple to solve, but I have consulted all resources and stack overflow posts I could find online on the subject</strong></p> <p>This is probably something simple that's missing but I haven't been able to debug this problem :</p> <p>I want to connect an Azure Function API to a React app, but I am unable to process the Html Response, which makes my await functions hang.</p> <p>Here is the very simple Azure functions API code :</p> <pre><code>import logging import azure.functions as func import json def main(req: func.HttpRequest) -&gt; func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') return func.HttpResponse( json.dumps({ 'recommendations': [1,2,3,4,5] }), mimetype=&quot;application/json&quot; ); </code></pre> <p>And here is my React based app (running with Expo) :</p> <pre><code>class App extends Component { state = { selectedUser: 0, step: 0, recommendations: 1 }; goToStep0 = async () =&gt; { this.setState({ step: 0, recommendations: 1 }); }; goToStep1 = async () =&gt; { const { data: rec } = await axios.get(config.API_URL); //const rec = await axios.get(config.API_URL); // const options = {method: &quot;GET&quot;}; // var rec; // fetch(config.API_URL,options) // .then(data =&gt; {rec = data.recommendations;}); this.setState({ step: 1, recommendations: rec }); }; </code></pre> <p>The Azure function <strong>is receiving input and returns a successful answer everytime</strong>.</p> <p>What I have tried :</p> <ul> <li>Changing the the Azure function app to return a string</li> <li>Trying to get the request with fetch</li> <li>Removing async and running a more old school request :</li> </ul> <pre><code>var rec; fetch(config.API_URL) .then(response =&gt; response.json()) .then(data =&gt; { rec = data }); </code></pre> <ul> <li>Probably at least 10 other things I have forgotten (I have wasted more than 4 hours on this...)</li> </ul> <p>Thanks a lot in advance for your help!</p> <p>Edit : Below is the code for the rendering part of the app (text is in French) :</p> <pre><code> render() { if (!config.API_URL) { return ( &lt;View style={styles.container}&gt; &lt;Image style={{ resizeMode: &quot;center&quot;, width: 450, height: 150 }} source={require(&quot;./assets/icon-flat.png&quot;)} /&gt; &lt;Text style={{ color: &quot;red&quot;, margin: 20 }}&gt; L'app n'est pas configurée correctement. Mettez à jour le fichier config.json comme indiqué dans le README. &lt;/Text&gt; &lt;/View&gt; ); } return ( &lt;View style={styles.container}&gt; &lt;Image style={{ resizeMode: &quot;center&quot;, width: 450, height: 150 }} source={require(&quot;./assets/icon-flat.png&quot;)} /&gt; &lt;Text style={{ fontSize: 18, padding: 20, textAlign: &quot;center&quot; }}&gt; Choisissez votre profil afin de recevoir des recommendations de lecture personnalisées : {this.state.recommendations.toString()} Quel est mon état : {this.state.step} &lt;/Text&gt; &lt;Picker style={{ height: 200, width: &quot;80%&quot;, margin: 30 }} selectedValue={this.state.selectedUser} onValueChange={value =&gt; this.setState({ selectedUser: value })} &gt; {[...Array(10000).keys()].map(e =&gt; ( &lt;Picker.Item key={e} label={`User ${e}`} value={e} /&gt; ))} &lt;/Picker&gt; &lt;Button title=&quot;Se connecter&quot; onPress={this.goToStep1} /&gt; &lt;/View&gt; ); } } </code></pre>
[ { "answer_id": 74385720, "author": "Jason Pan", "author_id": 7687666, "author_profile": "https://Stackoverflow.com/users/7687666", "pm_score": 0, "selected": false, "text": "SignInManager.cs" }, { "answer_id": 74496457, "author": "jgasiorowski", "author_id": 2892208, "author_profile": "https://Stackoverflow.com/users/2892208", "pm_score": 0, "selected": false, "text": "result.IsLockedOut" }, { "answer_id": 74506563, "author": "MD Zand", "author_id": 5118861, "author_profile": "https://Stackoverflow.com/users/5118861", "pm_score": 2, "selected": false, "text": "var user = await _userManager.Users.Where(s => s.UserName == model.Username).FirstOrDefaultAsync();\n if (user != null)\n {\n if (!user.IsActive)\n {\n \n ModelState.AddModelError(\"\", \"User has been deactivated\");\n//Log the failure\n \n return View();\n }\n }\n" }, { "answer_id": 74523691, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "public class CustomSignInManager : SignInManager<ApplicationUser>\n{\n public CustomSignInManager(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<ApplicationUser>> logger) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger)\n {\n }\n \n public override async Task<SignInResult> PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)\n {\n var user = await UserManager.FindByNameAsync(userName);\n \n if (user != null && user.Lockout)\n {\n return SignInResult.LockedOut;\n }\n \n return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure);\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19108231/" ]
74,375,453
<p>I am trying to search using <code>node.js</code>, <code>ejs</code> and <code>mongoose</code>. All the filter parameters are working perfectly but only <code>categoryIds</code> is not (stored as a collection of ObjectIDs in the mongodb document, referring to the respective document in <code>categories</code> collection), always giving me the empty record set.</p> <p>For example:<br /> If I need to find the a movie called <code>Cosmos</code> (see the attached screenshot) then I can easily find it with all or any filter except <code>categories</code>. Once I select any category, the record-set will go blank even if the I have selected the one which it belongs to.</p> <p>model.js</p> <pre class="lang-js prettyprint-override"><code>const Model = mongoose.model('Movie', new Schema({ ... categoryIds: [{ type: Schema.Types.ObjectId, trim: true, default: null, ref: 'Category', }], copyrightId: { type: Schema.Types.ObjectId, trim: true, default: null, ref: 'Copyright', }, ... }, { timestamps: true }); </code></pre> <p>Controller.js</p> <pre class="lang-js prettyprint-override"><code>Router.get('/', (req, res) =&gt; { const search = req.query; const conditions = (() =&gt; { let object = {}; ['releaseYear', 'languageId', 'copyrightId'].forEach(filter =&gt; { if (search[filter] != '') { object[filter] = search[filter]; } }); if (typeof search.categoryIds !== 'undefined') { object.categoryIds = []; search.categoryIds.forEach(item =&gt; object.categoryIds.push(item)); } if (search.keywords != '') { object.title = { $regex: search.keywords, $options: 'i' }; } return object; })(); const count = await Model.count(conditions); const items = await Model.find(conditions, { __v: false, imdb: false, trailer: false, createdAt: false, updatedAt: false, }).sort({ status: -1, releaseYear: -1, title: 1 }) .populate('languageId', ['title']) .populate('copyrightId', ['title']) .populate('categoryIds', ['title']) .skip(serialNumber) .limit(perPage); ... }); </code></pre> <p>All the fields in the search form</p> <pre class="lang-json prettyprint-override"><code>{ categoryIds: [ '6332a8a2a336e8dd78e3fe30', '6332a899a336e8dd78e3fe2e', '6332a87ba336e8dd78e3fe2c', '634574ab339b1a6b09c1e144' ], languageId: '', copyrightId: '', releaseYear: '', rating: '', seen: '', status: '', keywords: '', submit: 'search' // button } </code></pre> <p>filtered search parameters</p> <pre class="lang-json prettyprint-override"><code>{ categoryIds: [ '6332a8a2a336e8dd78e3fe30', '6332a899a336e8dd78e3fe2e', '6332a87ba336e8dd78e3fe2c', '634574ab339b1a6b09c1e144' ] } </code></pre> <p>Here is the screenshot of mongodb document. <a href="https://i.stack.imgur.com/PdWJl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PdWJl.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74385720, "author": "Jason Pan", "author_id": 7687666, "author_profile": "https://Stackoverflow.com/users/7687666", "pm_score": 0, "selected": false, "text": "SignInManager.cs" }, { "answer_id": 74496457, "author": "jgasiorowski", "author_id": 2892208, "author_profile": "https://Stackoverflow.com/users/2892208", "pm_score": 0, "selected": false, "text": "result.IsLockedOut" }, { "answer_id": 74506563, "author": "MD Zand", "author_id": 5118861, "author_profile": "https://Stackoverflow.com/users/5118861", "pm_score": 2, "selected": false, "text": "var user = await _userManager.Users.Where(s => s.UserName == model.Username).FirstOrDefaultAsync();\n if (user != null)\n {\n if (!user.IsActive)\n {\n \n ModelState.AddModelError(\"\", \"User has been deactivated\");\n//Log the failure\n \n return View();\n }\n }\n" }, { "answer_id": 74523691, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "public class CustomSignInManager : SignInManager<ApplicationUser>\n{\n public CustomSignInManager(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<ApplicationUser>> logger) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger)\n {\n }\n \n public override async Task<SignInResult> PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)\n {\n var user = await UserManager.FindByNameAsync(userName);\n \n if (user != null && user.Lockout)\n {\n return SignInResult.LockedOut;\n }\n \n return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure);\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136807/" ]
74,375,476
<p>I am trying to create a column, that should do a calculation per product, based on multiple columns.</p> <p>Logic for the calculation column:</p> <ul> <li>Calculations should be done per product</li> <li>Use quantity as default</li> <li>IF promo[Y/N] = 1, then take previous weeks quantity * season perc. change.</li> <li>Except when the promo is on the first week of the product. Then keep quantity as well.</li> </ul> <p>In the example below, You see the calculation column (I placed comments for the logic).</p> <pre><code>week product promo[Y/N] quantity Season calculation 1 A 0 100 6 100 # no promo, so = quantity col 2 A 0 100 10 100 # no promo, so = quantity col 3 A 1 ? -10 90 # 100 (quantity last week)- 10% (season) 4 A 1 ? 20 108 # quantity last week, what we calculated, 90 + 20% (18) = 108. 5 A 0 80 4 80 # no promo, so = quantity col 1 B 1 100 6 100 # Promo, but first week of this product. So regular quantity. 2 B 0 100 10 100 # no promo, so = quantity col 3 B 1 ? -10 90 # 100 (quantity last week)- 10% (season) 4 B 1 ? 20 108 # quantity last week, what we calculated, 90 + 20% (18) = 108. 5 B 0 80 4 80 # no promo, so = quantity col </code></pre> <p>I tried to solve this in two ways:</p> <ol> <li><p>Via a groupby(), and then the Product, but this was messing up my end file (I would like to have it in the format above, so with 1 additional column.</p> </li> <li><p>By looping over the dataframe with iterrows(). However, I messed up, because it doesn't distinct between products unfortunately.</p> </li> </ol> <p>Anyone an idea what a proper method is to solve this? Appreciated!</p>
[ { "answer_id": 74385720, "author": "Jason Pan", "author_id": 7687666, "author_profile": "https://Stackoverflow.com/users/7687666", "pm_score": 0, "selected": false, "text": "SignInManager.cs" }, { "answer_id": 74496457, "author": "jgasiorowski", "author_id": 2892208, "author_profile": "https://Stackoverflow.com/users/2892208", "pm_score": 0, "selected": false, "text": "result.IsLockedOut" }, { "answer_id": 74506563, "author": "MD Zand", "author_id": 5118861, "author_profile": "https://Stackoverflow.com/users/5118861", "pm_score": 2, "selected": false, "text": "var user = await _userManager.Users.Where(s => s.UserName == model.Username).FirstOrDefaultAsync();\n if (user != null)\n {\n if (!user.IsActive)\n {\n \n ModelState.AddModelError(\"\", \"User has been deactivated\");\n//Log the failure\n \n return View();\n }\n }\n" }, { "answer_id": 74523691, "author": "GPT-3", "author_id": 20562957, "author_profile": "https://Stackoverflow.com/users/20562957", "pm_score": 0, "selected": false, "text": "public class CustomSignInManager : SignInManager<ApplicationUser>\n{\n public CustomSignInManager(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<ApplicationUser>> logger) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger)\n {\n }\n \n public override async Task<SignInResult> PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)\n {\n var user = await UserManager.FindByNameAsync(userName);\n \n if (user != null && user.Lockout)\n {\n return SignInResult.LockedOut;\n }\n \n return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure);\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917999/" ]
74,375,486
<p>I would like to find out how to find repeated numbers after every 4 numbers.</p> <p>This is what I have.</p> <pre><code>arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8] size = len(arr) for i in range(0,size,4): if arr[i] == arr[i + 4] and arr[i + 4] == arr[i + 8] and arr[i + 8] == arr[i + 12 : print(arr[i]) </code></pre> <p>The output should be 5.</p>
[ { "answer_id": 74375560, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 1, "selected": false, "text": "arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]\n\nfor i in range(0, len(arr)):\n try:\n # checking the conditions\n if arr[i] == arr[i+4] and arr[i] == arr[i+8] and arr[i] == arr[i+12] :\n print(arr[i])\n except IndexError as e:\n # when you catch this exception, you can no longer find a number that match what you are looking for, so you break the loop.\n print(e)\n break\n" }, { "answer_id": 74375833, "author": "MrMattBusby", "author_id": 8507777, "author_profile": "https://Stackoverflow.com/users/8507777", "pm_score": 0, "selected": false, "text": "arr" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20459398/" ]
74,375,491
<p>To put it simply, I was given a .txt file with a list of words in it, then asked to read it in python and store it in a list with a function. So far, no problem. I wrote something that looks like this:</p> <pre><code>def load_lexicon(): with open(&quot;lexicon.txt&quot;, &quot;r&quot;) as f: content_list = f.read().splitlines() lexique = open(&quot;lexicon.txt&quot;, &quot;r&quot;) liste_des_mots = [] for i in lexique: ligne = i.strip() liste = ligne.split() liste_des_mots.append(liste) return liste_des_mots </code></pre> <p>The problem is that I would like to create a function that accesses this list that I created in the previous function and checks if a given word is there or not. I tried something like this:</p> <pre><code>def check_word(): search_word = input(&quot;enter the word you want to search for: &quot;) if search_word in load_lexicon(): print ('word found') else: print ('word not found') </code></pre> <p>But the thing is, no matter what word I put in, whether it's in the .txt file or not it always returns that the word is not in it, for example:</p> <pre><code>enter the word you want to search for: 'a' word not found </code></pre> <p>or</p> <pre><code>enter the word you want to search for: a word not found </code></pre> <p>just so you know, a is in the .txt file</p>
[ { "answer_id": 74375560, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 1, "selected": false, "text": "arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]\n\nfor i in range(0, len(arr)):\n try:\n # checking the conditions\n if arr[i] == arr[i+4] and arr[i] == arr[i+8] and arr[i] == arr[i+12] :\n print(arr[i])\n except IndexError as e:\n # when you catch this exception, you can no longer find a number that match what you are looking for, so you break the loop.\n print(e)\n break\n" }, { "answer_id": 74375833, "author": "MrMattBusby", "author_id": 8507777, "author_profile": "https://Stackoverflow.com/users/8507777", "pm_score": 0, "selected": false, "text": "arr" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20406558/" ]
74,375,513
<p>I have a vector of integers that I want to split by 3, then I have to order the splitted parts and put bac into integer vector.</p> <pre><code>as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8)) </code></pre> <p>First step - split like this:</p> <pre><code>16,9,2 17,10,3 18,11,4 19,12,5 20,13,6 21,14,7 22,15,8 </code></pre> <p>Second step - order:</p> <pre><code>2,9,16 3,10,17 4,11,18 5,12,19 6,13,20 7,14,21 8,15,22 </code></pre> <p>Third step - put back into integer vector:</p> <pre><code>2,9,16,3,10,17,4,11,18,5,12,19,6,13,20,7,14,21,8,15,22 </code></pre>
[ { "answer_id": 74375612, "author": "swolf", "author_id": 2433233, "author_profile": "https://Stackoverflow.com/users/2433233", "pm_score": 3, "selected": true, "text": "x <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nspl.x <- split(x, ceiling(seq_along(x)/3)) # split the vector\nspl.x <- lapply(spl.x, sort) # sort each element of the list\nReduce(c, spl.x) # Reduce list to vector\n" }, { "answer_id": 74375637, "author": "Clemsang", "author_id": 6356430, "author_profile": "https://Stackoverflow.com/users/6356430", "pm_score": 0, "selected": false, "text": "v <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nres <- split(v, 0:(length(v)-1) %/%3)\nunlist(lapply(res, sort), use.names = FALSE)\n" }, { "answer_id": 74375656, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "matrix" }, { "answer_id": 74375735, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 0, "selected": false, "text": "v <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nm <- matrix(v, ncol = 3, byrow = TRUE)\nc(t(matrix(m[order(row(m), m)], nrow(m), byrow = TRUE)))\n\n[1] 2 9 16 3 10 17 4 11 18 5 12 19 6 13 20 7 14 21 8 15 22\n" }, { "answer_id": 74375765, "author": "islem", "author_id": 11952767, "author_profile": "https://Stackoverflow.com/users/11952767", "pm_score": 1, "selected": false, "text": "vector=as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nchunk <- 3\nn <- length(vector)\nr <- rep(1:ceiling(n/chunk),each=chunk)[1:n]\nlist_of3 <- split(vector,r)\n# > list_of3\n# $`1`\n# [1] 16 9 2\n# \n# $`2`\n# [1] 17 10 3\n# \n# $`3`\n# [1] 18 11 4\n# \n# $`4`\n# [1] 19 12 5\n# \n# $`5`\n# [1] 20 13 6\n# \n# $`6`\n# [1] 21 14 7\n# \n# $`7`\n# [1] 22 15 8\nsorted_list<- lapply(list_of3, function(x)sort(x))\nfinal_vector <- unname(unlist(sorted_list))\nfinal_vector\n# > final_vector\n# [1] 2 9 16 3 10 17 4 11 18 5 12 19 6 13 20 7 14 21 8 15 22```\n" }, { "answer_id": 74375766, "author": "Juan C", "author_id": 9462829, "author_profile": "https://Stackoverflow.com/users/9462829", "pm_score": 0, "selected": false, "text": "v = as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\n\nv2 = v %>% matrix(ncol= 3, byrow = T) \n\n\n# [,1] [,2] [,3]\n# [1,] 16 9 2\n# [2,] 17 10 3\n# [3,] 18 11 4\n# [4,] 19 12 5\n# [5,] 20 13 6\n# [6,] 21 14 7\n# [7,] 22 15 8\n\nv3 = v2[, rev(seq_len(ncol(v2)))]\n\n# [,1] [,2] [,3]\n# [1,] 2 9 16\n# [2,] 3 10 17\n# [3,] 4 11 18\n# [4,] 5 12 19\n# [5,] 6 13 20\n# [6,] 7 14 21\n# [7,] 8 15 22\n\n\nv4 = v3 %>% as.vector\n\n# [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9076548/" ]
74,375,522
<p>I am developing an application in Express and Vue js I'm getting this:</p> <p>Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/vue.js?v=460a75c2' does not provide an export named 'Vue' (at main.js?t=1667997788986:1:9)</p> <p>App.vue file :</p> <pre><code>import {Vue, createApp } from 'vue' import App from './App.vue' import './assets/main.css' import axios from 'axios' import vueAxios from 'vue-axios' Vue.use(axios, vueAxios) createApp(App).mount('#app') </code></pre> <p>My main.js file is :</p> <pre><code>&lt;script&gt; export default { data(){ return{ dataResponse: [], } }, methods: { async getDataResponse(){ const res = await axios.get(`${this.baseUrl}/catalog/home`) console.log(response) } }, created(){ this.getDataResponse() } } &lt;/script&gt; &lt;template&gt; &lt;h1&gt;Welcome&lt;/h1&gt; &lt;/template&gt; </code></pre>
[ { "answer_id": 74375612, "author": "swolf", "author_id": 2433233, "author_profile": "https://Stackoverflow.com/users/2433233", "pm_score": 3, "selected": true, "text": "x <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nspl.x <- split(x, ceiling(seq_along(x)/3)) # split the vector\nspl.x <- lapply(spl.x, sort) # sort each element of the list\nReduce(c, spl.x) # Reduce list to vector\n" }, { "answer_id": 74375637, "author": "Clemsang", "author_id": 6356430, "author_profile": "https://Stackoverflow.com/users/6356430", "pm_score": 0, "selected": false, "text": "v <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nres <- split(v, 0:(length(v)-1) %/%3)\nunlist(lapply(res, sort), use.names = FALSE)\n" }, { "answer_id": 74375656, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "matrix" }, { "answer_id": 74375735, "author": "Ritchie Sacramento", "author_id": 2835261, "author_profile": "https://Stackoverflow.com/users/2835261", "pm_score": 0, "selected": false, "text": "v <- as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nm <- matrix(v, ncol = 3, byrow = TRUE)\nc(t(matrix(m[order(row(m), m)], nrow(m), byrow = TRUE)))\n\n[1] 2 9 16 3 10 17 4 11 18 5 12 19 6 13 20 7 14 21 8 15 22\n" }, { "answer_id": 74375765, "author": "islem", "author_id": 11952767, "author_profile": "https://Stackoverflow.com/users/11952767", "pm_score": 1, "selected": false, "text": "vector=as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\nchunk <- 3\nn <- length(vector)\nr <- rep(1:ceiling(n/chunk),each=chunk)[1:n]\nlist_of3 <- split(vector,r)\n# > list_of3\n# $`1`\n# [1] 16 9 2\n# \n# $`2`\n# [1] 17 10 3\n# \n# $`3`\n# [1] 18 11 4\n# \n# $`4`\n# [1] 19 12 5\n# \n# $`5`\n# [1] 20 13 6\n# \n# $`6`\n# [1] 21 14 7\n# \n# $`7`\n# [1] 22 15 8\nsorted_list<- lapply(list_of3, function(x)sort(x))\nfinal_vector <- unname(unlist(sorted_list))\nfinal_vector\n# > final_vector\n# [1] 2 9 16 3 10 17 4 11 18 5 12 19 6 13 20 7 14 21 8 15 22```\n" }, { "answer_id": 74375766, "author": "Juan C", "author_id": 9462829, "author_profile": "https://Stackoverflow.com/users/9462829", "pm_score": 0, "selected": false, "text": "v = as.integer(c(16,9,2,17,10,3,18,11,4,19,12,5,20,13,6,21,14,7,22,15,8))\n\nv2 = v %>% matrix(ncol= 3, byrow = T) \n\n\n# [,1] [,2] [,3]\n# [1,] 16 9 2\n# [2,] 17 10 3\n# [3,] 18 11 4\n# [4,] 19 12 5\n# [5,] 20 13 6\n# [6,] 21 14 7\n# [7,] 22 15 8\n\nv3 = v2[, rev(seq_len(ncol(v2)))]\n\n# [,1] [,2] [,3]\n# [1,] 2 9 16\n# [2,] 3 10 17\n# [3,] 4 11 18\n# [4,] 5 12 19\n# [5,] 6 13 20\n# [6,] 7 14 21\n# [7,] 8 15 22\n\n\nv4 = v3 %>% as.vector\n\n# [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74375522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20459237/" ]