qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,490,803
<p>When trying to fill a table with rows using v-for it is quite easy to map the v-for elements 1:1 with the rows like:</p> <pre><code>&lt;template&gt; &lt;table&gt; &lt;tr v-for=&quot;item in items&quot;&gt;&lt;td&gt;{{item}}&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/template&gt; </code></pre> <p>My question is: how can I create multiple rows (eg td elements) per item (see following pseudocode):</p> <pre><code>&lt;template&gt; &lt;table&gt; &lt;nothing v-for=&quot;item in items&quot;&gt; &lt;tr&gt;&lt;td&gt;{{item.line1}}&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;{{item.line2}}&lt;/td&gt;&lt;/tr&gt; &lt;/nothing&gt; &lt;/table&gt; &lt;/template&gt; </code></pre> <p>Here <code>&lt;nothing&gt;</code> should not be emitted in the DOM as a level, only <code>&lt;td&gt;</code> directly under <code>&lt;table&gt;</code>.</p> <p>Is this possible?</p>
[ { "answer_id": 74491154, "author": "Dmitry Arestov", "author_id": 1032003, "author_profile": "https://Stackoverflow.com/users/1032003", "pm_score": 2, "selected": true, "text": "<template> nothing <table id=\"t1\">\n <template v-for=\"item in items\">\n <tr><td>{{item.line1}}</td></tr>\n <tr><td>{{item.line2}}</td></tr>\n </template>\n</table>\n tbody" }, { "answer_id": 74491285, "author": "Steven Spungin", "author_id": 5093961, "author_profile": "https://Stackoverflow.com/users/5093961", "pm_score": 0, "selected": false, "text": "td <table>\n <tr v-for=\"item in items\">\n <td>\n {{item.line1}} <br />\n {{item.line2}}\n </td>\n </tr>\n </table>\n <table>\n <tr v-for=\"item in items\">\n <td>\n <div>{{item.line1}}</div>\n <div>{{item.line2}}</div>\n </td>\n </tr>\n </table>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246383/" ]
74,490,814
<p>how can i replace columns with those in transact sql? I only have this code this way. I could do it directly in sms but I don't understand some things in this code so I prefer to do it directly in transact to be safer. For example I can make an Id column with int but I don't understand the &quot;Identity&quot; and (1,1)... the get date I have to put it where... so here it is Thanks</p> <pre><code> [Id] INT IDENTITY (1, 1) NOT NULL, [DateCreated] DATETIMEOFFSET NOT NULL DEFAULT (getdate()), </code></pre>
[ { "answer_id": 74491108, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 0, "selected": false, "text": "(1,1) NOT NULL" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19989353/" ]
74,490,832
<p>I am trying to connect database in sql server 2014 with php as follows:</p> <p>First I have this script in conexaosql.php:</p> <pre><code>class Conexao { private static $connection; private function __construct(){} public static function getConnection() { $pdoConfig = DB_DRIVER . &quot;:&quot;. &quot;Server=&quot; . DB_HOST . &quot;;&quot;; $pdoConfig .= &quot;Database=&quot;.DB_NAME.&quot;;&quot;; try { if(!isset($connection)){ $connection = new PDO($pdoConfig, DB_USER, DB_PASSWORD); $connection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return $connection; } catch (PDOException $e) { $mensagem = &quot;Drivers disponiveis: &quot; . implode(&quot;,&quot;, PDO::getAvailableDrivers()); $mensagem .= &quot;\nErro: &quot; . $e-&gt;getMessage(); throw new Exception($mensagem); } } } </code></pre> <p>Then I call this script and I have the following code:</p> <pre><code>define('DB_HOST' , &quot;xxxx&quot;); define('DB_USER' , &quot;xxxx&quot;); define('DB_PASSWORD' , &quot;xxxx&quot;); define('DB_NAME' , &quot;xxxx&quot;); define('DB_DRIVER' , &quot;sqlsrv&quot;); require (&quot;conexaosql.php&quot;); try{ $Conexao = Conexao::getConnection(); $query = $Conexao-&gt;query(&quot;SELECT Pago FROM UTE02.dbo.Recibos&quot;); $produtos = $query-&gt;fetchAll(); }catch(Exception $e){ echo $e-&gt;getMessage(); exit; } </code></pre> <p>I get the following error when I run the code:</p> <blockquote> <p>mysql,sqlite Erro: could not find driver</p> </blockquote> <p>I'm using php 8.1 and apache. I leave the <a href="https://www.canva.com/design/DAFSTZattHo/Yg8zuJvrzPtZ3jhvH9-Xlw/view?utm_content=DAFSTZattHo&amp;utm_campaign=designshare&amp;utm_medium=link&amp;utm_source=publishsharelink" rel="nofollow noreferrer">link </a> with images from phpinfo()</p>
[ { "answer_id": 74513242, "author": "Anónimo", "author_id": 20379006, "author_profile": "https://Stackoverflow.com/users/20379006", "pm_score": 2, "selected": true, "text": "# Microsoft ODBC 17\nsudo su\ncurl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\n\n#Download appropriate package for the OS version - Ubuntu 18.04\ncurl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list\nexit\nsudo apt-get update\nsudo ACCEPT_EULA=Y apt-get install msodbcsql17\n\n# optional: for bcp and sqlcmd\nsudo ACCEPT_EULA=Y apt-get install mssql-tools\necho 'export PATH=\"$PATH:/opt/mssql-tools/bin\"' >> ~/.bash_profile\necho 'export PATH=\"$PATH:/opt/mssql-tools/bin\"' >> ~/.bashrc\nsource ~/.bashrc\n# optional: for unixODBC development headers\nsudo apt-get install unixodbc-dev\n\n# Microsoft ODBC 17\n# 8.1\nsudo apt-get -y install php-pear php8.1-dev\nsudo update-alternatives --set php /usr/bin/php8.1\nsudo update-alternatives --set phar /usr/bin/phar8.1\nsudo update-alternatives --set phar.phar /usr/bin/phar.phar8.1\nsudo update-alternatives --set phpize /usr/bin/phpize8.1\nsudo update-alternatives --set php-config /usr/bin/php-config8.1\n\nsudo pecl uninstall -r sqlsrv \nsudo pecl uninstall -r pdo_sqlsrv \nsudo pecl -d php_suffix=8.1 install sqlsrv\nsudo pecl -d php_suffix=8.1 install pdo_sqlsrv\nsudo su\nprintf \"; priority=20\\nextension=sqlsrv.so\\n\" > /etc/php/8.1/mods-available/sqlsrv.ini\nprintf \"; priority=30\\nextension=pdo_sqlsrv.so\\n\" > /etc/php/8.1/mods-available/pdo_sqlsrv.ini\nexit\nsudo phpenmod -v 8.1 sqlsrv pdo_sqlsrv\nsudo service apache2 restart\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20379006/" ]
74,490,843
<p>I have data as follows:</p> <pre><code>library(data.table) dat &lt;- fread(&quot;id var 1 thisstring 2 otherstring 3 notthisone&quot;) </code></pre> <p>I am trying to get a vector of all strings in column <code>var</code> that contain <code>string</code>.</p> <p>If I do:</p> <pre><code>grepl(&quot;string&quot;, dat$var) </code></pre> <p>I get:</p> <pre><code>[1] TRUE TRUE FALSE </code></pre> <p>What I want to get is:</p> <pre><code>matches &lt;- c(&quot;thisstring&quot;, &quot;otherstring&quot;) </code></pre> <p>How should I do this?</p>
[ { "answer_id": 74490876, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 4, "selected": true, "text": "value = TRUE grep grep(\"string\", dat$var, value = TRUE)\n#[1] \"thisstring\" \"otherstring\"\n" }, { "answer_id": 74490900, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 3, "selected": false, "text": "dat[grepl(\"string\",var),var]\n [1] \"thisstring\" \"otherstring\"\n" }, { "answer_id": 74490970, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 2, "selected": false, "text": "%like% library(data.table)\ndat <- fread(\"id var\n 1 thisstring\n 2 otherstring\n 3 notthisone\")\n\ndat$var[dat$var %like% 'string']\n#> [1] \"thisstring\" \"otherstring\"\n" }, { "answer_id": 74493248, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "str_subset library(stringr)\nstr_subset(dat$var, \"string\")\n[1] \"thisstring\" \"otherstring\"\n" }, { "answer_id": 74493740, "author": "Chris", "author_id": 794450, "author_profile": "https://Stackoverflow.com/users/794450", "pm_score": 0, "selected": false, "text": "dat$var[which(grepl('string', dat$var) == TRUE)] \n[1] \"thisstring\" \"otherstring\"\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071608/" ]
74,490,863
<p>** <strong>Updated with nitro plugin approach</strong> **</p> <p>I'm using <code>Playwright</code> server-side to get some data from a page that I want to use in my frontend, this the setup using nitro plugin</p> <ul> <li><p>Base Project Structure</p> <pre><code>pages index.vue server db index.js plugins playwright.js routes playwright.js ... </code></pre> </li> <li><p><code>server/db/index.js</code></p> <pre class="lang-js prettyprint-override"><code>export const db = []; </code></pre> </li> <li><p><code>server/routes/playwright.js</code></p> <pre class="lang-js prettyprint-override"><code>import { db } from '../db'; export default defineEventHandler(() =&gt; db); </code></pre> </li> <li><p><code>server/plugins/playwright.js</code></p> <pre class="lang-js prettyprint-override"><code>import { chromium } from 'playwright'; export default defineNitroPlugin(async () =&gt; { const browser = await chromium.launch(); // ... // some operations goes here // and some console logs for tracking progress // ... db.push(results); // results is the scraped data }); </code></pre> </li> </ul> <p>On running <code>nuxt dev</code>, the script in <code>plugins/playwright</code> starts, opens the browser, scrape the data and store it to <code>db</code> <strong>with all my <code>console.log</code> logged to the terminal (this is different in prod)</strong>.</p> <p>When I open local host I get the index page with the fetched data from db with no errors.</p> <p>However on running <code>nuxt generate</code> the CLI runs as usual and I see <strong>only some of the console.logs</strong> printed to terminal as following</p> <pre class="lang-js prettyprint-override"><code>yarn run v1.22.19 $ nuxt generate Nuxi 3.0.0 Nuxt 3.0.0 with Nitro 1.0.0 WARN Using experimental payload extraction for full-static output. You can opt-out by setting experimental.payloadExtraction to false. i Client built in 1666ms i Building server... √ Server built in 581ms √ Generated public .output/public i Initializing prerenderer Starting Playwright server plugin ⚙️ Read User-specifed options Initiating a new page // There are more console.logs than these three i Prerendering 3 initial routes with crawler ├─ / (290ms) ├─ /200.html (3ms) ├─ /404.html (5ms) ├─ /_payload.js (2ms) √ You can now deploy .output/public to any static hosting! Done in 6.21s. * Terminal will be reused by tasks, press any key to close it. </code></pre> <p>On running <code>nuxt preview</code> and openning local host I get the index page with a an empty array (the initial value for <code>db</code>)</p> <p>Do I need to somehow force the <code>generate</code> command to wait until the nitro plugin finish executing? and how can I do that?</p>
[ { "answer_id": 74490942, "author": "Adem kriouane", "author_id": 20320091, "author_profile": "https://Stackoverflow.com/users/20320091", "pm_score": 1, "selected": false, "text": "export default (nuxtConfig) => ({\n ready: () => {\n // Execute your code here\n }\n});\n import hooks from './hooks/hooks';\nexport default {\n // Other stuff\n hooks: hooks(this),\n // Other stuff\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17700794/" ]
74,490,870
<p>So I understand the basics of java programming but when I'm trying to use my little knowledge in android studio it make everything harder having classes and different files needing to be referenced. Coming from python, when making a simple game I would define different functions, then run them in a game loop like</p> <pre><code>while running: </code></pre> <p>or something similar. I know to define something in java you go like</p> <pre><code>public void Example() {} </code></pre> <p>but when I use this in java, when I try to run the program my game either instantly crashes or doesnt load anything.</p> <p>The code at the moment is</p> <pre><code>public class MainActivity extends AppCompatActivity { //Variables Boolean running = true; public int years = 0; //Setup Year Counter TextView textView = (TextView) findViewById(R.id.year_counter); //Advance Button public void advance() { ImageButton button = (ImageButton) findViewById(R.id.advance); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { years += 1; textView.setText(&quot;&quot; + years + &quot;&quot;); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Game Loop while (running) { advance(); } } } </code></pre> <p>And this results in the app not opening. Any help at all would mean a lot to me. Thanks in advance :)</p>
[ { "answer_id": 74490942, "author": "Adem kriouane", "author_id": 20320091, "author_profile": "https://Stackoverflow.com/users/20320091", "pm_score": 1, "selected": false, "text": "export default (nuxtConfig) => ({\n ready: () => {\n // Execute your code here\n }\n});\n import hooks from './hooks/hooks';\nexport default {\n // Other stuff\n hooks: hooks(this),\n // Other stuff\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20523271/" ]
74,490,925
<p>Why referring to a pointer to a derived class that has not yet been created is valid, but not undefined behavior. <a href="https://godbolt.org/z/zv38Gc4ar" rel="nofollow noreferrer">godbolt.org</a></p> <pre><code> #include &lt;iostream&gt; struct A{ int a; void foo() { std::cout &lt;&lt; &quot;A = &quot; &lt;&lt; a &lt;&lt; std::endl; } }; struct B : public A{ int b; void foo() { std::cout &lt;&lt; &quot;B = &quot; &lt;&lt; b &lt;&lt; std::endl; } }; int main() { A *a = new A(); B *b = static_cast&lt;B*&gt;(a); a-&gt;foo(); // cout A = 0 b-&gt;foo(); // cout B = 0 b-&gt;b = 333; b-&gt;foo(); // cout B = 333 a-&gt;foo(); // cout A = 0 } </code></pre> <p>Should a pointer to a derived class be undefined?</p>
[ { "answer_id": 74490993, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 3, "selected": false, "text": "static_cast B *b = static_cast<B*>(a);" }, { "answer_id": 74491133, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 2, "selected": true, "text": "-O3 -Werror -Wall <source>: In function 'int main()':\n<source>:25:8: error: array subscript 'B[0]' is partly outside array bounds of 'unsigned char [4]' [-Werror=array-bounds]\n 25 | b->b = 333;\n | ~~~^\n<source>:19:18: note: object of size 4 allocated by 'operator new'\n 19 | A *a = new A();\n | ^\ncc1plus: all warnings being treated as errors\n unsigned char [4] B A \n B\n A B A 4 b->b b A B B b B \"Hello World\"" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453711/" ]
74,490,937
<p>I have this Dataframe that I want to get all possible combinations of this dataframe across both rows and columns.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A_Points</th> <th>B_Points</th> <th>C_Points</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> <td>1</td> </tr> <tr> <td>3</td> <td>5</td> <td>4</td> </tr> <tr> <td>9</td> <td>2</td> <td>4</td> </tr> </tbody> </table> </div> <p>For example a combination as follows Points = 0 + 5 + 4, or 9 + 1 + 1. Is there a builtin tool for such problem?</p> <p>This is what I tried, but it did not give the desired output.</p> <pre><code>&gt; import itertools &gt; combined_dataframe = pd.DataFrame({'{}{}'.format(a, b): possible_feature_characteristicpoints[a] - possible_feature_characteristicpoints[b] for a, b in itertools.combinations(possible_feature_characteristicpoints.columns, 2)}) </code></pre>
[ { "answer_id": 74490993, "author": "user17732522", "author_id": 17732522, "author_profile": "https://Stackoverflow.com/users/17732522", "pm_score": 3, "selected": false, "text": "static_cast B *b = static_cast<B*>(a);" }, { "answer_id": 74491133, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 2, "selected": true, "text": "-O3 -Werror -Wall <source>: In function 'int main()':\n<source>:25:8: error: array subscript 'B[0]' is partly outside array bounds of 'unsigned char [4]' [-Werror=array-bounds]\n 25 | b->b = 333;\n | ~~~^\n<source>:19:18: note: object of size 4 allocated by 'operator new'\n 19 | A *a = new A();\n | ^\ncc1plus: all warnings being treated as errors\n unsigned char [4] B A \n B\n A B A 4 b->b b A B B b B \"Hello World\"" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540224/" ]
74,490,941
<p>I have 3 different Accordions that a single state controls their open and close state like so:</p> <pre><code> const [accordionOpen, setAccordionOpen] = useState({ countryOfOriginAccordion: true, schoolAccordion: false, areaOfStudyAccordion: false, }); </code></pre> <p>ideally, I am setting each state with their own function like this:</p> <pre><code>setAccordionOpen((previousState) =&gt; ({ ...previousState, schoolAccordion: !accordionOpen.schoolAccordion, })) </code></pre> <p>I want to use a single function that changes this value in state dynamically:</p>
[ { "answer_id": 74490972, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 0, "selected": false, "text": "const setValue = (key:string, value:string) => {\n setAccordionOpen((previousState) => ({\n ...previousState,\n [key]: value,\n }))\n}\n setValue( 'schoolAccordion', !accordionOpen.schoolAccordion)\n" }, { "answer_id": 74491120, "author": "Wani", "author_id": 9608615, "author_profile": "https://Stackoverflow.com/users/9608615", "pm_score": 3, "selected": true, "text": "const toggleAccordionOpen = (accordionName) => setAccordionOpen((prevState) => ({\n ...prevState,\n [accordionName]: !prevState[accordionName],\n}));\n\n// Example of usage\ntoggleAccordionOpen('countryOfOriginAccordion');\n accordionName const ACCORDION_NAMES = {\n COUNTRY_OF_ORIGIN: 'countryOfOriginAccordion',\n SCHOOL: 'schoolAccordion',\n AREA_OF_STUDY: 'areaOfStudyAccordion',\n} as const;\n\ntype AccordionNameGeneric<T> = T[keyof T];\ntype AccordionName = AccordionNameGeneric<typeof ACCORDION_NAMES>;\n\nconst toggleAccordionOpen = (accordionName: AccordionName) => \n...\n toggleAccordionOpen(ACCORDION_NAMES.COUNTRY_OF_ORIGIN);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9806667/" ]
74,490,953
<p>I am working on a Shopify store where there are multiple divs like below:</p> <pre><code>&lt;div class=&quot;options-selection__option-values&quot; data-variant-option=&quot;&quot; data-variant-option-index=&quot;0&quot; data-variant-option-chosen-value=&quot;One&quot;&gt;&lt;/div&gt; &lt;div class=&quot;options-selection__option-values&quot; data-variant-option=&quot;&quot; data-variant-option-index=&quot;0&quot; data-variant-option-chosen-value=&quot;Two&quot;&gt; &lt;div class=&quot;options-selection__option-values&quot; data-variant-option=&quot;&quot; data-variant-option-index=&quot;0&quot; data-variant-option-chosen-value=&quot;Three&quot;&gt; &lt;div class=&quot;options-selection__option-values&quot; data-variant-option=&quot;&quot; data-variant-option-index=&quot;0&quot; data-variant-option-chosen-value=&quot;Four&quot;&gt; </code></pre> <p>I want to get the value of custom attribute <code>data-variant-option-chosen-value</code>and print that into <code>&lt;span class=&quot;selected-variant&quot;&gt;&lt;/span&gt;</code></p> <p>I tried reading the custom attribute value by following jQuery without any success</p> <pre><code>$(document).ready(function() { $('.options-selection__option-values').each(function() { console.log($(this).attr('data-variant-option-chosen-value')); }); </code></pre>
[ { "answer_id": 74491038, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 0, "selected": false, "text": "Uncaught SyntaxError: Unexpected end of input\" $(document).ready(function() {\n\n$('.options-selection__option-values').each(function() {\n console.log($(this).attr('data-variant-option-chosen-value'));\n});\n})\n" }, { "answer_id": 74491040, "author": "Nitheesh", "author_id": 6099327, "author_profile": "https://Stackoverflow.com/users/6099327", "pm_score": 2, "selected": true, "text": "$(this).attr(\"data-variant-option-chosen-value\") $(document).ready(function () { $(document).ready(function () {\n let val = ''\n $(\".options-selection__option-values\").each(function () {\n val += $(this).attr(\"data-variant-option-chosen-value\");\n });\n $(\".selected-variant\").text(val)\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n<span class=\"selected-variant\"></span>\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"One\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Two\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Three\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Four\"\n></div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74490953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4803789/" ]
74,491,025
<p>I've been trying to get the first block of this accordion to open by default but haven't been able to. All of the examples I see are in jQuery and the code looks slightly different. Any and all help is appreciated. This is for a report I'm building.</p> <p>[Here is the code.][1]</p> <p><a href="https://jsfiddle.net/infotech2/dc5k74em/3/" rel="nofollow noreferrer">https://jsfiddle.net/infotech2/dc5k74em/3/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>(function () { //script parameters const id="myAccordion1" const w="500px" const multiselect = true; var el = document.getElementById(id); el.className='container' //var tmp = [...el.cloneNode(true).children]; //el.innerHTML="" tmp = [...el.children] tmp.forEach((e,i) =&gt; { let p = document.createElement('p'); p.className="accordion_item" if(i%2==0){//titles dt = document.createElement('dt') dt.className="accordion__heading" btn = document.createElement("button") btn.className="accordion__trigger" btn.appendChild(e) dt.appendChild(btn) el.appendChild(dt) }else{//contents e.className="accordion__panel" p.appendChild(e) el.appendChild(e) } }) //accordion stuff const headings = el.querySelectorAll(".accordion__heading"); const triggers = []; const accordionContents = document.querySelectorAll(".accordion__panel"); const copyOpenClass = "accordion__panel--open"; headings.forEach((h, i) =&gt; { let btn = h.querySelector("button"); triggers.push(btn); let target = h.nextElementSibling; btn.onclick = () =&gt; { let expanded = btn.getAttribute("aria-expanded") === "true"; if (expanded) { closeItem(target, btn); } else { openItem(target, btn); } }; }); function closeAllExpandedItems() { const expandedTriggers = triggers.filter( (t) =&gt; t.getAttribute("aria-expanded") === "true" ); const expandedCopy = Array.from(accordionContents).filter((c) =&gt; c.classList.value.includes(copyOpenClass) ); expandedTriggers.forEach((trigger) =&gt; { trigger.setAttribute("aria-expanded", false); }); expandedCopy.forEach((copy) =&gt; { copy.classList.remove(copyOpenClass); copy.style.maxHeight = 0; copy.style.padding = "0 1.5rem 0 1.5rem"; }); } function closeItem(target, btn) { if (!multiselect) { closeAllExpandedItems(); } else { btn.setAttribute("aria-expanded", false); target.classList.remove(copyOpenClass); target.style.maxHeight = 0; target.style.padding = "0 1.5rem 0 1.5rem"; } } function openItem(target, btn) { if (!multiselect) { closeAllExpandedItems(); } btn.setAttribute("aria-expanded", true); target.classList.add(copyOpenClass); target.style.maxHeight = target.scrollHeight + "px"; target.style.padding = "1rem 1.5rem 2rem 1.5rem"; } //setTimeout(() =&gt; triggers[0].click(), 750); })();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>//accordion look and feel css=`&lt;style&gt; dt.accordion__heading { font-size: .75rem; font-weight: normal; line-height: 1; margin: 0; padding: 0; } .accordion__item{ margin:0 !important; } .container { max-width: ${w}; Xmargin: 0 auto; background: transparent; } .accordion { width: 100%; background: #fff; border: 1px solid RGB(45,132,219); text-align: left; } .accordion__trigger { -webkit-appearance: none; -moz-appearance: none; appearance: none; font-size: inherit; /* text-transform: uppercase; */ letter-spacing: 2px; padding: 1rem 1.5rem; background: RGB(62,142,222); color: white; cursor: pointer; transition: 0.3s ease; border: 0 none; border-bottom: 1px solid RGB(45,132,219); width: 100%; text-align: left; margin: 0; position: relative; } .accordion__trigger::after { content: ""; position: absolute; right: 20px; top: calc(50% - 5px); width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-top: 10px solid #fff; /*arrow*/ transform: rotate(0deg); transform-origin: center; transition: transform 0.5s; } .accordion__trigger[aria-expanded="true"]::after { transform: rotate(-180deg); } .accordion__trigger:hover, .accordion__trigger:focus { background: RGB(35,122,210); } .accordion__panel { overflow: hidden; padding: 0 1.5rem 0 1.5rem; line-height: 1.6; font-size: 1rem; font-weight: 500; max-height: 0; border-right:1px solid RGB(35,122,210); border-left:1px solid RGB(35,122,210); visibility: hidden; transition: visibility 0.5s, padding 0.5s, max-height 0.5s; } .accordion__panel--open { visibility: visible; border-bottom:1px solid RGB(35,122,210); } &lt;/style&gt;`</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;FONT size=2&gt; &lt;P&gt;&lt;SpotfireControl id="aaa37ff537bc4cf1977755f7b80e0a40" /&gt;&lt;/P&gt; &lt;div id='myAccordion1'&gt; &lt;b&gt;Controls&lt;/b&gt; &lt;DIV&gt; &lt;P&gt;&lt;U&gt;Date Slider&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="b66eca7e1cff4295bf614b37f089546b" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Total / Daily Avg&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="882e441cd33847129f5179fe544a7d8e" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Gross / Net&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="788a04c90b30490ebca9ef58b2c13da9" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Deferred &lt;EM&gt;BOE&lt;/EM&gt; / &lt;EM&gt;Oil&lt;/EM&gt; / &lt;EM&gt;Gas&lt;/EM&gt; / &lt;EM&gt;NGL&lt;/EM&gt;&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="b4d4c03dcd924eacb02614e5954aa93c" /&gt;&lt;/P&gt; &lt;P&gt;&lt;FONT color=#239e58&gt;&lt;U&gt;Hide Deferred for DT Types&lt;/U&gt;&lt;/FONT&gt;&lt;/P&gt; &lt;P&gt;&lt;FONT color=#239e58&gt;&lt;SpotfireControl id="a0feb88eaa184527a3df20956c9e2291" /&gt;&lt;/FONT&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Report Data Up Through&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="cea1851e80024190a7539d6e7bb5f33b" /&gt;&lt;/P&gt; &lt;/div&gt; &lt;b&gt;Filters (Main)&lt;/b&gt; &lt;DIV&gt; &lt;P&gt;&lt;U&gt;Date&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="c0b5976e75c841208ff40023cbfadd5e" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Formation&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="dfcf0dd748214ce39178edb65d687690" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Well&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="b8b08ecd1e9a42cfaaf4e1bda015f3a6" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Pad&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="9419ac81214d40769813b93d54aeec9a" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Route&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="7be74d9d54674b6ea6b248e15e627881" /&gt;&lt;/P&gt; &lt;/DIV&gt; &lt;b&gt;Filters (Downtime)&lt;/b&gt; &lt;DIV&gt; &lt;P&gt;&lt;U&gt;Primary DT Reason&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="bdb60a369a8a4c8e94ac647f3c72807c" /&gt;&lt;/P&gt; &lt;P&gt;&lt;U&gt;Secondary DT Reason&lt;/U&gt;&lt;/P&gt; &lt;P&gt;&lt;SpotfireControl id="267f49d05e9b47c7909b203d76714e69" /&gt;&lt;/P&gt; &lt;/DIV&gt; &lt;/DIV&gt; &lt;/FONT&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74491038, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 0, "selected": false, "text": "Uncaught SyntaxError: Unexpected end of input\" $(document).ready(function() {\n\n$('.options-selection__option-values').each(function() {\n console.log($(this).attr('data-variant-option-chosen-value'));\n});\n})\n" }, { "answer_id": 74491040, "author": "Nitheesh", "author_id": 6099327, "author_profile": "https://Stackoverflow.com/users/6099327", "pm_score": 2, "selected": true, "text": "$(this).attr(\"data-variant-option-chosen-value\") $(document).ready(function () { $(document).ready(function () {\n let val = ''\n $(\".options-selection__option-values\").each(function () {\n val += $(this).attr(\"data-variant-option-chosen-value\");\n });\n $(\".selected-variant\").text(val)\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n<span class=\"selected-variant\"></span>\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"One\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Two\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Three\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Four\"\n></div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341569/" ]
74,491,059
<p>I currently have Azure Data Factory on Prod. It is already functional and has pipelines, Linked Services etc.</p> <p>Now I want to deploy Develop, have built Deplyoment pipelines and am able to move Prod to Dev.</p> <p>However, I need to make a few changes to make Dev work, e.g. I need to adjust parameters of Linked Service so that it accesses storage/KV on Dev and not on Prod.</p> <p>But if I have developed later on Dev (e.g. new pipeline) and want to move these changes to Prod, of course the parameters of Linked Service are also deployed with PR on prod.</p> <p>This means that I then have Linked Service on both Dev and Prod and both access Dev.</p> <p>Example:</p> <pre><code>PR Dev to Prod, wants to change - https://prdtestkv.vault.azure.net --&gt; https://devtestkv.vault.azure.net Then Prod linked service KV is the same as on Dev --&gt; https://devtestkv.vault.azure.net </code></pre> <p>is it possible to exclude these changes during PR from Dev to Prod? So that I can only merge other changes? Thanks!</p>
[ { "answer_id": 74491038, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 0, "selected": false, "text": "Uncaught SyntaxError: Unexpected end of input\" $(document).ready(function() {\n\n$('.options-selection__option-values').each(function() {\n console.log($(this).attr('data-variant-option-chosen-value'));\n});\n})\n" }, { "answer_id": 74491040, "author": "Nitheesh", "author_id": 6099327, "author_profile": "https://Stackoverflow.com/users/6099327", "pm_score": 2, "selected": true, "text": "$(this).attr(\"data-variant-option-chosen-value\") $(document).ready(function () { $(document).ready(function () {\n let val = ''\n $(\".options-selection__option-values\").each(function () {\n val += $(this).attr(\"data-variant-option-chosen-value\");\n });\n $(\".selected-variant\").text(val)\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n<span class=\"selected-variant\"></span>\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"One\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Two\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Three\"\n></div>\n\n<div\n class=\"options-selection__option-values\"\n data-variant-option=\"\"\n data-variant-option-index=\"0\"\n data-variant-option-chosen-value=\"Four\"\n></div>" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14789035/" ]
74,491,090
<p>I have a dataframe which was originally a survey where people could answer their dog breeds and their favorit dog breed. Obviously each person can have multiple answers which will be displayed in the same categorie but separated with a comma. However I can't figure out how to count the number of times each breed was mensionned for their respective category.</p> <p>here is the code:</p> <pre><code>dogs_owned &lt;-c(&quot;labrador, golden&quot;, &quot;golden&quot;,&quot;pitbull, chihuahua&quot;) dogs_fav &lt;- c(&quot;beagle&quot;, &quot;labrador, shepherd&quot;, &quot;chihuahua, pitbull&quot;) test &lt;- data.frame(dogs_owned,dogs_fav) list &lt;- c(&quot;labrador&quot;, &quot;golden&quot;,&quot;pitbull&quot;,&quot;chihuahua&quot;,&quot;beagle&quot;,&quot;shepherd&quot;) list_test &lt;- data.frame(list) list_test$count_own &lt;- 0 list_test$count_fav &lt;- 0 </code></pre> <p>The goal is to count how many times the name of each breed of dog appear in either dogs_owned and dogs_fav in their respective list count</p>
[ { "answer_id": 74491141, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "strsplit table > (owned <- as.data.frame(table(trimws(unlist(strsplit(test$dogs_owned, split=\",\"))))))\n Var1 Freq\n1 chihuahua 1\n2 golden 2\n3 labrador 1\n4 pitbull 1\n> (fav <- as.data.frame(table(trimws(unlist(strsplit(test$dogs_fav, split=\",\"))))))\n Var1 Freq\n1 beagle 1\n2 chihuahua 1\n3 labrador 1\n4 pitbull 1\n5 shepherd 1\n full_join merge > library(dplyr)\n owned %>% \n full_join(fav, by=\"Var1\") %>% \n rename(Owned = Freq.x,\n Fav = Freq.y)\n Var1 Owned Fav\n1 chihuahua 1 1\n2 golden 2 NA\n3 labrador 1 1\n4 pitbull 1 1\n5 beagle NA 1\n6 shepherd NA 1\n" }, { "answer_id": 74491217, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": true, "text": "out <- Reduce(function(a, b) merge(a, b, by=\"Var1\", all=TRUE),\n lapply(test,\n function(z) as.data.frame.table(table(unlist(strsplit(z, \"[ ,]+\"))), \n stringsAsFactors=FALSE)))\nnames(out)[-1] <- names(test)\nout\n# Var1 dogs_owned dogs_fav\n# 1 beagle NA 1\n# 2 chihuahua 1 1\n# 3 golden 2 NA\n# 4 labrador 1 1\n# 5 pitbull 1 1\n# 6 shepherd NA 1\n strsplit(z, \"[ ,]+\") trimws strsplit(test$dogs_fav, \"[ ,]+\")\n# [[1]]\n# [1] \"beagle\"\n# [[2]]\n# [1] \"labrador\" \"shepherd\"\n# [[3]]\n# [1] \"chihuahua\" \"pitbull\" \n table(unlist(.)) table(unlist(strsplit(test$dogs_fav, \"[ ,]+\")))\n# beagle chihuahua labrador pitbull shepherd \n# 1 1 1 1 1 \n as.data.frame.table(.) Var1 Freq merge(a, b, by=\"Var1\", ...) Var1 Freq all=TRUE Reduce dogs_*" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19749748/" ]
74,491,128
<p>I have a dataframe &quot;data&quot; that contains</p> <ul> <li>employee ID (&quot;CPNo&quot;) - int</li> <li>Gender - factor</li> <li>Job Role - factor</li> <li>Country - factor</li> <li>Annual Salary - int</li> </ul> <p>I want to run a t-test for each job role in each country to see if there is a significant paygap between the genders in the same job role and country.</p> <p>I create a nested dataframe which contains dataframes with at least 20 observations:</p> <pre><code>dataNested &lt;- data %&gt;% select(CPNo, Gender, JobRole, Country, AnnualSalaryLocal) %&gt;% nest(data = c(CPNo, Gender, AnnualSalaryLocal)) %&gt;% filter(map_int(data, nrow) &gt; 20) </code></pre> <p>And I want to run a t-test on that nested dataframe:</p> <pre><code>dataNested %&gt;% mutate(t_test = map(data, ~t.test(.x$AnnualSalaryLocal ~ .x$Gender, var.eq=F, paired=F))) </code></pre> <p>Now, if I run the code I get the following table which is a nested dataframe that contain the results of my t-tests:</p> <pre><code>JobRole &lt;fctr&gt; JobStage &lt;fctr&gt; Country &lt;fctr&gt; data &lt;list&gt; t_test &lt;list&gt; 76 Product Development 06 Ireland &lt;tibble&gt; &lt;S3: htest&gt; 76 Product Development 06 Italy &lt;tibble&gt; &lt;S3: htest&gt; 82 Service Delivery 05 Italy &lt;tibble&gt; &lt;S3: htest&gt; 82 Service Delivery 06 Italy &lt;tibble&gt; &lt;S3: htest&gt; 82 Service Delivery 03 Mexico &lt;tibble&gt; &lt;S3: htest&gt; 83 Supply &amp; Logistics 01 Mexico &lt;tibble&gt; &lt;S3: htest&gt; 76 Product Development 05 Poland &lt;tibble&gt; &lt;S3: htest&gt; </code></pre> <p>How do I write the syntax if I want to add a new variable &quot;sig&quot; which extracts the p.value from my &quot;t_test&quot; variable?</p>
[ { "answer_id": 74491141, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "strsplit table > (owned <- as.data.frame(table(trimws(unlist(strsplit(test$dogs_owned, split=\",\"))))))\n Var1 Freq\n1 chihuahua 1\n2 golden 2\n3 labrador 1\n4 pitbull 1\n> (fav <- as.data.frame(table(trimws(unlist(strsplit(test$dogs_fav, split=\",\"))))))\n Var1 Freq\n1 beagle 1\n2 chihuahua 1\n3 labrador 1\n4 pitbull 1\n5 shepherd 1\n full_join merge > library(dplyr)\n owned %>% \n full_join(fav, by=\"Var1\") %>% \n rename(Owned = Freq.x,\n Fav = Freq.y)\n Var1 Owned Fav\n1 chihuahua 1 1\n2 golden 2 NA\n3 labrador 1 1\n4 pitbull 1 1\n5 beagle NA 1\n6 shepherd NA 1\n" }, { "answer_id": 74491217, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": true, "text": "out <- Reduce(function(a, b) merge(a, b, by=\"Var1\", all=TRUE),\n lapply(test,\n function(z) as.data.frame.table(table(unlist(strsplit(z, \"[ ,]+\"))), \n stringsAsFactors=FALSE)))\nnames(out)[-1] <- names(test)\nout\n# Var1 dogs_owned dogs_fav\n# 1 beagle NA 1\n# 2 chihuahua 1 1\n# 3 golden 2 NA\n# 4 labrador 1 1\n# 5 pitbull 1 1\n# 6 shepherd NA 1\n strsplit(z, \"[ ,]+\") trimws strsplit(test$dogs_fav, \"[ ,]+\")\n# [[1]]\n# [1] \"beagle\"\n# [[2]]\n# [1] \"labrador\" \"shepherd\"\n# [[3]]\n# [1] \"chihuahua\" \"pitbull\" \n table(unlist(.)) table(unlist(strsplit(test$dogs_fav, \"[ ,]+\")))\n# beagle chihuahua labrador pitbull shepherd \n# 1 1 1 1 1 \n as.data.frame.table(.) Var1 Freq merge(a, b, by=\"Var1\", ...) Var1 Freq all=TRUE Reduce dogs_*" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14792431/" ]
74,491,144
<p><code>'[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]'</code></p> <p>I tried using JSON.parse(string) But got Uncaught SyntaxError: Unexpected token 'b', &quot;[b426be49-0&quot;... is not valid JSON</p> <p>I am expecting it to be :</p> <pre><code>[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf] </code></pre> <p>without the strings around it.</p>
[ { "answer_id": 74491202, "author": "muka.gergely", "author_id": 2316540, "author_profile": "https://Stackoverflow.com/users/2316540", "pm_score": 3, "selected": true, "text": "regexp const s = '[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]'\n\nconst splitS = (s) => s.split(/[\\[\\],]/).filter(e => e)\n\nconsole.log(splitS(s))" }, { "answer_id": 74491226, "author": "Mauro Vinicius", "author_id": 12064628, "author_profile": "https://Stackoverflow.com/users/12064628", "pm_score": 0, "selected": false, "text": "Uncaught SyntaxError: Unexpected token 'b', \"[b426be49-0\"... is not valid JSON const myString = '[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]';\n\nconst myStringWithoutBrackets = myString.substring(1, myString.length - 1);\nconst arrayOfStrings = myStringWithoutBrackets.split(',');\n\nconsole.log(arrayOfStrings);\n// Output: ['b426be49-0621-4240-821f-79bddf378e1e', 'c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf']\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13267498/" ]
74,491,161
<p>I have a pandas DataFrame with a column <code>Size</code>, on which I filter first and then group by and count records per group. The result contains also rows for the groups which were filtered out before, but with a count of 0:</p> <pre class="lang-py prettyprint-override"><code>( df[df[&quot;Size&quot;].isin((&quot;XXS&quot;, &quot;XS&quot;, &quot;S&quot;, &quot;M&quot;, &quot;L&quot;, &quot;XL&quot;, &quot;XXL&quot;))] .groupby(&quot;Size&quot;) .agg( count=(&quot;OID&quot;, &quot;count&quot;), ) .sort_values(&quot;count&quot;, ascending=False) ) </code></pre> <p>The result DataFrame is shown in the figure below. In my understanding of the groupby function, the groups which were filtered out (I double checked, they are really not anymore in the dataframe) should no longer occur in the aggregated dataframe. Even copying and resetting the index before grouping by does not change the output.</p> <p>Unfortunately, I was not able to reproduce the issue with a simple example dataframe, so I assume that there is something strange happening. Does anybody have an idea why this could happen?</p> <p><strong>Result dataframe</strong>:</p> <p><a href="https://i.stack.imgur.com/ZTZUL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZTZUL.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74491384, "author": "Coco Kuang", "author_id": 20369539, "author_profile": "https://Stackoverflow.com/users/20369539", "pm_score": -1, "selected": false, "text": "df[df[\"Size\"].isin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])]\n .groupby(\"Size\")\n .agg(\n count=(\"OID\", \"count\"),\n )\n .sort_values(\"count\", ascending=False)\n\n====================================================\nisin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])\n" }, { "answer_id": 74515800, "author": "Yannic", "author_id": 9519322, "author_profile": "https://Stackoverflow.com/users/9519322", "pm_score": 2, "selected": true, "text": "Size >>> df.dtypes\n\nSize category\n...\n\n>>> df[\"Size\"].unique()\n\n['S', 'M', 'L', 'XL', 'XXL', 'XS', 'XXS']\nCategories (80, object): ['100 CM', '105 CM', '24', '25', ..., 'XS/S', 'XXL', 'XXS', 'XXS/XS']\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9519322/" ]
74,491,174
<p>I have a basic MAUI project and I want to set an SVG file as the splash screen.</p> <p>I have tried to modify the csproj file using the code below: </p> <p>As you can see the photo is cropped in a circle <img src="https://i.stack.imgur.com/k6meY.png" /></p> <p>How can I make the splash screen display the entire photo?</p>
[ { "answer_id": 74491384, "author": "Coco Kuang", "author_id": 20369539, "author_profile": "https://Stackoverflow.com/users/20369539", "pm_score": -1, "selected": false, "text": "df[df[\"Size\"].isin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])]\n .groupby(\"Size\")\n .agg(\n count=(\"OID\", \"count\"),\n )\n .sort_values(\"count\", ascending=False)\n\n====================================================\nisin([\"XXS\", \"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\"])\n" }, { "answer_id": 74515800, "author": "Yannic", "author_id": 9519322, "author_profile": "https://Stackoverflow.com/users/9519322", "pm_score": 2, "selected": true, "text": "Size >>> df.dtypes\n\nSize category\n...\n\n>>> df[\"Size\"].unique()\n\n['S', 'M', 'L', 'XL', 'XXL', 'XS', 'XXS']\nCategories (80, object): ['100 CM', '105 CM', '24', '25', ..., 'XS/S', 'XXL', 'XXS', 'XXS/XS']\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16695191/" ]
74,491,184
<p>What I have:</p> <pre><code>string = &quot;string&quot; range_list = list(range(10)) </code></pre> <p>What I want:</p> <pre><code>['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9'] </code></pre> <p>What I usually do:</p> <pre><code>import pandas as pd (string+pd.Series(range_list).astype(str)).tolist() </code></pre> <p>What I would like to do:<br> <em>obtain the same expected output from the same input, without importing libraries nor using loops</em></p> <p>Since there is probably no way to do this complying my requests, any other solution cleaner and/or more performing than mine is well accepted. Thanks in advice.</p>
[ { "answer_id": 74491211, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 1, "selected": false, "text": "[f\"{string}{idx}\" for idx in range_list]\n" }, { "answer_id": 74491274, "author": "Rodimeniya", "author_id": 17565474, "author_profile": "https://Stackoverflow.com/users/17565474", "pm_score": 0, "selected": false, "text": "string = \"string\"\n\nstr_list = [string + str(i) for i in range(10)]\n" }, { "answer_id": 74491532, "author": "Artygo", "author_id": 11547305, "author_profile": "https://Stackoverflow.com/users/11547305", "pm_score": 1, "selected": false, "text": "map def get_string(x):\n return f'string{x}'\n\nlist(map(get_string, range(10)))\n list(map(lambda x: f'string{x}', range(10)))\n list(map(lambda x: f'{string}{x}', range_list))\n" }, { "answer_id": 74493456, "author": "Talha Tayyab", "author_id": 13086128, "author_profile": "https://Stackoverflow.com/users/13086128", "pm_score": 1, "selected": false, "text": "string = \"string\"\nrange_list = list(range(10))\n\nlist(map(lambda x: string + x, np.array(range_list).astype(str)))\n list(map(lambda x: 'string{}'.format(x), range_list))\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11728488/" ]
74,491,196
<p>I have the following data frame called &quot;CNO_2020_Monthly&quot;. I have only 3 months populated on this data frame.</p> <pre><code> Var1 Freq 1 Oct 2020 4 2 Nov 2020 5 3 Dec 2020 6 </code></pre> <p>I want to create a month.name index. For that, I used the code below:</p> <pre><code>CNO_2020_Monthly$MonthInd &lt;- month.name[CNO_2020_Monthly$Var1] </code></pre> <p>The result came like that:</p> <pre><code>structure(list(Var1 = structure(1:3, .Label = c(&quot;Oct 2020&quot;, &quot;Nov 2020&quot;, &quot;Dec 2020&quot;), class = &quot;factor&quot;), Freq = 4:6, MonthInd = c(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;)), row.names = c(NA, -3L), class = &quot;data.frame&quot;) </code></pre> <p>October, November, and december come as &quot;January&quot;, &quot;February&quot;, &quot;March&quot;. Is that any way to create a month.name() based on the contents of the field instead of creating a sequence - meaning, that the month.name for October 2020 will be &quot;october&quot;?</p> <p><em>Additional information</em> I have additional data frames that I will merge with the one above based on the month.name - that is why I don't what to create manyally the month.name index but find a way to do it using logic.</p>
[ { "answer_id": 74491340, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 1, "selected": false, "text": "library(zoo)\nformat(as.yearmon(CNO$Var1), \"%B\")\n## [1] \"October\" \"November\" \"December\"\n month.name[match(substr(CNO$Var1, 1, 3), month.abb)]\n## [1] \"October\" \"November\" \"December\"\n CNO <- structure(list(Var1 = structure(1:3, levels = c(\"Oct 2020\", \"Nov 2020\", \n\"Dec 2020\"), class = \"factor\"), Freq = 4:6), row.names = c(NA, \n-3L), class = \"data.frame\")\n" }, { "answer_id": 74491647, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "lubridate my library(lubridate)\n\ncbind(CNO_2020_Monthly, MonthInd = format(my(CNO_2020_Monthly$Var1), \"%B\"))\n Var1 Freq MonthInd\n1 Oct 2020 4 October\n2 Nov 2020 5 November\n3 Dec 2020 6 December\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16906500/" ]
74,491,204
<p>What is the rusticle way to to represent the an i64 [-9223372036854775808, 9223372036854775807] into the u64 domain [0, 18446744073709551615]. So for example 0 in i64 is 9223372036854775808 in u64.</p> <p>Here is what I have done.</p> <pre><code> let x: i64 = -10; let x_transform = ((x as u64) ^ (1 &lt;&lt; 63)) &amp; (1 &lt;&lt; 63) | (x as u64 &amp; (u64::MAX &gt;&gt; 1)); let x_original = ((x_transform as i64) ^ (1 &lt;&lt; 63)) &amp; (1 &lt;&lt; 63) | (x_transform &amp; (u64::MAX &gt;&gt; 1)) as i64; println!(&quot;x_transform {}&quot;, x_transform); println!(&quot;x_original {} {}&quot;, x_original, x_original == x); </code></pre> <p>yielding</p> <blockquote> <p>x_transform 9223372036854775798</p> </blockquote> <blockquote> <p>x_original -10 true</p> </blockquote> <p>Is there a built in way to do this, because it seems too verbose, and error prone?</p>
[ { "answer_id": 74491364, "author": "Masklinn", "author_id": 8182118, "author_profile": "https://Stackoverflow.com/users/8182118", "pm_score": 1, "selected": false, "text": "let x_transform = u64::from_ne_bytes(x.to_ne_bytes());\nlet x_original = i64::from_ne_bytes(x_transform.to_ne_bytes());\n pub fn convert1(x: i64) -> u64 {\n ((x as u64) ^ (1 << 63)) & (1 << 63) | (x as u64 & (u64::MAX >> 1))\n}\n\npub fn convert3(x: i64) -> u64 {\n // manipulating the bytes in transit requires\n // knowing the MSB, use LE as that's the most\n // commmon by far\n let mut bytes = x.to_le_bytes();\n bytes[7] ^= 0x80;\n u64::from_le_bytes(bytes)\n}\n\npub fn convert4(x: i64) -> u64 {\n u64::from_ne_bytes((x ^ i64::MIN).to_ne_bytes())\n}\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n" }, { "answer_id": 74491572, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 3, "selected": true, "text": "pub fn wrap_to_u64(x: i64) -> u64 {\n (x as u64).wrapping_add(u64::MAX/2 + 1)\n}\npub fn wrap_to_i64(x: u64) -> i64 {\n x.wrapping_sub(u64::MAX/2 + 1) as i64\n}\npub fn to_u64(x: i64) -> u64 {\n ((x as u64) ^ (1 << 63)) & (1 << 63) | (x as u64 & (u64::MAX >> 1))\n}\npub fn to_i64(x: u64) -> i64 {\n ((x as i64) ^ (1 << 63)) & (1 << 63) | (x & (u64::MAX >> 1)) as i64\n}\n example::wrap_to_u64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n\nexample::wrap_to_i64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n\nexample::to_u64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n\nexample::to_i64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19634011/" ]
74,491,205
<p>I'm trying to run a .py file and in the file I have this import</p> <pre><code>from config.wsgi import * import os from django.template.loader import get_template from weasyprint import HTML, CSS from config import settings </code></pre> <p>The whole project works, if I set runserver, the project starts without any problem, but this file does not work. The structure of the project is as follows</p> <pre><code>NombreDelProyecto --app ---config ----__init__.py ----asgi.py ----settings.py ----wsgy.py ----db.py ---core ----general ----login ----user ----archivodetest.py </code></pre> <p>the case as I say the project works, but in the views of the applications that I have been doing to put imports I get in red underlined but as I say it works for example:</p> <pre><code>from core.general.forms import ActividadForm </code></pre> <p>That comes out in red, if I put in front of the core, app.core as follows</p> <pre><code>from app.core.general.forms import ActividadForm </code></pre> <p>it does not show red but the project does not work and I get the following error</p> <pre><code>from app.core.general.forms import ActividadForm ModuleNotFoundError: No module named 'app' </code></pre> <p>I understand that it is the routes or something I did wrong from the beginning, please could someone help me.</p> <p>Thank you very much.</p> <p>I tried adding the route, changing the app's route in settings, but to no avail.</p>
[ { "answer_id": 74491364, "author": "Masklinn", "author_id": 8182118, "author_profile": "https://Stackoverflow.com/users/8182118", "pm_score": 1, "selected": false, "text": "let x_transform = u64::from_ne_bytes(x.to_ne_bytes());\nlet x_original = i64::from_ne_bytes(x_transform.to_ne_bytes());\n pub fn convert1(x: i64) -> u64 {\n ((x as u64) ^ (1 << 63)) & (1 << 63) | (x as u64 & (u64::MAX >> 1))\n}\n\npub fn convert3(x: i64) -> u64 {\n // manipulating the bytes in transit requires\n // knowing the MSB, use LE as that's the most\n // commmon by far\n let mut bytes = x.to_le_bytes();\n bytes[7] ^= 0x80;\n u64::from_le_bytes(bytes)\n}\n\npub fn convert4(x: i64) -> u64 {\n u64::from_ne_bytes((x ^ i64::MIN).to_ne_bytes())\n}\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n" }, { "answer_id": 74491572, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 3, "selected": true, "text": "pub fn wrap_to_u64(x: i64) -> u64 {\n (x as u64).wrapping_add(u64::MAX/2 + 1)\n}\npub fn wrap_to_i64(x: u64) -> i64 {\n x.wrapping_sub(u64::MAX/2 + 1) as i64\n}\npub fn to_u64(x: i64) -> u64 {\n ((x as u64) ^ (1 << 63)) & (1 << 63) | (x as u64 & (u64::MAX >> 1))\n}\npub fn to_i64(x: u64) -> i64 {\n ((x as i64) ^ (1 << 63)) & (1 << 63) | (x & (u64::MAX >> 1)) as i64\n}\n example::wrap_to_u64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n\nexample::wrap_to_i64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n\nexample::to_u64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n\nexample::to_i64:\n movabs rax, -9223372036854775808\n xor rax, rdi\n ret\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20447571/" ]
74,491,231
<p>I display some events with current date and how many days left. The first span of days-left has opacity 0. I want when I hover on the second span (tour-date) then change opacity 1 for the first span (days-left).</p> <p>I can solve this with eventlistener or jQuery but before I do it I want to know if there option with 2-3 lines in the CSS.</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>.days-left { position: absolute; left: 21%; background-color: black; height: 3%; color: white; border-radius: 10%; font-weight: bold; opacity: 1; } .tour-row :nth-child(2):hover&gt; :nth-child(1) { opacity: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div className="tour-row"&gt; &lt;span className='days-left'&gt;{`daysLeft : ${currentTourInArray.daysLeft}`}&lt;/span&gt; &lt;span className="tour-item tour-date "&gt;{currentTourInArray.date}&lt;/span&gt; &lt;span className="tour-item tour-city"&gt;{currentTourInArray.city}&lt;/span&gt; &lt;span className="tour-item tour-arena"&gt;{currentTourInArray.arena}&lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74491255, "author": "Nuro007", "author_id": 19669556, "author_profile": "https://Stackoverflow.com/users/19669556", "pm_score": 1, "selected": false, "text": ":hover transition \n.days-left {\n opacity: 0;\n transition: opacity 0.5s;\n}\n\n.days-left:hover {\n opacity: 1;\n}\n\n" }, { "answer_id": 74491327, "author": "Aldo Nezha", "author_id": 20476656, "author_profile": "https://Stackoverflow.com/users/20476656", "pm_score": 0, "selected": false, "text": ".tour-row .towr-date:hover .days-left { opacity: 1 }" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15906386/" ]
74,491,234
<p>I am trying to create a uri, but for some reason is the path being decoded everytime, causing problems with my browser trying to access the page the uri build?</p> <p>POC:</p> <pre><code>using System; public class Program { public static void Main() { Console.WriteLine(&quot;Hello World&quot;); var newLocation = new UriBuilder() { Scheme = Uri.UriSchemeHttps, Host = &quot;localhost&quot;, Path = &quot;/WebResource.axd?d=0&quot; }.Uri; Console.WriteLine($&quot;Hello World {newLocation}&quot;); } } </code></pre> <p>This outputs:</p> <pre><code>Hello World Hello World https://localhost/WebResource.axd%3Fd=0 </code></pre> <p>I would have expected:</p> <pre><code>Hello World Hello World https://localhost/WebResource.axd?d=0 </code></pre>
[ { "answer_id": 74492851, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".path .query ?d=0 .query UriBuilder UriBuilder baseUri = new UriBuilder(\"http://www.contoso.com/default.aspx?Param1=7890\");" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7400630/" ]
74,491,243
<p>I've got a ListView within a Column. In that Listview I want to place a couple of ListTiles. Unfortunately the tiles behave weird when scrolling. They are shown on top of the other widget placed in the Column</p> <p><a href="https://i.stack.imgur.com/2qjSv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2qjSv.png" alt="" /></a></p> <p>Is there a way to prevent that behaviour of ListTile?</p> <p>Here is my code:</p> <pre><code>Column(children: [ const ChatHeader(), Padding( padding: const EdgeInsets.all(8), child: SizedBox( height: 300, child: ListView.builder( padding: const EdgeInsets.only(left: 8, right: 8), scrollDirection: Axis.vertical, itemCount: myCollection, shrinkWrap: true, physics: const BouncingScrollPhysics(), itemBuilder: (BuildContext context, int index) { var item = myCollection[index]; return Column(children: [ Row( children: [ Container( decoration: boxDecoration( radius: 20, bgColor: d_colorPrimary)), text(&quot;${item.value1}&quot;, fontSize: textSizeMedium) ], ), ListTile( dense: true, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), tileColor: quiz_light_gray, title: SizedBox( child: text(item.name, fontSize: textSizeMedium, textColor: d_textColorPrimary, isLongText: true, maxLine: 10))) ]); }))), 16.height, Container(color: greenColor, child: Text(&quot;text input here&quot;)) ]); </code></pre> <p>Replacing the ListTiles with a Container solves this problem. As far as I can see there is no property to prevent that behaviour. Still want to use ListTiles.</p>
[ { "answer_id": 74492851, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".path .query ?d=0 .query UriBuilder UriBuilder baseUri = new UriBuilder(\"http://www.contoso.com/default.aspx?Param1=7890\");" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794088/" ]
74,491,251
<p>I have a Navbar that has a <code>&lt;li&gt;</code> and one of those list items have a ID of <strong>Navbar-login-btn</strong>. I am able to modify just that ID in the css, however whenever I try to use the <strong>:hover</strong> function on it; it does not work.</p> <p>Is there something I am doing wrong here, because I am not sure. Any help would be nice, thank you!</p> <p><strong>Navbar.jsx:</strong></p> <pre><code>import '../App.css'; import myAvatar from '../images/avataaars.png' function Navbar() { return( &lt;div className='Navbar-container'&gt; &lt;img src={myAvatar} className='Nav-logo'/&gt; &lt;ul&gt; &lt;li&gt;Home&lt;/li&gt; &lt;li&gt;About&lt;/li&gt; &lt;li&gt;Skills&lt;/li&gt; &lt;li&gt;Projects&lt;/li&gt; &lt;li id='Navbar-login-btn'&gt;Login&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; ) } export default Navbar; </code></pre> <p><strong>App.css:</strong></p> <pre><code>.Navbar-container{ margin: 0; width: 100%; display: flex; align-items: center; position: fixed; background-color: #fff; box-sizing: border-box; padding: 10px 40px 10px 40px; } .Nav-logo { width: 75px; height: auto; } #Navbar-login-btn { border: 2px solid rgb(101, 201, 255); border-radius: 20px; color: rgb(101, 201, 255); cursor: pointer; } #Navbar-login-btn:hover { color: #fff; background-color: rgb(101, 201, 255); } .Navbar-container ul{ width: 100%; display: flex; justify-content: space-evenly; font-family: Russo One; list-style: none; gap: 40px; } .Navbar-container li{ padding: 10px; } </code></pre>
[ { "answer_id": 74492851, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".path .query ?d=0 .query UriBuilder UriBuilder baseUri = new UriBuilder(\"http://www.contoso.com/default.aspx?Param1=7890\");" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422283/" ]
74,491,264
<p>npm ERR! code ENOENT</p> <p>npm ERR! syscall open</p> <p>npm ERR! path /Users/giovanylopes/bootcamp-projects/react-nodejs-example/package.json</p> <p>npm ERR! errno -2</p> <p>npm ERR! enoent ENOENT: no such file or directory, open '/Users/giovanylopes/bootcamp-projects/react-nodejs-example/package.json'</p> <p>npm ERR! enoent This is related to npm not being able to find a file.</p> <p>npm ERR! enoent</p> <p>npm ERR! A complete log of this run can be found in:</p> <p>npm ERR! /Users/giovanylopes/.npm/_logs/2022-11-18T14_26_47_519Z-debug-0.log</p> <p>I was expecting to install all the dependencies that are defined in the package.json file</p>
[ { "answer_id": 74492851, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".path .query ?d=0 .query UriBuilder UriBuilder baseUri = new UriBuilder(\"http://www.contoso.com/default.aspx?Param1=7890\");" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19888610/" ]
74,491,269
<p>We have had several instances where new stories have been added to the backlog and then people are confused because the active sprint has new stories that haven't been refined - from the backlog view, adding a new Story always seems to add it to the current sprint iteration.</p> <p><a href="https://i.stack.imgur.com/r9T93.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r9T93.png" alt="enter image description here" /></a></p> <p>It seems a bad approach that new stories are added to a current iteration rather than the main backlog, is there a way to configure this behavior?</p>
[ { "answer_id": 74492851, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": ".path .query ?d=0 .query UriBuilder UriBuilder baseUri = new UriBuilder(\"http://www.contoso.com/default.aspx?Param1=7890\");" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
74,491,279
<p>My dataframe has 22 variables. this is a simplified sample. the variables include x1,x2,y1_,y2_. i want to create a new variable. the variable values are <code>x1*y1_+x2*y2_</code>. the code is as follows:</p> <pre class="lang-r prettyprint-override"><code>df &lt;- data.frame(x1=c(0,0,0,1),x2=c(0,0,0,1),y1_=c(3,0,2,1),y2_=c(1,0,0,1)) df$var &lt;- df$x1*df$y1_+df$x2*df$y2_ </code></pre> <p>if no. of variables is 22, the above code is unreasonable. so,how to get this variable?</p>
[ { "answer_id": 74491378, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 0, "selected": false, "text": "df$var <- do.call(`+`, \n lapply(split.default(df, gsub(\".*([0-9]+)_?$\", \"\\\\1\", names(df))),\n function(z) apply(z, 1, prod)))\ndf\n# x1 x2 y1_ y2_ var\n# 1 0 0 3 1 0\n# 2 0 0 0 0 0\n# 3 0 0 2 0 0\n# 4 1 1 1 1 2\n gsub(\".*([0-9]+)_?$\", \"\\\\1\", names(df))\n# [1] \"1\" \"2\" \"1\" \"2\"\nsplit.default(df, gsub(\".*([0-9]+)_?$\", \"\\\\1\", names(df)))\n# $`1`\n# x1 y1_\n# 1 0 3\n# 2 0 0\n# 3 0 2\n# 4 1 1\n# $`2`\n# x2 y2_\n# 1 0 1\n# 2 0 0\n# 3 0 0\n# 4 1 1\nlapply(split.default(df, gsub(\".*([0-9]+)_?$\", \"\\\\1\", names(df))),\n function(z) apply(z, 1, prod))\n# $`1`\n# [1] 0 0 0 1\n# $`2`\n# [1] 0 0 0 1\n" }, { "answer_id": 74491414, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "x <- colnames(df)\ndf$var <- rowSums(df[, grepl(\"^x\", x)] * df[, grepl(\"^y\", x)])\ndf\n# x1 x2 y1_ y2_ var\n# 1 0 0 3 1 0\n# 2 0 0 0 0 0\n# 3 0 0 2 0 0\n# 4 1 1 1 1 2\n" }, { "answer_id": 74491728, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 0, "selected": false, "text": "across library(dplyr)\n\ndf %>% mutate(var = rowSums(across(matches(\"\\\\d$\")) * across(ends_with(\"_\"))))\n x1 x2 y1_ y2_ var\n1 0 0 3 1 0\n2 0 0 0 0 0\n3 0 0 2 0 0\n4 1 1 1 1 2\n df %>%\n rowwise %>%\n mutate(var = sum(c_across(matches(\"\\\\d$\")) * c_across(ends_with(\"_\")))) %>%\n ungroup\n df <- structure(list(x1 = c(0, 0, 0, 1), x2 = c(0, 0, 0, 1), y1_ = c(3, \n0, 2, 1), y2_ = c(1, 0, 0, 1)), class = \"data.frame\", row.names = c(NA, \n-4L))\n\ndf\n## x1 x2 y1_ y2_\n## 1 0 0 3 1\n## 2 0 0 0 0\n## 3 0 0 2 0\n## 4 1 1 1 1\n" }, { "answer_id": 74491855, "author": "Captain Hat", "author_id": 4676560, "author_profile": "https://Stackoverflow.com/users/4676560", "pm_score": 0, "selected": false, "text": "tidyverse df <- data.frame(x1=c(1,2,3,4),x2=c(1,1,0,1),y1_=c(3,0,2,1),y2_=c(1,4,0,1))\n\nlibrary(tidyr)\nlibrary(dplyr)\nlibrary(purrr)\n\npivoted <-\n pivot_longer(\n df,\n cols = everything(),\n names_to = c(\"letter\", \"number\"),\n names_pattern = \"(.)(.)\"\n )\n\npivoted\n#> # A tibble: 16 × 3\n#> letter number value\n#> <chr> <chr> <dbl>\n#> 1 x 1 1\n#> 2 x 2 1\n#> 3 y 1 3\n#> 4 y 2 1\n#> 5 x 1 2\n#> 6 x 2 1\n#> 7 y 1 0\n#> 8 y 2 4\n#> 9 x 1 3\n#> 10 x 2 0\n#> 11 y 1 2\n#> 12 y 2 0\n#> 13 x 1 4\n#> 14 x 2 1\n#> 15 y 1 1\n#> 16 y 2 1\n\nnested <- \n pivoted |> \n group_by(letter, number) |> \n nest(num_data = value)\n\nnested\n#> # A tibble: 4 × 3\n#> # Groups: letter, number [4]\n#> letter number num_data \n#> <chr> <chr> <list> \n#> 1 x 1 <tibble [4 × 1]>\n#> 2 x 2 <tibble [4 × 1]>\n#> 3 y 1 <tibble [4 × 1]>\n#> 4 y 2 <tibble [4 × 1]>\n\nsummarised <-\n nested |>\n group_by(number) |> \n summarise(across(num_data, pmap, list))\n\nsummarised\n#> # A tibble: 2 × 2\n#> number num_data \n#> <chr> <named list>\n#> 1 1 <list [2]> \n#> 2 2 <list [2]>\n\nsummarised <- rowwise(summarised)\n\nsummarised <- \n transmute(\n summarised,\n products = list(\n pmap(num_data, prod)\n )\n )\n\nsummarised[[\"products\"]]\n#> [[1]]\n#> [[1]][[1]]\n#> [1] 3\n#> \n#> [[1]][[2]]\n#> [1] 0\n#> \n#> [[1]][[3]]\n#> [1] 6\n#> \n#> [[1]][[4]]\n#> [1] 4\n#> \n#> \n#> [[2]]\n#> [[2]][[1]]\n#> [1] 1\n#> \n#> [[2]][[2]]\n#> [1] 4\n#> \n#> [[2]][[3]]\n#> [1] 0\n#> \n#> [[2]][[4]]\n#> [1] 1\n\ndf[[\"var\"]] <- \n summarised[[\"products\"]] |> \n pmap_dbl(sum)\n\ndf\n#> x1 x2 y1_ y2_ var\n#> 1 1 1 3 1 4\n#> 2 2 1 0 4 4\n#> 3 3 0 2 0 6\n#> 4 4 1 1 1 5\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16273736/" ]
74,491,306
<p>I have an array and a variable :</p> <pre><code>string[] StringArray = { &quot;foo bar foo $ bar $ foo bar $&quot; }; string check = &quot;$&quot;; </code></pre> <p>And I want to remove the &quot;$&quot; so the output will be :</p> <pre><code>foo bar foo bar foo bar </code></pre>
[ { "answer_id": 74491351, "author": "Josh Adams", "author_id": 8382067, "author_profile": "https://Stackoverflow.com/users/8382067", "pm_score": 2, "selected": false, "text": "string[] StringArray = { \"foo bar foo $ bar $ foo bar $\" };\nstring check = \"$\";\n\nvar noDollaBillsYall = StringArray.Select(x => x.Replace(check, string.Empty)).ToArray();\n" }, { "answer_id": 74491361, "author": "SupaMaggie70 b", "author_id": 17547957, "author_profile": "https://Stackoverflow.com/users/17547957", "pm_score": 1, "selected": false, "text": "for(int i = 0;i < StringArray.Length;i++) {\nStringArray[i] = StringArray[i].Replace(“$”,””);\n}\n" }, { "answer_id": 74491547, "author": "DonMiguelSanchez", "author_id": 13337616, "author_profile": "https://Stackoverflow.com/users/13337616", "pm_score": 1, "selected": false, "text": "string string[] StringArray = { \"foo\", \"bar\", \"foo\", \"$\", \"bar\", \"$\", \"foo\", \"bar\", \"$\" };\n string check = \"$\";\n\n var stringList = StringArray.ToList();\n\n stringList.RemoveAll(x => x == check);\n\n StringArray = stringList.ToArray();\n" }, { "answer_id": 74491561, "author": "Iseca", "author_id": 16294873, "author_profile": "https://Stackoverflow.com/users/16294873", "pm_score": 0, "selected": false, "text": " string[] StringArray = { \"foo bar foo $ bar $ foo bar $\" };\n\n foreach(var result in StringArray)\n {\n Console.WriteLine(result.Replace('$',' ').ToString());\n }\n" }, { "answer_id": 74491802, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "$ \"$ foo bar foo $ bar $ foo bar $\"\n item => item.Replace(\"$\", string.Empty) \" foo bar foo bar $ foo bar \" <- note spaces \n \"foo bar foo bar foo bar\" \n using System.Linq;\nusing System.Text.RegularExpressions;\n\n...\n\nstring[] StringArray = { \"$ foo bar foo $ bar $ foo bar $\" };\n\nstring[] result = StringArray\n .Select(item => Regex.Replace(\n item,\n @\"\\s*\\$\\s*\",\n m => m.Index == 0 || m.Index + m.Length == item.Length ? \"\" : \" \"))\n .ToArray();\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16294873/" ]
74,491,310
<p>I have a Xamarin Android App in which I need to check the VersionName. Here is the function call:</p> <pre><code>var appVersion = PackageManager.GetPackageInfo(PackageName, 0).VersionName; </code></pre> <p>It has been working fine. All of a sudden with the last Android OS update, the function call is deprecated. I prefer not to use Xamarin Essentials. Doing that forces me to use older Nuget packages. Does anyone know what the preferred way will be to get the Version Name in Xamarin going forward?</p> <p>Thanks, Jim</p>
[ { "answer_id": 74491351, "author": "Josh Adams", "author_id": 8382067, "author_profile": "https://Stackoverflow.com/users/8382067", "pm_score": 2, "selected": false, "text": "string[] StringArray = { \"foo bar foo $ bar $ foo bar $\" };\nstring check = \"$\";\n\nvar noDollaBillsYall = StringArray.Select(x => x.Replace(check, string.Empty)).ToArray();\n" }, { "answer_id": 74491361, "author": "SupaMaggie70 b", "author_id": 17547957, "author_profile": "https://Stackoverflow.com/users/17547957", "pm_score": 1, "selected": false, "text": "for(int i = 0;i < StringArray.Length;i++) {\nStringArray[i] = StringArray[i].Replace(“$”,””);\n}\n" }, { "answer_id": 74491547, "author": "DonMiguelSanchez", "author_id": 13337616, "author_profile": "https://Stackoverflow.com/users/13337616", "pm_score": 1, "selected": false, "text": "string string[] StringArray = { \"foo\", \"bar\", \"foo\", \"$\", \"bar\", \"$\", \"foo\", \"bar\", \"$\" };\n string check = \"$\";\n\n var stringList = StringArray.ToList();\n\n stringList.RemoveAll(x => x == check);\n\n StringArray = stringList.ToArray();\n" }, { "answer_id": 74491561, "author": "Iseca", "author_id": 16294873, "author_profile": "https://Stackoverflow.com/users/16294873", "pm_score": 0, "selected": false, "text": " string[] StringArray = { \"foo bar foo $ bar $ foo bar $\" };\n\n foreach(var result in StringArray)\n {\n Console.WriteLine(result.Replace('$',' ').ToString());\n }\n" }, { "answer_id": 74491802, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 0, "selected": false, "text": "$ \"$ foo bar foo $ bar $ foo bar $\"\n item => item.Replace(\"$\", string.Empty) \" foo bar foo bar $ foo bar \" <- note spaces \n \"foo bar foo bar foo bar\" \n using System.Linq;\nusing System.Text.RegularExpressions;\n\n...\n\nstring[] StringArray = { \"$ foo bar foo $ bar $ foo bar $\" };\n\nstring[] result = StringArray\n .Select(item => Regex.Replace(\n item,\n @\"\\s*\\$\\s*\",\n m => m.Index == 0 || m.Index + m.Length == item.Length ? \"\" : \" \"))\n .ToArray();\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3074765/" ]
74,491,381
<p>I have a Dialog that I cant close when I press the button this is my code, I believe that is for the if cycle, but I need it to make it true under those circumstances, any idea that could help me here?</p> <pre><code>@Composable fun PopupWindowDialog( parentUiState: ParentHomeUiState, ) { val openDialog = remember { mutableStateOf(false) } var sliderPosition by remember { mutableStateOf(0f) } if (!parentUiState.showInAppFeedback){ openDialog.value = true } val recommend = sliderPosition.toInt() Column( ) { Box { if (openDialog.value) { Dialog( onDismissRequest = { openDialog.value = false }, properties = DialogProperties(), ){ Box( Modifier .fillMaxWidth() .fillMaxHeight() //.padding(vertical = 70.dp, horizontal = 10.dp) .padding(vertical = 70.dp ) .background(Color.White, RoundedCornerShape(10.dp)) //.border(1.dp, color = Color.Black, RoundedCornerShape(20.dp)) .border(1.dp, color = Color.White, RoundedCornerShape(20.dp)) ) { Button( modifier = Modifier .fillMaxWidth() .padding(10.dp), onClick = { openDialog.value = !openDialog.value } ) { Text( text = &quot;¡Contesta y gana +20 puntos!&quot;, style = MaterialTheme.typography.subtitle2, fontWeight = FontWeight.Bold, modifier = Modifier.padding(3.dp)) } } } } } } } </code></pre>
[ { "answer_id": 74491581, "author": "z.y", "author_id": 19023745, "author_profile": "https://Stackoverflow.com/users/19023745", "pm_score": 3, "selected": true, "text": ".showInAppFeedback val openDialog = remember { mutableStateOf(false) }\n\n...\n...\n\nif (!parentUiState.showInAppFeedback) {\n openDialog.value = true\n}\n openDialog re-compose LaunchedEffect LaunchedEffect(parentUiState.showInAppFeedback) {\n openDialog.value = true\n}\n" }, { "answer_id": 74491714, "author": "Ryan Payne", "author_id": 11809808, "author_profile": "https://Stackoverflow.com/users/11809808", "pm_score": 1, "selected": false, "text": "parentUiState.showInAppFeedback openDialog.value true parentUiState.showInAppFeedback remember @Composable\nfun PopupWindowDialog(parentUiState: ParentHomeUiState) {\n val openDialog = remember { mutableStateOf(!parentUiState.showInAppFeedback) }\n var sliderPosition by remember { mutableStateOf(0f) }\n\n val recommend = sliderPosition.toInt()\n Column {\n Box {\n if (openDialog.value) {\n Dialog(\n onDismissRequest = { openDialog.value = false },\n properties = DialogProperties(),\n ) {\n Box(\n Modifier\n .fillMaxWidth()\n .fillMaxHeight()\n //.padding(vertical = 70.dp, horizontal = 10.dp)\n .padding(vertical = 70.dp)\n .background(Color.White, RoundedCornerShape(10.dp))\n //.border(1.dp, color = Color.Black, RoundedCornerShape(20.dp))\n .border(1.dp, color = Color.White, RoundedCornerShape(20.dp))\n ) {\n Button(\n modifier = Modifier\n .fillMaxWidth()\n .padding(10.dp),\n onClick = {\n openDialog.value = !openDialog.value\n }\n ) {\n Text(\n text = \"¡Contesta y gana +20 puntos!\",\n style = MaterialTheme.typography.subtitle2,\n fontWeight = FontWeight.Bold,\n modifier = Modifier.padding(3.dp)\n )\n }\n }\n }\n }\n }\n }\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10625391/" ]
74,491,449
<p>I am looking to remove duplicate rows based on the values in a column (&quot;Name&quot;), but append the corresponding string values in another column(&quot;Occupation&quot;).</p> <p>Duplicate entry is &quot;Jack&quot;</p> <p>I have a dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: center;">center</th> <th style="text-align: right;">Occupation</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Jack</td> <td style="text-align: center;">Miami</td> <td style="text-align: right;">Clerk</td> </tr> <tr> <td style="text-align: left;">Alice</td> <td style="text-align: center;">Tx</td> <td style="text-align: right;">Manager</td> </tr> <tr> <td style="text-align: left;">Jack</td> <td style="text-align: center;">San Jose</td> <td style="text-align: right;">PO</td> </tr> <tr> <td style="text-align: left;">Cathy</td> <td style="text-align: center;">Houston</td> <td style="text-align: right;">Security</td> </tr> </tbody> </table> </div> <p>And i am expecting this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: center;">center</th> <th style="text-align: right;">Occupation</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Jack</td> <td style="text-align: center;">Miami</td> <td style="text-align: right;">Clerk PO</td> </tr> <tr> <td style="text-align: left;">Alice</td> <td style="text-align: center;">Tx</td> <td style="text-align: right;">Manager</td> </tr> <tr> <td style="text-align: left;">Cathy</td> <td style="text-align: center;">Houston</td> <td style="text-align: right;">Security</td> </tr> </tbody> </table> </div> <p>Appreciate any answer on this</p>
[ { "answer_id": 74491549, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 1, "selected": true, "text": "df.groupby('Name',as_index=False).agg(\n {'center':'first','Occupation':lambda x: ' '.join(x)}\n )\n Name center Occupation\n0 Alice Tx Manager\n1 Cathy Houston Security\n2 Jack Miami Clerk PO\n first" }, { "answer_id": 74491557, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 1, "selected": false, "text": "first out = df.groupby('Name', as_index=False, sort=False).agg({'center': 'first', 'Occupation': ' '.join})\nprint(out)\n Name center Occupation\n0 Jack Miami Clerk PO\n1 Alice Tx Manager\n2 Cathy Houston Security\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663383/" ]
74,491,487
<p>Having a <code>&lt;nullable&gt;enabled&lt;/nullable&gt;</code> in project settings, having the following class</p> <pre><code>public class Car { public required string Name { get; init; } } </code></pre> <p>and deserializing it from string:</p> <pre><code>System.Text.Json.JsonSerializer.Deserialize&lt;Car&gt;(&quot;&quot;&quot;{&quot;Name&quot;: null}&quot;&quot;&quot;); </code></pre> <p>Does not throw an exception</p> <p>Because property is marked as not nullable, is it possible to configure STJ to throw in case of <code>null</code> value?</p>
[ { "answer_id": 74491583, "author": "merlinabarzda", "author_id": 10163557, "author_profile": "https://Stackoverflow.com/users/10163557", "pm_score": 2, "selected": false, "text": "public class Car\n{\n [JsonProperty(Required = Required.Always)]\n public string Name { get; init; }\n}\n" }, { "answer_id": 74492877, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 0, "selected": false, "text": "required JsonRequiredAttribute JsonTypeInfo.IsRequired private static void ThrowNullableRequired(JsonTypeInfo jsonTypeInfo)\n{\n if (jsonTypeInfo.Kind != JsonTypeInfoKind.Object)\n {\n return;\n }\n\n foreach (var property in jsonTypeInfo.Properties)\n {\n if (property.IsRequired && !property.PropertyType.IsValueType && property.Set is { } setter)\n {\n // not sure maybe should cache nullability checks\n NullabilityInfoContext context = new();\n var nullabilityInfo = context.Create(jsonTypeInfo.Type.GetProperty(property.Name));\n if (nullabilityInfo.WriteState is not NullabilityState.NotNull)\n {\n continue;\n }\n\n property.Set = (obj, val) =>\n {\n if (val is null)\n {\n throw new JsonException($\"null for required prop: {property.Name}\");\n }\n\n setter(obj, val);\n };\n }\n }\n}\n var settings = new JsonSerializerOptions\n{\n TypeInfoResolver = new DefaultJsonTypeInfoResolver\n {\n Modifiers = { ThrowNullableRequired }\n }\n};\n \ntry\n{\n var myClass1 = JsonSerializer.Deserialize<Car>(\n \"\"\"\n {\n \"Name\":null,\n \"Prefix\":null\n }\n \"\"\", settings);\n}\ncatch (Exception e)\n{\n}\n\nvar car = JsonSerializer.Deserialize<Car>(\n \"\"\"\n {\n \"Name\":\"a\",\n \"Prefix\":null\n }\n \"\"\", settings);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963935/" ]
74,491,495
<p>I need to make sure we have support to create a hierarchy table based on a &quot;father/son&quot; table. Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">F</th> <th style="text-align: right;">S</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">a</td> <td style="text-align: right;">b</td> </tr> <tr> <td style="text-align: left;">b</td> <td style="text-align: right;">c</td> </tr> <tr> <td style="text-align: left;">b</td> <td style="text-align: right;">d</td> </tr> <tr> <td style="text-align: left;">b</td> <td style="text-align: right;">e</td> </tr> <tr> <td style="text-align: left;">e</td> <td style="text-align: right;">f</td> </tr> <tr> <td style="text-align: left;">e</td> <td style="text-align: right;">g</td> </tr> <tr> <td style="text-align: left;">b</td> <td style="text-align: right;">m</td> </tr> <tr> <td style="text-align: left;">z</td> <td style="text-align: right;">n</td> </tr> <tr> <td style="text-align: left;">m</td> <td style="text-align: right;">k</td> </tr> </tbody> </table> </div> <p>Expected result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">L</th> <th style="text-align: center;">L1</th> <th style="text-align: center;">L2</th> <th style="text-align: right;">L3</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">a</td> <td style="text-align: center;">b</td> <td style="text-align: center;">c</td> <td style="text-align: right;"></td> </tr> <tr> <td style="text-align: left;">a</td> <td style="text-align: center;">b</td> <td style="text-align: center;">d</td> <td style="text-align: right;"></td> </tr> <tr> <td style="text-align: left;">a</td> <td style="text-align: center;">b</td> <td style="text-align: center;">e</td> <td style="text-align: right;"></td> </tr> <tr> <td style="text-align: left;">e</td> <td style="text-align: center;">f</td> <td style="text-align: center;"></td> <td style="text-align: right;"></td> </tr> <tr> <td style="text-align: left;">e</td> <td style="text-align: center;">g</td> <td style="text-align: center;"></td> <td style="text-align: right;"></td> </tr> <tr> <td style="text-align: left;">a</td> <td style="text-align: center;">b</td> <td style="text-align: center;">m</td> <td style="text-align: right;">k</td> </tr> <tr> <td style="text-align: left;">z</td> <td style="text-align: center;">n</td> <td style="text-align: center;"></td> <td style="text-align: right;"></td> </tr> </tbody> </table> </div> <p>Any idea, suggestion?</p> <p>Thank you</p>
[ { "answer_id": 74491745, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 2, "selected": false, "text": "SELECT L0.F AS L, L1.F AS L1, L2.F AS L2, L3.S AS L3\nFROM t L0\nLEFT JOIN t L1\nON L0.S = L1.F\nLEFT JOIN t L2\nON L1.S = L2.F\nLEFT JOIN t L3\nON L2.S = L3.S\nLEFT JOIN t nonexistent\nON L0.F = nonexistent.S\nWHERE nonexistent.S IS NULL\n $SELECT = \"SELECT L0.F AS L\";\n$FROM = \"t L0\";\nfor ($index = 1; $index < $n; $index++) {\n $SELECT .= \", L{$index}.F AS L{$index}\";\n $FROM .= \" LEFT JOIN L\" . $index . \" ON L\" . ($index - 1) . \".S = L\" . $index . \"F\";\n}\n$FROM .= \" LEFT JOIN t nonexistent ON L0.F = nonexistent.S \";\nWHERE = \"WHERE nonexistent.S IS NULL\";\n$query = \"{$SELECT} ${FROM} {$WHERE}\";\n" }, { "answer_id": 74491963, "author": "DannySlor", "author_id": 19174570, "author_profile": "https://Stackoverflow.com/users/19174570", "pm_score": 2, "selected": true, "text": "with \nrecursive cte(id, path) as\n(\nselect f, f::text from t where f not in(select s from t where s is not null)\nunion all\nselect t.s, cte.path || '/' || t.s from cte join t on cte.id = t.f \n)\n\nselect id \n ,path[1] as root\n ,path[2] as l1\n ,path[3] as l2\n ,path[4] as l3\n ,path[5] as l4\nfrom \n(\nselect id \n ,regexp_split_to_array(path, '/') as path\nfrom cte\n) cte\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7673528/" ]
74,491,530
<p>Does microservice artchitecture/ rest api standards allow for different structures for different response codes like, say, for 200 and 207 ?</p> <p>If yes, how can I implement the same in my spring boot restful application ?</p>
[ { "answer_id": 74596422, "author": "The-Proton-Resurgence", "author_id": 4939287, "author_profile": "https://Stackoverflow.com/users/4939287", "pm_score": 0, "selected": false, "text": "ResponseEntity<Object> @GetMapping(path = \"/demo/example\")\n public ResponseEntity<Object> getData (\n @RequestParam(name = \"auth_id\") String authId\n) {\n//Logic\n//200\n//return ResponseEntity.ok().body(objFor200Response);\n\n//204\n//return ResponseEntity.accepted().body(objFor204Response);\n\n//207\n//return new ResponseEntity<>(objFor207Response,HttpStatus.MULTI_STATUS);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13548254/" ]
74,491,538
<p>I am given <code>k</code> numbers of <code>LinkedList&lt;Integer&gt;</code> and I'm trying to put them into a <code>PriorityQueue p</code> in order to sort it.</p> <p>However, I'm having trouble trying to convert it back into a <code>LinkedList&lt;Integer&gt;</code> from the Priority Queue that I have declared.</p> <p>Here is my code:</p> <pre><code>//Code by Dave S. public class MultiMergeWay { public static LinkedList&lt;Integer&gt; mergeAll(LinkedList&lt;Integer&gt;[] lists){ PriorityQueue&lt;LinkedList&lt;Integer&gt;&gt; p = new PriorityQueue&lt;&gt;(); for(LinkedList&lt;Integer&gt; x : lists){ p.add(x); } LinkedList&lt;Integer&gt; array_list = new LinkedList&lt;Integer&gt;(p); // return array_list; } } </code></pre> <p>Unless you haven't already seen it, my code wouldn't even compile because of an error in the line marked with a <code>//</code>.</p> <p>Can anyone please explain how can I change my priority queue back to a LinkedList?</p>
[ { "answer_id": 74491891, "author": "Sagar Gangwal", "author_id": 5809720, "author_profile": "https://Stackoverflow.com/users/5809720", "pm_score": 0, "selected": false, "text": "flatMap public class MultiMergeWay {\n public static void main(String[] args) {\n LinkedList<Integer> array_list = new LinkedList<>(Arrays.asList(new Integer[]{100, 500, 80}));\n LinkedList<Integer> array_list1 = new LinkedList<>(Arrays.asList(new Integer[]{200, 600, 90}));\n LinkedList<Integer> array_list2 = new LinkedList<>(Arrays.asList(new Integer[]{1200, 700, 80}));\n mergeAll(new LinkedList[]{array_list, array_list1, array_list2});\n }\n\n public static LinkedList<Integer> mergeAll(LinkedList<Integer>[] array) {\n System.out.println(\"Before ==>\" + array[0] + \" \" + array[1] + \"\" + array[2]);\n var result = Stream.of(array).flatMap(Collection::stream).sorted().collect(Collectors.toList());\n System.out.println(\"After ==>\" + result);\n return new LinkedList<>(result);\n }\n\n}\n" }, { "answer_id": 74492012, "author": "matt", "author_id": 2067492, "author_profile": "https://Stackoverflow.com/users/2067492", "pm_score": 3, "selected": true, "text": "PriorityQueue<Integer> p = new PriorityQueue<>();\n p.addAll(x);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18984687/" ]
74,491,593
<p>my app got error &quot;Type 'String' is not a subtype of type 'int' of 'index'. This is because i want to get data with a string id. But i use listview.builder and it can't accept a string data this is my code</p> <pre><code>class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() =&gt; _HomePageState(); } class _HomePageState extends State&lt;HomePage&gt; { late Future&lt;List&lt;Agent&gt;&gt; agents; @override void initState() { super.initState(); agents = fetchAgents(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('My Anime List'), ), body: Column( children: [ FutureBuilder( builder: (context, AsyncSnapshot&lt;List&lt;Agent&gt;&gt; snapshot) { if (snapshot.hasData) { return Expanded( child: ListView.builder( itemCount: snapshot.data?.length, itemBuilder: (BuildContext context, index) { return Card( child: ListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 20.0, vertical: 10.0), leading: CircleAvatar( radius: 30, backgroundImage: NetworkImage( snapshot.data![index].displayIconSmall), ), title: Text(snapshot.data![index].displayName), subtitle: Text('Role: ${snapshot.data![index].role.displayName}'), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; DetailPage( item: snapshot.data![index].uuid, title: snapshot.data![index].displayName, role: snapshot.data![index].role.displayName, image: snapshot.data![index].displayIconSmall, description: snapshot.data![index].description,), ), ); }, ), ); }, ), ); } else if (snapshot.hasError) { return Center(child: Text('${snapshot.error}')); } return const CircularProgressIndicator(); }, future: agents, ), ], ), ); } } </code></pre> <pre><code>class Agent { final String uuid; final String displayName; final String description; final String displayIcon; final String displayIconSmall; final bool isPlayableCharacter; Role role; Agent({ required this.uuid, required this.displayName, required this.description, required this.displayIcon, required this.displayIconSmall, required this.isPlayableCharacter, required this.role }); factory Agent.fromJson(Map&lt;String, dynamic&gt; json) { return Agent( uuid: json['uuid'], displayName : json['displayName'], description : json['description'], displayIcon : json['displayIcon'], displayIconSmall : json['displayIconSmall'], isPlayableCharacter : json['isPlayableCharacter'], role : json['role'], ); } Map&lt;String, dynamic&gt; toJson() =&gt; { 'uuid': uuid, 'displayName': displayName, 'description': description, 'displayIcon': displayIcon, 'displayIconSmall': displayIconSmall, 'isPlayableCharacter': isPlayableCharacter, 'role': role }; } class Role{ final String uuid; final String displayName; final String description; Role({ required this.uuid, required this.displayName, required this.description, }); factory Role.fromJson(Map&lt;String, dynamic&gt; json) { return Role( uuid: json['uuid'], displayName : json['displayName'], description : json['description'], ); } Map&lt;String, dynamic&gt; toJson() =&gt; { 'uuid': uuid, 'displayName': displayName, 'description': description, }; } </code></pre> <pre><code>Future&lt;List&lt;Agent&gt;&gt; fetchAgents() async { final response = await http.get(Uri.parse('https://valorant-api.com/v1/agents')); if (response.statusCode == 200) { var jsonResponse = json.decode(response.body)['data']; var data = jsonResponse[&quot;data&quot;]; if(data is Map) { Role user = Role( uuid:[&quot;uuid&quot;].toString(), displayName:[&quot;displayName&quot;].toString(), description:[&quot;description&quot;].toString(), ); return jsonResponse.map((role) =&gt; Agent.fromJson(role)).toList(); }; return jsonResponse.map((agent) =&gt; Agent.fromJson(agent)).toList(); } else { throw Exception('Failed to load data'); } } </code></pre> <p>i already try to change it to integer but it can't since listview.build must have index and index must be integer. I expecting the data can be pass because the uid for the api data is string type</p>
[ { "answer_id": 74491891, "author": "Sagar Gangwal", "author_id": 5809720, "author_profile": "https://Stackoverflow.com/users/5809720", "pm_score": 0, "selected": false, "text": "flatMap public class MultiMergeWay {\n public static void main(String[] args) {\n LinkedList<Integer> array_list = new LinkedList<>(Arrays.asList(new Integer[]{100, 500, 80}));\n LinkedList<Integer> array_list1 = new LinkedList<>(Arrays.asList(new Integer[]{200, 600, 90}));\n LinkedList<Integer> array_list2 = new LinkedList<>(Arrays.asList(new Integer[]{1200, 700, 80}));\n mergeAll(new LinkedList[]{array_list, array_list1, array_list2});\n }\n\n public static LinkedList<Integer> mergeAll(LinkedList<Integer>[] array) {\n System.out.println(\"Before ==>\" + array[0] + \" \" + array[1] + \"\" + array[2]);\n var result = Stream.of(array).flatMap(Collection::stream).sorted().collect(Collectors.toList());\n System.out.println(\"After ==>\" + result);\n return new LinkedList<>(result);\n }\n\n}\n" }, { "answer_id": 74492012, "author": "matt", "author_id": 2067492, "author_profile": "https://Stackoverflow.com/users/2067492", "pm_score": 3, "selected": true, "text": "PriorityQueue<Integer> p = new PriorityQueue<>();\n p.addAll(x);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540659/" ]
74,491,674
<p>I am trying to have a list of checkboxes with different values that then will populate into a multi-line textbox based on the selection. I will need to have the list be dynamic between users checking and unchecking boxes and having these populate by their selection into this textbox.</p> <p><a href="https://i.stack.imgur.com/Bs7j0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bs7j0.png" alt="enter image description here" /></a></p> <p>Any direction will help thanks!</p> <p>I do not have a solution for this aright now</p>
[ { "answer_id": 74491891, "author": "Sagar Gangwal", "author_id": 5809720, "author_profile": "https://Stackoverflow.com/users/5809720", "pm_score": 0, "selected": false, "text": "flatMap public class MultiMergeWay {\n public static void main(String[] args) {\n LinkedList<Integer> array_list = new LinkedList<>(Arrays.asList(new Integer[]{100, 500, 80}));\n LinkedList<Integer> array_list1 = new LinkedList<>(Arrays.asList(new Integer[]{200, 600, 90}));\n LinkedList<Integer> array_list2 = new LinkedList<>(Arrays.asList(new Integer[]{1200, 700, 80}));\n mergeAll(new LinkedList[]{array_list, array_list1, array_list2});\n }\n\n public static LinkedList<Integer> mergeAll(LinkedList<Integer>[] array) {\n System.out.println(\"Before ==>\" + array[0] + \" \" + array[1] + \"\" + array[2]);\n var result = Stream.of(array).flatMap(Collection::stream).sorted().collect(Collectors.toList());\n System.out.println(\"After ==>\" + result);\n return new LinkedList<>(result);\n }\n\n}\n" }, { "answer_id": 74492012, "author": "matt", "author_id": 2067492, "author_profile": "https://Stackoverflow.com/users/2067492", "pm_score": 3, "selected": true, "text": "PriorityQueue<Integer> p = new PriorityQueue<>();\n p.addAll(x);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13486871/" ]
74,491,679
<p>I'm looking to sort a list of of strings which illustrate dependencies (the structure of a Bayesian Networks determined through the PC Algorithm).</p> <p>e.g.</p> <pre><code>verbose_struct = ['A', 'C|A,E', 'E', 'B|C,D', 'D'] </code></pre> <pre><code>sorted_struct = ['A', 'E', 'D', 'C|A,E', 'B|C,D'] </code></pre> <p>The order of the strings is determined by whether or not the dependencies (the letters following the delimiter '|', e.g. B is dependent on C and D) have been previously listed. As in the above, 'E' should be positioned before 'C|A,E' as C is dependent on E. Strings with no dependencies should be positioned before all strings with dependencies, e.g. 'D' before 'C|A,E' and 'B|C,D'.</p> <p>How would I go about this?</p> <p>I have managed to order the strings by whether or not they have dependencies using the following:</p> <pre><code>sorted_struct = sorted(verbose_struct, key=lambda x: len(x.split('|'))) </code></pre> <p>I am unsure how to then further sort the variables by their dependencies, as I am fairly unfamiliar with lambda functions in Python.</p>
[ { "answer_id": 74492217, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 0, "selected": false, "text": "import queue\n\na = list(filter(lambda x: len(x) == 1, verbose_struct ))\nb = {x.split('|')[0]: tuple(x.split('|')[1].split(',')) for x in filter(lambda x: len(x) > 1, verbose_struct )}\nnodes = a[:]\nq = queue.deque(b.keys())\nwhile q:\n cur = q.pop()\n if all(map(lambda x: x in nodes, b[cur])):\n nodes.append(cur[0])\n a.append(f\"{cur}|\" + \",\".join(b[cur]))\n else:\n q.appendleft(cur)\n" }, { "answer_id": 74494285, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 2, "selected": true, "text": "class __lt__ Element elements sort() # Bayesian Elements\n\nclass Element():\n\n def __init__(self, data: str):\n self.label = data\n if '|' in data:\n # dependency...break it up\n self.base, dependencies = data.split('|')\n # break up the dependencies\n self.dependencies = set(dependencies.split(','))\n else: # it is a single base element\n self.base = data\n self.dependencies = None\n\n def get_dependencies(self):\n return self.dependencies\n\n def get_base(self):\n return self.base\n\n def get_label(self):\n return self.label\n\n def __str__(self):\n return f'base: {self.base}, dep: {self.dependencies}'\n\n def __repr__(self):\n return self.label\n\n # in order to compare class elements, you must create a custom \"less than\" function\n # it is the basis of sort\n def __lt__(self, other: 'Element'):\n # case 1: both are singletons, just alphabetically sort them:\n if self.dependencies is None and other.dependencies is None:\n return self.label < other.label\n # case 2: self has no dependencies, but other does\n elif self.dependencies is None and other.dependencies is not None:\n return True\n # case 3: other has no dependencies, self does\n elif other.dependencies is None and self.dependencies is not None:\n return False\n # case 4: both have dependencies, check if self depends on other:\n else:\n if self.base in other.dependencies:\n return True\n elif other.base in self.dependencies:\n return False\n else: # sort by the base element\n return self.base < other.base\n\ndata = ['B', 'A', 'C|A,E', 'E', 'B|C,D', 'D']\n\n# make \"elements\" from the strings\nelements = [Element(t) for t in data]\n\nelements.sort()\n\nprint(elements)\n\n# example\nprint(elements[4].get_dependencies())\n [A, B, D, E, C|A,E, B|C,D]\n{'A', 'E'}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16488477/" ]
74,491,681
<p>After requesting it for the backend, I want to display the product image to the user.</p> <p>the problem is: the API response with PNG image found the product image but if the product has no image the API response is with (204 NO Content), so I need to display the default image instead.</p> <p>after searching I found the <code>defaultSource</code> prop to the <code>&lt;Image&gt;</code> component and it works fine on IOS but in android, it does not.</p> <pre><code>&lt;Image defaultSource={{ uri: productDefaultImage }} source={{ uri: env.apiUrl.concat(env.productImageById.replace(&quot;:productId&quot;, price.id.toString())).concat(&quot;?thumbnail=true&quot;), headers: { Authorization: `Bearer ${token}`} }} resizeMode=&quot;contain&quot; style={{ width: 100, height: 70 }} onLoadEnd={() =&gt; setImageLoading(false)} /&gt; </code></pre> <p>some of the returned data from API</p> <pre><code>�PNG IHDRww^�� pHYs��IDATx^����wu���9u��=9g͌rH ���1x�1��YG���kÚ�/�ؘl�,!��F��g:��ʹ�����ww�y�����6�����tW=ϭ�{���sϑ�;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;v���#`G���;?�p�d_� }u?��2�sM8��~ޟ��;&gt;WqZ��.���\r&gt;�8 ]=���d6�Δ }��ayB�B��.��|6,�j�dU��Ⱥ��z ����b&gt;^�Y������S�ԂV&amp;�w�r��j��@���7�&gt;���5/\��n&gt;��D$���.o���x$���p8�t:�N����������rX��a5̇C!m4�a�T�Ѩ�U���� }������X���;��d�/?��&quot;)8j 9&lt;N�5_i�&gt;�����q:��W��uso��;��Gn�9�����?�I�V*�@�R�k �,�'_s�sU��X����×/�ZҙLK�R�����&gt;W��vW�Paf���4ꞈ�(����ɢ&gt;���,+T�4¹����VP4ȧ�%o�w�Cmr�Z����9i~Z*f�I��3�*�C��T ٜWV ]��=mr8�R*�GZ�BZ5��&amp;q�R8$�ˣz.�j2)��&gt;���K���H� 2�y4�A����|�&amp;'��jr4�&gt;�ިfT��V�5�?T= }�J�������3�m�&quot;����ɛ�{,����p���/g|]�wY����ov(�H��V[5������rqi�z&gt;Xp���l �x}*y�H��ΒO�r�Z�NG�^��n�7���m�^�����{�����rj�5,��ҹe��;0�]�M�������B ���G�㎅�3X�T��r���v�*�Z#�u4�+nwЪYy�/P ��9�.��jX^�%ϫVq������獒� </code></pre> <p>is there's any way I can display default image in android too?</p>
[ { "answer_id": 74492217, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 0, "selected": false, "text": "import queue\n\na = list(filter(lambda x: len(x) == 1, verbose_struct ))\nb = {x.split('|')[0]: tuple(x.split('|')[1].split(',')) for x in filter(lambda x: len(x) > 1, verbose_struct )}\nnodes = a[:]\nq = queue.deque(b.keys())\nwhile q:\n cur = q.pop()\n if all(map(lambda x: x in nodes, b[cur])):\n nodes.append(cur[0])\n a.append(f\"{cur}|\" + \",\".join(b[cur]))\n else:\n q.appendleft(cur)\n" }, { "answer_id": 74494285, "author": "AirSquid", "author_id": 10789207, "author_profile": "https://Stackoverflow.com/users/10789207", "pm_score": 2, "selected": true, "text": "class __lt__ Element elements sort() # Bayesian Elements\n\nclass Element():\n\n def __init__(self, data: str):\n self.label = data\n if '|' in data:\n # dependency...break it up\n self.base, dependencies = data.split('|')\n # break up the dependencies\n self.dependencies = set(dependencies.split(','))\n else: # it is a single base element\n self.base = data\n self.dependencies = None\n\n def get_dependencies(self):\n return self.dependencies\n\n def get_base(self):\n return self.base\n\n def get_label(self):\n return self.label\n\n def __str__(self):\n return f'base: {self.base}, dep: {self.dependencies}'\n\n def __repr__(self):\n return self.label\n\n # in order to compare class elements, you must create a custom \"less than\" function\n # it is the basis of sort\n def __lt__(self, other: 'Element'):\n # case 1: both are singletons, just alphabetically sort them:\n if self.dependencies is None and other.dependencies is None:\n return self.label < other.label\n # case 2: self has no dependencies, but other does\n elif self.dependencies is None and other.dependencies is not None:\n return True\n # case 3: other has no dependencies, self does\n elif other.dependencies is None and self.dependencies is not None:\n return False\n # case 4: both have dependencies, check if self depends on other:\n else:\n if self.base in other.dependencies:\n return True\n elif other.base in self.dependencies:\n return False\n else: # sort by the base element\n return self.base < other.base\n\ndata = ['B', 'A', 'C|A,E', 'E', 'B|C,D', 'D']\n\n# make \"elements\" from the strings\nelements = [Element(t) for t in data]\n\nelements.sort()\n\nprint(elements)\n\n# example\nprint(elements[4].get_dependencies())\n [A, B, D, E, C|A,E, B|C,D]\n{'A', 'E'}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13546478/" ]
74,491,685
<p>Here is some code:</p> <pre><code>declare const foo: Record&lt;string, number&gt; const x = foo['some-key'] </code></pre> <p>TypeScript says <code>x</code> has type <code>number</code>.</p> <p>It <strong>should</strong> be <code>number | undefined</code>, because there's no guarantee that <code>some-key</code> exists on the object.</p> <p><strong>Why</strong> does TypeScript give this false reassurance, even with <code>strict: true</code>?</p>
[ { "answer_id": 74491842, "author": "geisterfurz007", "author_id": 6707985, "author_profile": "https://Stackoverflow.com/users/6707985", "pm_score": 2, "selected": false, "text": "noUncheckedIndexedAccess strict Record<int, T> Record<string, number> number | undefined string number" }, { "answer_id": 74493611, "author": "geoffrey", "author_id": 8225569, "author_profile": "https://Stackoverflow.com/users/8225569", "pm_score": 0, "selected": false, "text": "number | undefined { [K in MyKeys]: number } Partial<Record<string, number>> PartialRecord type PartialRecord<K extends PropertyKey, T> = { [P in K]?: T }\n Record Record type foo = Record<string, number>;\ntype foo = { [K in string]: number };\ntype foo = { [k: string]: number };\n Record type MyKeys = 'foo' | 'bar' | 'baz';\n\ntype foobar = Record<MyKeys, number>\n\n// same as\ntype foobar = {\n foo: number\n bar: number\n baz: number\n};\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414825/" ]
74,491,687
<p>I'm trying to update an application built with expo + react native and I encounter the last problem.</p> <p>expo.dev <a href="https://i.stack.imgur.com/vzuqo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzuqo.png" alt="enter image description here" /></a></p> <p>Visual Code terminal</p> <pre><code> iOS build failed: Starting from Xcode 14, resource bundles are signed by default, which requires setting the development team for each resource bundle target. To resolve this issue, downgrade to an older Xcode version using the &quot;image&quot; field in eas.json, or turn off signing resource bundles in your Podfile: https://expo.fyi/r/disable-bundle-resource-signing Learn more: https://docs.expo.dev/build-reference/infrastructure/#ios-build-server- configurations </code></pre> <p>I tried to solve this problem by cleaning cache and reinstalling all pods. I went to the permissions in xcode, I tried logging in with an apple developer account but still the same.</p> <p>I tried to see the changes in this link <a href="https://expo.fyi/r/disable-bundle-resource-signing" rel="nofollow noreferrer">https://expo.fyi/r/disable-bundle-resource-signing</a> but it is very different from mine, I made the changes but all app is broken when i try to build.</p> <p>Expo Version: 43.00</p> <p>cocoapods: &quot;1.11.2&quot;</p> <p>eas cli version: &quot;&gt;= 0.38.1&quot;</p> <p>xCode Version: 13.2.1</p> <p>Podfile</p> <pre><code>require File.join(File.dirname(`node --print &quot;require.resolve('expo/package.json')&quot;`), &quot;scripts/autolinking&quot;) require File.join(File.dirname(`node --print &quot;require.resolve('react- native/package.json')&quot;`), &quot;scripts/react_native_pods&quot;) require File.join(File.dirname(`node --print &quot;require.resolve('@react-native- community/cli-platform-ios/package.json')&quot;`), &quot;native_modules&quot;) platform :ios, '12.0' require 'json' podfile_properties = JSON.parse(File.read('./Podfile.properties.json')) rescue {} target 'appName' do use_expo_modules! config = use_native_modules! use_react_native!( :path =&gt; config[:reactNativePath], :hermes_enabled =&gt; podfile_properties['expo.jsEngine'] == 'hermes' ) # Uncomment to opt-in to using Flipper # # if !ENV['CI'] # use_flipper!('Flipper' =&gt; '0.75.1', 'Flipper-Folly' =&gt; '2.5.3', 'Flipper-RSocket' =&gt; '1.3.1') # end post_install do |installer| react_native_post_install(installer) # Workaround `Cycle inside FBReactNativeSpec` error for react-native 0.64 # Reference: https://github.com/software-mansion/react-native-screens/issues/842#issuecomment-812543933 installer.pods_project.targets.each do |target| if (target.name&amp;.eql?('FBReactNativeSpec')) target.build_phases.each do |build_phase| if (build_phase.respond_to?(:name) &amp;&amp; build_phase.name.eql?('[CP-User] Generate Specs')) target.build_phases.move(build_phase, 0) end end end end end end </code></pre> <p>How can i solve this problem in may case?</p>
[ { "answer_id": 74535989, "author": "Pruteanu Alexandru", "author_id": 12403963, "author_profile": "https://Stackoverflow.com/users/12403963", "pm_score": 1, "selected": false, "text": "require File.join(File.dirname(`node --print \"require.resolve('expo/package.json')\"`), \"scripts/autolinking\")\nrequire File.join(File.dirname(`node --print \"require.resolve('react- native/package.json')\"`), \"scripts/react_native_pods\")\nrequire File.join(File.dirname(`node --print \"require.resolve('@react-native-community/cli-platform-ios/package.json')\"`), \"native_modules\")\n\nplatform :ios, '12.0'\n\nrequire 'json'\npodfile_properties = JSON.parse(File.read('./Podfile.properties.json')) \nrescue {}\n\ntarget 'YOUR APP NAME' do\nuse_expo_modules!\nconfig = use_native_modules!\n\nuse_react_native!(\n :path => config[:reactNativePath],\n :hermes_enabled => podfile_properties['expo.jsEngine'] == 'hermes'\n)\n\n# Uncomment to opt-in to using Flipper\n#\n# if !ENV['CI']\n# use_flipper!('Flipper' => '0.75.1', 'Flipper-Folly' => '2.5.3', \n 'Flipper-RSocket' => '1.3.1')\n# end\n\n\npost_install do |installer|\n react_native_post_install(installer)\n # __apply_Xcode_12_5_M1_post_install_workaround(installer)\n\n # This is necessary for Xcode 14, because it signs resource bundles by default\n # when building for devices.\n installer.target_installation_results.pod_target_installation_results\n .each do |pod_name, target_installation_result|\n target_installation_result.resource_bundle_targets.each do |resource_bundle_target|\n resource_bundle_target.build_configurations.each do |config|\n config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'\n end\n end\n end\n end\nend\n" }, { "answer_id": 74571909, "author": "Lonare", "author_id": 1551102, "author_profile": "https://Stackoverflow.com/users/1551102", "pm_score": 0, "selected": false, "text": "cd ios\n\npod deintegrate\n post_install do |installer|\n installer.generated_projects.each do |project|\n project.targets.each do |target|\n target.build_configurations.each do |config|\n config.build_settings[\"DEVELOPMENT_TEAM\"] = \"Your Team ID\"\n end\n end\n end\nend\n post_install do |installer|\n react_native_post_install(installer)\n\n # Workaround `Cycle inside FBReactNativeSpec` error for react-native 0.64\n # Reference: https://github.com/software-mansion/react-native-screens/issues/842#issuecomment-812543933\n installer.pods_project.targets.each do |target|\n if (target.name&.eql?('FBReactNativeSpec'))\n target.build_phases.each do |build_phase|\n if (build_phase.respond_to?(:name) && build_phase.name.eql?('[CP-User] Generate Specs'))\n target.build_phases.move(build_phase, 0)\n end\n end\n end\n end\n installer.generated_projects.each do |project|\n project.targets.each do |target|\n target.build_configurations.each do |config|\n config.build_settings[\"DEVELOPMENT_TEAM\"] = \"YOUR TEAM ID\"\n end\n end\n end\n end\n pod install\n\npod update\n\ncd ..\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12403963/" ]
74,491,713
<p>What is the usage of tilde symbol (~) in Oracle. Please share me the output for the below query if we are using the column name and table name with two tilde symbols.</p> <p><strong>SELECT ~column_name~ from ~Table_name~</strong></p>
[ { "answer_id": 74495884, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "_ $ # . @ $ # \\0 SELECT ~column_name~ from ~Table_name~\n ~column_name~ ~Table_name~ \" ~ _ $ # ORA-00911: invalid character\n" }, { "answer_id": 74503502, "author": "Jon Heller", "author_id": 409172, "author_profile": "https://Stackoverflow.com/users/409172", "pm_score": 0, "selected": false, "text": "begin\n if 1 ~= 2 then\n dbms_output.put_line('Not equal');\n end if;\nend;\n/\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12517359/" ]
74,491,723
<p>Let's say I have this script:</p> <pre><code>const BusInfo = [ { code: &quot;B31&quot;, destination: &quot;Toronto&quot; }, { code: &quot;HJ1&quot;, destination: &quot;Montreal&quot; } ] </code></pre> <p>How would I be able to put that information in my html document? I cannot change the above script at all. I am having issue doing this, I have tried googling but there isn't much information on how to do that or I am just having trouble comprehending. Also, how would I be able to style this in css?</p> <p>I have already called for the script in my index.html, but I am having trouble showing that information. One of the problems am having with is not being able to edit that script at all. I have to keep it like that.</p>
[ { "answer_id": 74493148, "author": "TheBugCoder", "author_id": 18866858, "author_profile": "https://Stackoverflow.com/users/18866858", "pm_score": 0, "selected": false, "text": "<p id=\"destination\">Destination</p> document.querySelector('#destination').textContent = BusInfo.destination;\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20305399/" ]
74,491,739
<p>I am trying to make a program, that tells me when a note has been pressed.</p> <p>I have the following notes exported as a <code>.wav</code> file <em>(The C Major Scale 4 times with different rhythms, dynamics and in different octaves)</em>: <a href="https://i.stack.imgur.com/bDlBz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bDlBz.png" alt="enter image description here" /></a></p> <p>I can get the volumes of my sound file using the following code:</p> <pre><code>from scipy.io import wavfile def get_volume(file): sr, data = wavfile.read(file) if data.ndim &gt; 1: data = data[:, 0] return data volumes = get_volume(&quot;FILE&quot;) </code></pre> <p>Here are some information about the output:</p> <pre><code>Max: 27851 Min: -25664 Mean: -0.7569383391943734 A Sample from the array: [ -7987 -8615 -8983 -9107 -9019 -8750 -8324 -7752 -7033 -6156 -5115 -3920 -2610 -1245 106 1377 2520 3515 4364 5077 5659 6113 6441 6639 6708 6662 6518 6288 5962 5525 4963 4265 3420 2418 1264 -27 -1429 -2901 -4388 -5814 -7101 -8186 -9028 -9614 -9955 -10077 -10012 -9785 -9401 -8846] </code></pre> <p>And here is what I get when I plot the volumes array (x is the index, y is the volume): <a href="https://i.stack.imgur.com/ar68f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ar68f.png" alt="enter image description here" /></a></p> <p>I want to get the indices of the start and end of the notes like the ones in the image (Did it by hand not accurate): <a href="https://i.stack.imgur.com/GfhhM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GfhhM.jpg" alt="enter image description here" /></a></p> <p>When I looked at the data I realized, that it is a 1d array and I also noticed, that when a note gets louder or quiter it is not smooth. It is like a ZigZag, but there is still a trend. So basically I can't just get the gradients (slope) of each point. So I though about grouping notes into batches and getting the average gradient there and thus doing the calculations with it, like so:</p> <pre><code>def get_average_gradient(arr): # Calculates average gradient return sum([i - (sum(arr) / len(arr)) for i in arr]) / len(arr) def get_note_start_end(arr_size, batch_size, arr): # Finds start and end indices ranges = [] curr_range = [0] prev_slope = curr_slope = &quot;NO SLOPE&quot; has_ended = False for i, j in enumerate(arr): if j &gt; 0: curr_slope = &quot;INCREASING&quot; elif j &lt; 0: curr_slope = &quot;DECREASING&quot; else: curr_slope = &quot;NO SLOPE&quot; if prev_slope == &quot;DECREASING&quot; and not has_ended: if i == len(arr) - 1 or arr[i + 1] &lt; 0: if curr_slope != &quot;DECREASING&quot;: curr_range.append((i + 1) * batch_size + batch_size) ranges.append(curr_range) curr_range = [(i + 1) * batch_size + batch_size + 1] has_ended = True if has_ended and curr_slope == &quot;INCREASING&quot;: has_ended = False prev_slope = curr_slope ranges[-1][-1] = arr_size - 1 return ranges def get_notes(batch_size, arr): # Gets the gradients of the batches out = [] for i in range(0, len(arr), batch_size): if i + batch_size &gt; len(arr): gradient = get_average_gradient(arr[i:]) else: gradient = get_average_gradient(arr[i: i+batch_size]) # print(gradient, i) out.append(gradient) return get_note_start_end(len(arr), batch_size, out) notes = get_notes(128, volumes) </code></pre> <p>The problem with this is, that if the batch size is too small, then it returns the indices of small peaks, which aren't a note on their own. If the batch size is too big then the program misses the start and end indices.</p> <p>I also tried to get the notes, by using the silence. Here is the code I used:</p> <pre><code>from pydub import AudioSegment, silence audio = intro = AudioSegment.from_wav(&quot;C - Major - Test.wav&quot;) dBFS = audio.dBFS notes = silence.detect_nonsilent(audio, min_silence_len=50, silence_thresh=dBFS-10) </code></pre> <p>This worked the best, but it still wasn't good enough. Here is what I got: <a href="https://i.stack.imgur.com/A5Iqc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A5Iqc.png" alt="enter image description here" /></a></p> <p>It some notes pretty well, but it wasn't able to identify notes accurately if the notes themselves didn't become very quite before a different one was played (Like in the second scale and in the fourth scale).</p> <p>I have been thinking about this problem for days and I have basically tried most if not all of the good(?) ideas I had. I am new to analysing audio files. Maybe I am using the wrong data to do what I want to do. Maybe I need to use the frequency data (I tried getting it, but couldn't make sense of it) Frequency code:</p> <pre><code>from scipy.fft import * from scipy.io import wavfile import matplotlib.pyplot as plt def get_freq(file, start_time, end_time): sr, data = wavfile.read(file) if data.ndim &gt; 1: data = data[:, 0] else: pass # Fourier Transform N = len(data) yf = rfft(data) xf = rfftfreq(N, 1 / sr) return xf, yf FILE = &quot;C - Major - Test.wav&quot; plt.plot(*get_freq(FILE, 0, 10)) plt.show() </code></pre> <p>And the frequency graph: <a href="https://i.stack.imgur.com/fJu5h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fJu5h.png" alt="enter image description here" /></a></p> <p>And here is the .wav file: <a href="https://drive.google.com/file/d/1CERH-eovu20uhGoV1_O3B2Ph-4-uXpiP/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1CERH-eovu20uhGoV1_O3B2Ph-4-uXpiP/view?usp=sharing</a></p> <p>Any help is appreciated :)</p>
[ { "answer_id": 74493148, "author": "TheBugCoder", "author_id": 18866858, "author_profile": "https://Stackoverflow.com/users/18866858", "pm_score": 0, "selected": false, "text": "<p id=\"destination\">Destination</p> document.querySelector('#destination').textContent = BusInfo.destination;\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13984609/" ]
74,491,748
<p>I would like to merge two columns into one but I am not sure how to do this efficiently. My df looks like this:</p> <pre><code>col1 col2 0.4 -0.9 0.2 -0.5 -0.1 0.2 -0.2 0.4 0.8 -0.6 </code></pre> <p>So if one column is positive, the other one is always negative. But I would like to have all negative numbers from column 1 replaced by all positive numbers from column 2. So it would look like this:</p> <pre><code>col1 0.4 0.2 0.2 0.4 0.8 </code></pre> <p>If you know an efficient solution to this I would really appreciate it!!</p>
[ { "answer_id": 74491844, "author": "Rabinzel", "author_id": 15521392, "author_profile": "https://Stackoverflow.com/users/15521392", "pm_score": 2, "selected": false, "text": "col2 m = df['col1'] < 0 \ndf['col1'] = df['col1'].mask(m).fillna(df['col2'])\nprint(df)\n col1 col2\n0 0.4 -0.9\n1 0.2 -0.5\n2 0.2 0.2\n3 0.4 0.4\n4 0.8 -0.6\n" }, { "answer_id": 74491899, "author": "sophocles", "author_id": 9167382, "author_profile": "https://Stackoverflow.com/users/9167382", "pm_score": 3, "selected": true, "text": "df.loc[df['col1'] < 0, 'col1'] = df['col2']\n col1 col2\n0 0.4 -0.9\n1 0.2 -0.5\n2 0.2 0.2\n3 0.4 0.4\n4 0.8 -0.6\n" }, { "answer_id": 74491908, "author": "Umar.H", "author_id": 9375102, "author_profile": "https://Stackoverflow.com/users/9375102", "pm_score": 0, "selected": false, "text": "df.where .drop df_new = df.where(df['col1'].ge(0),df['col2'],axis=0).drop('col2',axis=1)\n\nprint(df_new)\n\n\n col1\n0 0.4\n1 0.2\n2 0.2\n3 0.4\n4 0.8\n" }, { "answer_id": 74491929, "author": "emilyisstewpid", "author_id": 19940541, "author_profile": "https://Stackoverflow.com/users/19940541", "pm_score": -1, "selected": false, "text": "df[\"col1\"] = df.apply(lambda row: max(row.col1, row.col2), axis=1)\ndf = df.drop(\"col2\", axis=1)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20127965/" ]
74,491,756
<p>apologies in advance if this question is stupid but:</p> <p>I have an interface:</p> <pre><code>template &lt;class T&gt; class IEqualCompare { public: virtual bool IsEqual(const T b) = 0; bool operator== (const T b) { return this-&gt;IsEqual(b); } //Both are implemented in cpp file bool operator!= (const T b) { return !(this-&gt;IsEqual(b)); } }; </code></pre> <p>And a class:</p> <pre><code>class Dimentions : IEqualCompare&lt;Dimentions&gt; { ... bool IsEqual(const Dimentions b) { //IsEqual logic for this specific class } ... } </code></pre> <p>I would like to only implement <code>IsEqual</code> method for each child class of <code>IEqualCompare</code>, as the logic within the operator overloads (==, !=) is the same for any <code>IEqualCompare</code> derived class.</p> <p>Up until now I have always simply defined both operator overrides as virtual and implemented them inside each class, but as the logic should be always the same I wanted to know if this is possible or is it bad programming.</p> <p>Thanks in advance for any answers.</p>
[ { "answer_id": 74494672, "author": "YurkoFlisk", "author_id": 3162368, "author_profile": "https://Stackoverflow.com/users/3162368", "pm_score": 1, "selected": false, "text": "IsEqual const IsEqual IsEqual T this T* IsEqual T template<typename T>\nclass AddEqualComparisons {\npublic:\n bool operator==(const T& b) const { return static_cast<T*>(this)->IsEqual(b); }\n bool operator!=(const T& b) const { return !static_cast<T*>(this)->IsEqual(b); }\n};\n\nclass Dimensions : public AddEqualComparisons<Dimensions> {\n bool IsEqual(const Dimensions& rhs) const {\n // ...\n }\n};\n" }, { "answer_id": 74503390, "author": "sigma", "author_id": 1719926, "author_profile": "https://Stackoverflow.com/users/1719926", "pm_score": 0, "selected": false, "text": "operator!= operator== !(x == y) class Foo {\n friend bool operator==(Foo const&, Foo const&) = default; \n};\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540421/" ]
74,491,765
<p>I am probably facing a basic problem. I would like to create TimePickers as in this project link: <a href="https://sourceforge.net/projects/time-picker/" rel="nofollow noreferrer">TimePickerProject</a></p> <p>This project was given as reference in one of the Stack overflow answers <a href="https://stackoverflow.com/a/32057537/5384988">Stack OverflowAnswer</a></p> <p>You can download and directly run that project really easy. But couldn't add it to my own project as an independent TimerPicker Object. TimePicker class is inside Opulos folder. As you can see Opulos folder is copy pasted to my own project.</p> <p>I <a href="https://i.stack.imgur.com/QJYRQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QJYRQ.png" alt="enter image description here" /></a></p> <p>And I can see that Timepicker inside my toolbox.</p> <p><a href="https://i.stack.imgur.com/mpQEN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mpQEN.png" alt="enter image description here" /></a></p> <p>But when I try to drag it to my panel I am facing with this error.</p> <p><a href="https://i.stack.imgur.com/UkLAe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UkLAe.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74515179, "author": "Jiale Xue - MSFT", "author_id": 16764901, "author_profile": "https://Stackoverflow.com/users/16764901", "pm_score": 3, "selected": true, "text": "Opulos folder Opulos/Core/UI/TimePicker.cs public TimePicker() :this(3, true, true, true, true) {\n\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5384988/" ]
74,491,769
<p>I have homework that asks me to use a .class file for my project, but I don't know how to use those files in a .java file. This is the project structure</p> <pre><code>agentes.class datos_confidenciales.class II_Parcial_2007_1.doc Main.java numeros.class </code></pre> <p>I mean, I got to make a class called <code>Main</code> that implements the <code>numeros interface</code>, the numeros interface is in <code>numeros.class</code> file</p> <p>I've googled but no results.</p>
[ { "answer_id": 74492037, "author": "MJG", "author_id": 20283130, "author_profile": "https://Stackoverflow.com/users/20283130", "pm_score": -1, "selected": false, "text": "numeros" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13542764/" ]
74,491,785
<p>Every time I dump my structure.sql on a rails app, I get PROCEDURE over FUNCTION. FUNCTION is our default and I have to commit the file in parts which is annoying and sometimes I miss lines which is even worse, as it is a rather big structure.sql file.</p> <p>git diff example:</p> <pre><code>-CREATE TRIGGER cache_comments_count AFTER INSERT OR DELETE OR UPDATE ON public.comments FOR EACH ROW EXECUTE PROCEDURE public.update_comments_counter(); +CREATE TRIGGER cache_comments_count AFTER INSERT OR DELETE OR UPDATE ON public.comments FOR EACH ROW EXECUTE FUNCTION public.update_comments_counter(); </code></pre> <p>I'm sure there is a postgresql setting for this somewhere, but I can't find it.</p>
[ { "answer_id": 74492037, "author": "MJG", "author_id": 20283130, "author_profile": "https://Stackoverflow.com/users/20283130", "pm_score": -1, "selected": false, "text": "numeros" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3920497/" ]
74,491,796
<p>I like to make a somewhat easy calculation on the rows of my data frame and used to use <code>.iterrows()</code> but the the operation is very slow. Now I wonder if I can use <code>.apply()</code> to achieve the same thing to get it done faster. It could also be that there is a totally differnt option, which I'm just not aware of or have not thought about.</p> <p>Here is what I want to do: Assuming the following dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>ID_1</th> <th>ID_2</th> <th>...</th> <th>ID_n</th> <th>mean</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>10</td> <td>15</td> <td>...</td> <td>12</td> <td>7</td> </tr> <tr> <td>1</td> <td>20</td> <td>10</td> <td>...</td> <td>17</td> <td>21</td> </tr> </tbody> </table> </div> <p>I like to check for each row which element is larger than the mean of the entire row (already given in the mean column). If the value is larger I like to get the part of the ID after the <code>_</code> (column name) for this entry and finally sum up all the values that are larger than the row mean and safe it to a new column.</p> <p>Thanks for any help.</p> <p>I already tried to use <code>df.apply(lamda row: my_func(row), axis=1)</code></p> <pre><code> def my_func(x): id = str(x.index) if x[x.name] &gt; (df['mean'].iloc[x.name]): sum( x ) </code></pre>
[ { "answer_id": 74491952, "author": "kakben", "author_id": 5550697, "author_profile": "https://Stackoverflow.com/users/5550697", "pm_score": 2, "selected": false, "text": "d = np.array([ [10,15,12,7],\n [20,10,17,21]])\ndf = pd.DataFrame(d, columns=[\"ID_1\",\"ID_2\",\"ID_3\",\"mean\"])\n\nN = 3\n\ndef my_func(row):\n s = 0\n for i in range(1,N+1):\n if row[f\"ID_{i}\"] > row[\"mean\"]:\n s += row[f\"ID_{i}\"]\n\n return s\n\ndf[\"sum_lrgr_mean\"] = df.apply(lambda row: my_func(row), axis=1)\ndf\n" }, { "answer_id": 74492080, "author": "kakben", "author_id": 5550697, "author_profile": "https://Stackoverflow.com/users/5550697", "pm_score": 1, "selected": false, "text": "N = np.array(\n [\n [10, 15, 12],\n [20, 10, 17]\n ]\n)\nM = np.array(\n [\n [7],\n [21]\n ]\n)\n\nnp.sum(N*(N>M),axis=1)\n array([37, 0])\n" }, { "answer_id": 74492104, "author": "Umar.H", "author_id": 9375102, "author_profile": "https://Stackoverflow.com/users/9375102", "pm_score": 2, "selected": true, "text": ".melt .loc .groupby .join #we need the index to rejoin later\ndf1 = pd.melt(df,id_vars='mean',ignore_index=False).reset_index()\n\ncon = df1['value'].gt(df1['mean']) # your conditional.\n\ndf_new = df.join(df1.loc[con].assign(_id=df1['variable'].str.split('_').str[1]\n ).groupby('index')\\\n .agg(_id=('_id',list),computed_mean=('value','sum')) \n )\n print(df_new)\n\n ID_1 ID_2 ID_n mean _id computed_mean\n0 10 15 12 7 [1, 2, n] 37.0\n1 20 10 17 21 NaN NaN\n df1 con index mean variable value\n0 0 7 ID_1 10\n1 1 21 ID_1 20\n2 0 7 ID_2 15\n3 1 21 ID_2 10\n4 0 7 ID_n 12\n5 1 21 ID_n 17\n\n\nprint(con)\n\n0 True\n1 False\n2 True\n3 False\n4 True\n5 False\ndtype: bool\n IDs sum mask df['computed_mean'] = df.mask(df.lt(df['mean'],axis=0)).drop('mean',axis=1).sum(axis=1)\n\n ID_1 ID_2 ID_n mean computed_mean\n0 10 15 12 7 37.0\n1 20 10 17 21 0.0\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12467446/" ]
74,491,820
<p>It should take multiple words and output a combined version, where each word is separated by a dollar sign $.</p> <p>For example, for the words &quot;hello&quot;, &quot;how&quot;, &quot;are&quot;, &quot;you&quot;, the output should be &quot;$hello$how$are$you$&quot;.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class Add { constructor(...words) { this.words = words; } all(){console.log('$'+ this.words)}; } var x = new Add("hehe", "hoho", "haha", "hihi", "huhu"); var y = new Add("this", "is", "awesome"); var z = new Add("lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit"); x.all();</code></pre> </div> </div> </p> <p>output <code>$hehe,hoho,haha,hihi,huhu</code></p> <p>expected output</p> <pre><code>$hehe$hoho$haha$hihi$huhu$ $this$is$awesome$ $lorem$ipsum$dolor$sit$amet$consectetur$adipiscing$elit$ </code></pre>
[ { "answer_id": 74492003, "author": "mplungjan", "author_id": 295783, "author_profile": "https://Stackoverflow.com/users/295783", "pm_score": 1, "selected": false, "text": "Array.join class Add {\n constructor(...words) {\n this.words = words;\n }\n all() {\n const output = this.words?.length ? `$${this.words.join(\"$\")}$` : \"No input\";\n console.log(output)\n };\n}\n\nvar x = new Add(\"hehe\", \"hoho\", \"haha\", \"hihi\", \"huhu\");\nvar y = new Add(\"this\", \"is\", \"awesome\");\nvar z = new Add(\"lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet\", \"consectetur\", \"adipiscing\", \"elit\");\nvar nope = new Add()\nx.all();\ny.all();\nz.all();\nnope.all();" }, { "answer_id": 74492081, "author": "CRuizH", "author_id": 16497843, "author_profile": "https://Stackoverflow.com/users/16497843", "pm_score": 0, "selected": false, "text": "this.words class Add {\n constructor(...words) {\n this.words = words;\n }\n all() {\n let newString = \"\";\n for (let word of this.words) {\n newString += \"$\" + word;\n }\n console.log(newString + \"$\");\n }\n}\n\nvar x = new Add(\"hehe\", \"hoho\", \"haha\", \"hihi\", \"huhu\");\n\nx.all();" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540744/" ]
74,491,840
<p>i have added a second 2 ssh keys and added the needed config in ubuntu WSL2 ~/.ssh</p> <pre><code> Host github-key2 HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/key2 </code></pre> <p>so in UBUNTU this works:</p> <pre><code> git clone git@github-key2:vendor/repoxxx.git </code></pre> <p>But i need to geht this running in ddev with composer:</p> <p>I added git@github-key2:vendor/repoxxx.git in the repositories section of composer in same Way i did it for other protected repos</p> <pre><code> &quot;vendor/repoxxx&quot;: { &quot;type&quot;: &quot;vcs&quot;, &quot;url&quot;: &quot;git@github-key2:vendor/repoxxx&quot; } </code></pre> <p>ddev auth ssh (both keys where added)</p> <p>but composer in DDEV just uses the normal &quot;id_rsa&quot; key but not the second &quot;key2&quot;</p> <pre><code> ddev composer req vendor/repoxxx </code></pre>
[ { "answer_id": 74507228, "author": "hakre", "author_id": 367456, "author_profile": "https://Stackoverflow.com/users/367456", "pm_score": -1, "selected": false, "text": "vendor-dir vendor platform composer.json" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1970576/" ]
74,491,843
<p>Can someone please help me return the highest speed (69) from the following Json array using javascript. Thanks</p> <pre class="lang-json prettyprint-override"><code> [ { &quot;imei&quot;: &quot;1234567&quot;, &quot;data_bucket&quot;: &quot;19314&quot;, &quot;timestamp&quot;: &quot;2022-11-18T13:51:28.000Z&quot;, &quot;acc_state&quot;: 1, &quot;altitude&quot;: 57, &quot;analogue_1&quot;: 0, &quot;analogue_2&quot;: 0, &quot;analogue_3&quot;: 0, &quot;analogue_4&quot;: 0, &quot;angle&quot;: 258, &quot;battery&quot;: 74, &quot;battery_current&quot;: 0, &quot;battery_voltage&quot;: 3859, &quot;button_id&quot;: 0, &quot;cell_id&quot;: 0, &quot;cid&quot;: &quot;&quot;, &quot;dallas_temperature_1&quot;: 0, &quot;dallas_temperature_2&quot;: 0, &quot;dallas_temperature_3&quot;: 0, &quot;device_type&quot;: &quot;FMBXXX&quot;, &quot;digital_1&quot;: false, &quot;digital_2&quot;: false, &quot;digital_3&quot;: false, &quot;digital_4&quot;: false, &quot;digital_output_1&quot;: 0, &quot;digital_output_2&quot;: 1, &quot;eco_score&quot;: 1000, &quot;external_power_voltage&quot;: 0, &quot;green_driving_type&quot;: 0, &quot;green_driving_value&quot;: 0, &quot;gsensor_state&quot;: 0, &quot;hdop&quot;: 6, &quot;ibutton_id&quot;: &quot;&quot;, &quot;id&quot;: &quot;1ba11080-6748-11ed-b708-1566bdff1367&quot;, &quot;lac&quot;: &quot;&quot;, &quot;lat&quot;: &quot;51.5390166&quot;, &quot;location_type&quot;: &quot;GPS&quot;, &quot;long&quot;: &quot;-3.5989166&quot;, &quot;movement&quot;: 0, &quot;movement_sensor&quot;: 1, &quot;pdop&quot;: 10, &quot;relay_state&quot;: 0, &quot;roaming&quot;: 0, &quot;satellites&quot;: 21, &quot;signal&quot;: 3, &quot;speed&quot;: 48, &quot;vdop&quot;: 0 }, { &quot;imei&quot;: &quot;1234567&quot;, &quot;data_bucket&quot;: &quot;19314&quot;, &quot;timestamp&quot;: &quot;2022-11-18T13:51:31.000Z&quot;, &quot;acc_state&quot;: 1, &quot;altitude&quot;: 56, &quot;analogue_1&quot;: 0, &quot;analogue_2&quot;: 0, &quot;analogue_3&quot;: 0, &quot;analogue_4&quot;: 0, &quot;angle&quot;: 258, &quot;battery&quot;: 72, &quot;battery_current&quot;: 0, &quot;battery_voltage&quot;: 3851, &quot;button_id&quot;: 0, &quot;cell_id&quot;: 0, &quot;cid&quot;: &quot;&quot;, &quot;dallas_temperature_1&quot;: 0, &quot;dallas_temperature_2&quot;: 0, &quot;dallas_temperature_3&quot;: 0, &quot;device_type&quot;: &quot;FMBXXX&quot;, &quot;digital_1&quot;: false, &quot;digital_2&quot;: false, &quot;digital_3&quot;: false, &quot;digital_4&quot;: false, &quot;digital_output_1&quot;: 0, &quot;digital_output_2&quot;: 1, &quot;eco_score&quot;: 1000, &quot;external_power_voltage&quot;: 0, &quot;green_driving_type&quot;: 0, &quot;green_driving_value&quot;: 0, &quot;gsensor_state&quot;: 0, &quot;hdop&quot;: 6, &quot;ibutton_id&quot;: &quot;&quot;, &quot;id&quot;: &quot;1dbbda30-6748-11ed-8164-c3bac4dd9d98&quot;, &quot;lac&quot;: &quot;&quot;, &quot;lat&quot;: &quot;51.5389416&quot;, &quot;location_type&quot;: &quot;GPS&quot;, &quot;long&quot;: &quot;-3.5995583&quot;, &quot;movement&quot;: 0, &quot;movement_sensor&quot;: 1, &quot;pdop&quot;: 11, &quot;relay_state&quot;: 0, &quot;roaming&quot;: 0, &quot;satellites&quot;: 19, &quot;signal&quot;: 3, &quot;speed&quot;: 60, &quot;vdop&quot;: 0 }, { &quot;imei&quot;: &quot;1234567&quot;, &quot;data_bucket&quot;: &quot;19314&quot;, &quot;timestamp&quot;: &quot;2022-11-18T13:51:41.000Z&quot;, &quot;acc_state&quot;: 1, &quot;altitude&quot;: 56, &quot;analogue_1&quot;: 0, &quot;analogue_2&quot;: 0, &quot;analogue_3&quot;: 0, &quot;analogue_4&quot;: 0, &quot;angle&quot;: 264, &quot;battery&quot;: 74, &quot;battery_current&quot;: 0, &quot;battery_voltage&quot;: 3864, &quot;button_id&quot;: 0, &quot;cell_id&quot;: 0, &quot;cid&quot;: &quot;&quot;, &quot;dallas_temperature_1&quot;: 0, &quot;dallas_temperature_2&quot;: 0, &quot;dallas_temperature_3&quot;: 0, &quot;device_type&quot;: &quot;FMBXXX&quot;, &quot;digital_1&quot;: false, &quot;digital_2&quot;: false, &quot;digital_3&quot;: false, &quot;digital_4&quot;: false, &quot;digital_output_1&quot;: 0, &quot;digital_output_2&quot;: 1, &quot;eco_score&quot;: 1000, &quot;external_power_voltage&quot;: 0, &quot;green_driving_type&quot;: 0, &quot;green_driving_value&quot;: 0, &quot;gsensor_state&quot;: 0, &quot;hdop&quot;: 7, &quot;ibutton_id&quot;: &quot;&quot;, &quot;id&quot;: &quot;239ad7d0-6748-11ed-9ef4-6df3685640ee&quot;, &quot;lac&quot;: &quot;&quot;, &quot;lat&quot;: &quot;51.53868&quot;, &quot;location_type&quot;: &quot;GPS&quot;, &quot;long&quot;: &quot;-3.6022&quot;, &quot;movement&quot;: 0, &quot;movement_sensor&quot;: 1, &quot;pdop&quot;: 12, &quot;relay_state&quot;: 0, &quot;roaming&quot;: 0, &quot;satellites&quot;: 20, &quot;signal&quot;: 3, &quot;speed&quot;: 69, &quot;vdop&quot;: 0 } ] </code></pre> <p>I've been looking at these <a href="https://stackoverflow.com/questions/22949597/getting-max-values-in-json-array">examples </a>for getting the max value from a JSon array.</p>
[ { "answer_id": 74492059, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "let max = Math.max(...json.map((items)=> items.speed))\nconsole.log(max);\n const json = [\n {\n \"imei\": \"1234567\",\n \"data_bucket\": \"19314\",\n \"timestamp\": \"2022-11-18T13:51:28.000Z\",\n \"acc_state\": 1,\n \"altitude\": 57,\n \"analogue_1\": 0,\n \"analogue_2\": 0,\n \"analogue_3\": 0,\n \"analogue_4\": 0,\n \"angle\": 258,\n \"battery\": 74,\n \"battery_current\": 0,\n \"battery_voltage\": 3859,\n \"button_id\": 0,\n \"cell_id\": 0,\n \"cid\": \"\",\n \"dallas_temperature_1\": 0,\n \"dallas_temperature_2\": 0,\n \"dallas_temperature_3\": 0,\n \"device_type\": \"FMBXXX\",\n \"digital_1\": false,\n \"digital_2\": false,\n \"digital_3\": false,\n \"digital_4\": false,\n \"digital_output_1\": 0,\n \"digital_output_2\": 1,\n \"eco_score\": 1000,\n \"external_power_voltage\": 0,\n \"green_driving_type\": 0,\n \"green_driving_value\": 0,\n \"gsensor_state\": 0,\n \"hdop\": 6,\n \"ibutton_id\": \"\",\n \"id\": \"1ba11080-6748-11ed-b708-1566bdff1367\",\n \"lac\": \"\",\n \"lat\": \"51.5390166\",\n \"location_type\": \"GPS\",\n \"long\": \"-3.5989166\",\n \"movement\": 0,\n \"movement_sensor\": 1,\n \"pdop\": 10,\n \"relay_state\": 0,\n \"roaming\": 0,\n \"satellites\": 21,\n \"signal\": 3,\n \"speed\": 48,\n \"vdop\": 0\n },\n {\n \"imei\": \"1234567\",\n \"data_bucket\": \"19314\",\n \"timestamp\": \"2022-11-18T13:51:31.000Z\",\n \"acc_state\": 1,\n \"altitude\": 56,\n \"analogue_1\": 0,\n \"analogue_2\": 0,\n \"analogue_3\": 0,\n \"analogue_4\": 0,\n \"angle\": 258,\n \"battery\": 72,\n \"battery_current\": 0,\n \"battery_voltage\": 3851,\n \"button_id\": 0,\n \"cell_id\": 0,\n \"cid\": \"\",\n \"dallas_temperature_1\": 0,\n \"dallas_temperature_2\": 0,\n \"dallas_temperature_3\": 0,\n \"device_type\": \"FMBXXX\",\n \"digital_1\": false,\n \"digital_2\": false,\n \"digital_3\": false,\n \"digital_4\": false,\n \"digital_output_1\": 0,\n \"digital_output_2\": 1,\n \"eco_score\": 1000,\n \"external_power_voltage\": 0,\n \"green_driving_type\": 0,\n \"green_driving_value\": 0,\n \"gsensor_state\": 0,\n \"hdop\": 6,\n \"ibutton_id\": \"\",\n \"id\": \"1dbbda30-6748-11ed-8164-c3bac4dd9d98\",\n \"lac\": \"\",\n \"lat\": \"51.5389416\",\n \"location_type\": \"GPS\",\n \"long\": \"-3.5995583\",\n \"movement\": 0,\n \"movement_sensor\": 1,\n \"pdop\": 11,\n \"relay_state\": 0,\n \"roaming\": 0,\n \"satellites\": 19,\n \"signal\": 3,\n \"speed\": 60,\n \"vdop\": 0\n },\n {\n \"imei\": \"1234567\",\n \"data_bucket\": \"19314\",\n \"timestamp\": \"2022-11-18T13:51:41.000Z\",\n \"acc_state\": 1,\n \"altitude\": 56,\n \"analogue_1\": 0,\n \"analogue_2\": 0,\n \"analogue_3\": 0,\n \"analogue_4\": 0,\n \"angle\": 264,\n \"battery\": 74,\n \"battery_current\": 0,\n \"battery_voltage\": 3864,\n \"button_id\": 0,\n \"cell_id\": 0,\n \"cid\": \"\",\n \"dallas_temperature_1\": 0,\n \"dallas_temperature_2\": 0,\n \"dallas_temperature_3\": 0,\n \"device_type\": \"FMBXXX\",\n \"digital_1\": false,\n \"digital_2\": false,\n \"digital_3\": false,\n \"digital_4\": false,\n \"digital_output_1\": 0,\n \"digital_output_2\": 1,\n \"eco_score\": 1000,\n \"external_power_voltage\": 0,\n \"green_driving_type\": 0,\n \"green_driving_value\": 0,\n \"gsensor_state\": 0,\n \"hdop\": 7,\n \"ibutton_id\": \"\",\n \"id\": \"239ad7d0-6748-11ed-9ef4-6df3685640ee\",\n \"lac\": \"\",\n \"lat\": \"51.53868\",\n \"location_type\": \"GPS\",\n \"long\": \"-3.6022\",\n \"movement\": 0,\n \"movement_sensor\": 1,\n \"pdop\": 12,\n \"relay_state\": 0,\n \"roaming\": 0,\n \"satellites\": 20,\n \"signal\": 3,\n \"speed\": 69,\n \"vdop\": 0\n }\n];\n\nlet max = Math.max(...json.map((items)=> items.speed))\nconsole.log(max);" }, { "answer_id": 74492140, "author": "Terry Lennox", "author_id": 7237224, "author_profile": "https://Stackoverflow.com/users/7237224", "pm_score": -1, "selected": false, "text": "Array.map() Math.max() const data = [ { \"imei\": \"1234567\", \"data_bucket\": \"19314\", \"timestamp\": \"2022-11-18T13:51:28.000Z\", \"acc_state\": 1, \"altitude\": 57, \"analogue_1\": 0, \"analogue_2\": 0, \"analogue_3\": 0, \"analogue_4\": 0, \"angle\": 258, \"battery\": 74, \"battery_current\": 0, \"battery_voltage\": 3859, \"button_id\": 0, \"cell_id\": 0, \"cid\": \"\", \"dallas_temperature_1\": 0, \"dallas_temperature_2\": 0, \"dallas_temperature_3\": 0, \"device_type\": \"FMBXXX\", \"digital_1\": false, \"digital_2\": false, \"digital_3\": false, \"digital_4\": false, \"digital_output_1\": 0, \"digital_output_2\": 1, \"eco_score\": 1000, \"external_power_voltage\": 0, \"green_driving_type\": 0, \"green_driving_value\": 0, \"gsensor_state\": 0, \"hdop\": 6, \"ibutton_id\": \"\", \"id\": \"1ba11080-6748-11ed-b708-1566bdff1367\", \"lac\": \"\", \"lat\": \"51.5390166\", \"location_type\": \"GPS\", \"long\": \"-3.5989166\", \"movement\": 0, \"movement_sensor\": 1, \"pdop\": 10, \"relay_state\": 0, \"roaming\": 0, \"satellites\": 21, \"signal\": 3, \"speed\": 48, \"vdop\": 0 }, { \"imei\": \"1234567\", \"data_bucket\": \"19314\", \"timestamp\": \"2022-11-18T13:51:31.000Z\", \"acc_state\": 1, \"altitude\": 56, \"analogue_1\": 0, \"analogue_2\": 0, \"analogue_3\": 0, \"analogue_4\": 0, \"angle\": 258, \"battery\": 72, \"battery_current\": 0, \"battery_voltage\": 3851, \"button_id\": 0, \"cell_id\": 0, \"cid\": \"\", \"dallas_temperature_1\": 0, \"dallas_temperature_2\": 0, \"dallas_temperature_3\": 0, \"device_type\": \"FMBXXX\", \"digital_1\": false, \"digital_2\": false, \"digital_3\": false, \"digital_4\": false, \"digital_output_1\": 0, \"digital_output_2\": 1, \"eco_score\": 1000, \"external_power_voltage\": 0, \"green_driving_type\": 0, \"green_driving_value\": 0, \"gsensor_state\": 0, \"hdop\": 6, \"ibutton_id\": \"\", \"id\": \"1dbbda30-6748-11ed-8164-c3bac4dd9d98\", \"lac\": \"\", \"lat\": \"51.5389416\", \"location_type\": \"GPS\", \"long\": \"-3.5995583\", \"movement\": 0, \"movement_sensor\": 1, \"pdop\": 11, \"relay_state\": 0, \"roaming\": 0, \"satellites\": 19, \"signal\": 3, \"speed\": 60, \"vdop\": 0 }, { \"imei\": \"1234567\", \"data_bucket\": \"19314\", \"timestamp\": \"2022-11-18T13:51:41.000Z\", \"acc_state\": 1, \"altitude\": 56, \"analogue_1\": 0, \"analogue_2\": 0, \"analogue_3\": 0, \"analogue_4\": 0, \"angle\": 264, \"battery\": 74, \"battery_current\": 0, \"battery_voltage\": 3864, \"button_id\": 0, \"cell_id\": 0, \"cid\": \"\", \"dallas_temperature_1\": 0, \"dallas_temperature_2\": 0, \"dallas_temperature_3\": 0, \"device_type\": \"FMBXXX\", \"digital_1\": false, \"digital_2\": false, \"digital_3\": false, \"digital_4\": false, \"digital_output_1\": 0, \"digital_output_2\": 1, \"eco_score\": 1000, \"external_power_voltage\": 0, \"green_driving_type\": 0, \"green_driving_value\": 0, \"gsensor_state\": 0, \"hdop\": 7, \"ibutton_id\": \"\", \"id\": \"239ad7d0-6748-11ed-9ef4-6df3685640ee\", \"lac\": \"\", \"lat\": \"51.53868\", \"location_type\": \"GPS\", \"long\": \"-3.6022\", \"movement\": 0, \"movement_sensor\": 1, \"pdop\": 12, \"relay_state\": 0, \"roaming\": 0, \"satellites\": 20, \"signal\": 3, \"speed\": 69, \"vdop\": 0 } ];\n\nconst speeds = data.map(item => item.speed);\nconst maxSpeed = Math.max(...speeds);\nconst minSpeed = Math.min(...speeds);\n\nconsole.log('Number of data points:', speeds.length);\nconsole.log('Max speed:', maxSpeed);\nconsole.log('Min speed:', minSpeed); .as-console-wrapper { max-height: 100% !important; } Array.reduce() const data = [ { \"imei\": \"1234567\", \"data_bucket\": \"19314\", \"timestamp\": \"2022-11-18T13:51:28.000Z\", \"acc_state\": 1, \"altitude\": 57, \"analogue_1\": 0, \"analogue_2\": 0, \"analogue_3\": 0, \"analogue_4\": 0, \"angle\": 258, \"battery\": 74, \"battery_current\": 0, \"battery_voltage\": 3859, \"button_id\": 0, \"cell_id\": 0, \"cid\": \"\", \"dallas_temperature_1\": 0, \"dallas_temperature_2\": 0, \"dallas_temperature_3\": 0, \"device_type\": \"FMBXXX\", \"digital_1\": false, \"digital_2\": false, \"digital_3\": false, \"digital_4\": false, \"digital_output_1\": 0, \"digital_output_2\": 1, \"eco_score\": 1000, \"external_power_voltage\": 0, \"green_driving_type\": 0, \"green_driving_value\": 0, \"gsensor_state\": 0, \"hdop\": 6, \"ibutton_id\": \"\", \"id\": \"1ba11080-6748-11ed-b708-1566bdff1367\", \"lac\": \"\", \"lat\": \"51.5390166\", \"location_type\": \"GPS\", \"long\": \"-3.5989166\", \"movement\": 0, \"movement_sensor\": 1, \"pdop\": 10, \"relay_state\": 0, \"roaming\": 0, \"satellites\": 21, \"signal\": 3, \"speed\": 48, \"vdop\": 0 }, { \"imei\": \"1234567\", \"data_bucket\": \"19314\", \"timestamp\": \"2022-11-18T13:51:31.000Z\", \"acc_state\": 1, \"altitude\": 56, \"analogue_1\": 0, \"analogue_2\": 0, \"analogue_3\": 0, \"analogue_4\": 0, \"angle\": 258, \"battery\": 72, \"battery_current\": 0, \"battery_voltage\": 3851, \"button_id\": 0, \"cell_id\": 0, \"cid\": \"\", \"dallas_temperature_1\": 0, \"dallas_temperature_2\": 0, \"dallas_temperature_3\": 0, \"device_type\": \"FMBXXX\", \"digital_1\": false, \"digital_2\": false, \"digital_3\": false, \"digital_4\": false, \"digital_output_1\": 0, \"digital_output_2\": 1, \"eco_score\": 1000, \"external_power_voltage\": 0, \"green_driving_type\": 0, \"green_driving_value\": 0, \"gsensor_state\": 0, \"hdop\": 6, \"ibutton_id\": \"\", \"id\": \"1dbbda30-6748-11ed-8164-c3bac4dd9d98\", \"lac\": \"\", \"lat\": \"51.5389416\", \"location_type\": \"GPS\", \"long\": \"-3.5995583\", \"movement\": 0, \"movement_sensor\": 1, \"pdop\": 11, \"relay_state\": 0, \"roaming\": 0, \"satellites\": 19, \"signal\": 3, \"speed\": 60, \"vdop\": 0 }, { \"imei\": \"1234567\", \"data_bucket\": \"19314\", \"timestamp\": \"2022-11-18T13:51:41.000Z\", \"acc_state\": 1, \"altitude\": 56, \"analogue_1\": 0, \"analogue_2\": 0, \"analogue_3\": 0, \"analogue_4\": 0, \"angle\": 264, \"battery\": 74, \"battery_current\": 0, \"battery_voltage\": 3864, \"button_id\": 0, \"cell_id\": 0, \"cid\": \"\", \"dallas_temperature_1\": 0, \"dallas_temperature_2\": 0, \"dallas_temperature_3\": 0, \"device_type\": \"FMBXXX\", \"digital_1\": false, \"digital_2\": false, \"digital_3\": false, \"digital_4\": false, \"digital_output_1\": 0, \"digital_output_2\": 1, \"eco_score\": 1000, \"external_power_voltage\": 0, \"green_driving_type\": 0, \"green_driving_value\": 0, \"gsensor_state\": 0, \"hdop\": 7, \"ibutton_id\": \"\", \"id\": \"239ad7d0-6748-11ed-9ef4-6df3685640ee\", \"lac\": \"\", \"lat\": \"51.53868\", \"location_type\": \"GPS\", \"long\": \"-3.6022\", \"movement\": 0, \"movement_sensor\": 1, \"pdop\": 12, \"relay_state\": 0, \"roaming\": 0, \"satellites\": 20, \"signal\": 3, \"speed\": 69, \"vdop\": 0 } ];\n\nconst maxSpeed = data.reduce((max, dataPt ) => {\n return (dataPt.speed > max) ? dataPt.speed: max;\n}, data[0].speed);\n\nconsole.log('Max speed:', maxSpeed)" }, { "answer_id": 74492315, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 0, "selected": false, "text": "const data = // Your JSON array here\nlet max = data[0].speed;\nfor (let i = 1; i < data.length; i++) {\n if (data[i].speed > max) max = data[i].speed;\n}\n map() sort let data = // Your JSON array here\ndata.sort((a,b) => b.speed - a.speed);\nconst max = data[0];\n reduce() const data = // Your JSON array here\nconst max = data.reduce((prev, cur) => Math.max(prev, cur.speed), data[0].speed);\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913800/" ]
74,491,853
<p>I am trying to scale and skew a bitmap in SkiaSharp with an affine matrix, however; the results always cut part of the resulting bitmap. I am also not sure if my affine matrix has the correct values.</p> <p>Here is a diagram of what I am trying to accomplish: on the left is the original image. It has a bitmap size of (178x242). On the right is the scaled and skewed image. The bounding box is (273x366), I also know that the the x scale has been skewed -10 pixels and the y scale has been skewed 7 pixels.</p> <p><a href="https://i.stack.imgur.com/64oYs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/64oYs.png" alt="enter image description here" /></a></p> <p>Here if my code for applying the affine matrix:</p> <pre><code>public SKBitmap ApplyAffine(SKBitmap origBitmap, SKSizeI newSize, SKPointI xyRotation) { var skewX = 1f / xyRotation.X; var skewY = 1f / xyRotation.Y; // Scale transform var scaleX = (newSize.Width / (float)origBitmap.Width); var scaleY = (newSize.Height / (float)origBitmap.Height); // Affine transform SKMatrix affine = new SKMatrix { ScaleX = scaleX, SkewY = skewY, SkewX = skewX, ScaleY = scaleY, TransX = 0, TransY = 0, Persp2 = 1 }; var bitmap = origBitmap.Copy(); var newBitmap = new SKBitmap(newSize.Width, newSize.Height); using (var canvas = new SKCanvas(newBitmap)) { canvas.SetMatrix(affine); canvas.DrawBitmap(bitmap, 0, 0); canvas.Restore(); } return newBitmap; } </code></pre> <p>The resulting bitmap has the left side cut off. It also appears that it is not translated correctly. How do I properly apply this affine?</p>
[ { "answer_id": 74552267, "author": "Maku", "author_id": 1768606, "author_profile": "https://Stackoverflow.com/users/1768606", "pm_score": 2, "selected": true, "text": "public SKBitmap ApplyAffine(SKBitmap origBitmap, SKSizeI newSize, SKPointI xyRotation)\n{\n // mcoo: skew is the tangent of the skew angle, but since xyRotation is not normalized\n // then it should be calculated based on original width/height\n var skewX = (float)xyRotation.X / origBitmap.Height;\n var skewY = (float)xyRotation.Y / origBitmap.Width;\n \n // Scale transform\n // mcoo (edit): we need to account here for the fact, that given skew is known AFTER the scale is applied\n var scaleX = (float)(newSize.Width - Math.Abs(xyRotation.X)) / origBitmap.Width;\n var scaleY = (float)(newSize.Height - Math.Abs(xyRotation.Y)) / origBitmap.Height;\n \n // Affine transform\n SKMatrix affine = new SKMatrix\n {\n ScaleX = scaleX,\n SkewY = skewY,\n SkewX = skewX,\n ScaleY = scaleY,\n //mcoo: we need to account for negative skew moving image bounds towards negative coords\n TransX = Math.Max(0, -xyRotation.X),\n TransY = Math.Max(0, -xyRotation.Y),\n Persp2 = 1\n };\n\n var bitmap = origBitmap.Copy();\n var newBitmap = new SKBitmap(newSize.Width, newSize.Height);\n\n using (var canvas = new SKCanvas(newBitmap))\n {\n // canvas.Clear(SKColors.Red);\n canvas.SetMatrix(affine);\n canvas.DrawBitmap(bitmap, 0, 0);\n }\n return newBitmap;\n}\n ApplyAffine(skBitmap, new SKSizeI(273, 366), new SKPointI(-10,7))" }, { "answer_id": 74604370, "author": "D P", "author_id": 20622893, "author_profile": "https://Stackoverflow.com/users/20622893", "pm_score": 0, "selected": false, "text": "| 1 0 0 |\n| 0 1 0 |\n| 0 0 1 |\n\nSKMatrix matrix = SKMatrix.MakeIdentity();\n | x y 1 |\n | 1 0 0 |\n| x y 1 | × | 0 1 0 | = | x' y' z' |\n | 0 0 1 |\n | 1 0 0 |\n| 0 1 0 |\n| tx ty 1 |\n | 1 0 0 |\n | sx 0 0 |\n │ 1 ySkew 0 │\n │ cos(α) sin(α) 0 │\n | –1 0 0 |\n| 0 –1 0 |\n| 0 0 1 |\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5792527/" ]
74,491,856
<p>I am learning Redux Toolkit. From a React POV it seems very intuitive to access whatever part of the state you need from within useSelector using an inline arrow function, and then conduct any calculations. As an example consider a cart item with its data (like item count) in redux store.</p> <pre><code>function CartItemCounter({ itemId }){ const cart = useSelector(state =&gt; state.cart); const itemInCart = cart.items[itemId]; const count = itemInCart?.count || 0; return &lt;div&gt;{itemId} - {count} nos&lt;/div&gt; } </code></pre> <p>But I'm seeing all this information saying you should define your selectors beside your slice, use createSelector and all. What is the right way, and why is it better?</p>
[ { "answer_id": 74491857, "author": "sayandcode", "author_id": 18620006, "author_profile": "https://Stackoverflow.com/users/18620006", "pm_score": 2, "selected": false, "text": "useSelector useSelector useSelector useSelector dispatch() useSelector 4 === 4 // true\n'itemA' === 'itemA // true\n const x = { name: 'Shashi' }\nconst fn1 = () => x;\nconst fn2 = () => x;\nconst fn3 = () => { name: 'Shashi' }\n\nfn1() === fn2(); // true\nfn1() === fn3(); // false, because the objects are different, with different references\n /* See how most keys are spread in, and will hence maintain reference equality.\nWhile certain keys like 'first', 'first.second', 'first.second[action.someId]' \nare changed with new objects, and so will break reference equality */\nfunction handwrittenReducer(state, action) {\n return {\n ...state,\n first: {\n ...state.first,\n second: {\n ...state.first.second,\n [action.someId]: {\n ...state.first.second[action.someId],\n fourth: action.someValue,\n },\n },\n },\n }\n}\n const cart1 = useSelector(state => state.cart)\nconst cart2 = useSelector(state => state.cart)\ncart1 === cart2; // true\n useSelector useSelector const cart = useSelector(state => state.cart)\n\n// extract the information you need from within the cart\nconst itemInCart = cart.items[itemId];\nconst count = itemInCart?.count || 0;\n useSelector // inside or next to the slice file\nconst selectCart = (state) => state.cart\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectCart)\n === // extract the information you need from within the cart, *within the selector*\nconst count = useSelector(state => state.cart.items[itemId]?.count || 0)\n// You don't have to use a one-liner, a multi-line function is better for readability\n useEffect const selectItemById = (state, itemId) => (state.cart.items[itemId]?.count || 0);\n\nfunction CartItemCounter({ itemId }){\n //...\n // somewhere inside a react component\n const count = useSelector((state) => selectCart(state, itemId))\n //...\n}\n const selectSomething = (state) => reallyExpensiveFn(state.cart)\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectSomething)\n const selectFilteredItems = (state) => state.itemsArray.filter(checkCondition) // the filter method will always return a new array\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectFilteredItems) // re-renders every time\n createSelector const selectFilteredItems = createSelector(\n (state) => state.itemsArray, // the first argument accesses relevant data from global state\n (itemsArray) => itemsArray.filter(checkCondition) // the second parameter conducts the transformation\n)\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectFilteredItems) // re-renders only when needed\n createSelector selectFilteredItems createSelector createSelector createSelector const makeSelectFilteredItems = () => createSelector(\n (state) => state.itemsArray, // the first argument accesses relevant data from global state\n (itemsArray) => itemsArray.filter(checkCondition) // the second parameter conducts the transformation\n)\n\n//...\n// somewhere inside a react component\nconst selectFilteredItems = useMemo(makeSelectFilteredItems,[]); // make a new selector for each component, when it mounts\nconst cart = useSelector(selectFilteredItems) // re-renders only when needed\n makeFilteredSelector useMemo createSelector" }, { "answer_id": 74508643, "author": "timotgl", "author_id": 6367424, "author_profile": "https://Stackoverflow.com/users/6367424", "pm_score": 0, "selected": false, "text": "state.cart createSelector useSelector" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18620006/" ]
74,491,889
<p>Since <a href="https://en.cppreference.com/w/cpp/iterator/iterator" rel="nofollow noreferrer">iterator</a> is deprecated, I began converting iterators in my code base to use non-deprecated constructs. I could not seem to make my indirect iterator compliant with the <code>std::forward_iterator</code> concept unless I explicitly specified <code>value_type</code>. I would like to know if this is expected.</p> <p>Based on the definition of <a href="https://en.cppreference.com/w/cpp/iterator/iter_t" rel="nofollow noreferrer">iter_value_t</a> and <a href="https://en.cppreference.com/w/cpp/iterator/indirectly_readable_traits" rel="nofollow noreferrer">indirectly_readible_traits</a>, it seems like there is no automatic inference of <code>std::iter_value_t</code>. Naively, I would have expected <code>std::iter_value_t&lt;Itr&gt;</code> to be defined as <code>std::remove_cvref_t&lt;std::iter_reference_t&lt;Itr&gt;&gt;</code> if no definition for <code>value_type</code> is present (which is checked via <code>has-member-value-type</code> in <a href="https://en.cppreference.com/w/cpp/iterator/indirectly_readable_traits" rel="nofollow noreferrer">indirectly_readible_traits</a>).</p> <pre><code>#include &lt;vector&gt; template &lt;std::forward_iterator Itr&gt; class IndirectItr { public: using value_type = std::iter_value_t&lt;Itr&gt;; // **do I need this?** explicit IndirectItr(Itr itr = {}) : m_itr{itr} {} bool operator==(const IndirectItr&amp; rhs) const { return m_itr == rhs.m_itr; } bool operator!=(const IndirectItr&amp; rhs) const { return m_itr != rhs.m_itr; } typename std::iter_reference_t&lt;Itr&gt; operator *() const { return *m_itr; } IndirectItr&amp; operator++() { ++m_itr; return *this; } IndirectItr operator++(int) { auto ret = *this; ++(*this); return ret; } typename std::iter_difference_t&lt;Itr&gt; operator-(const IndirectItr&amp; rhs) const { return m_itr - rhs.m_itr; } private: Itr m_itr; }; using Base = std::vector&lt;int&gt;::iterator; static_assert(std::forward_iterator&lt;IndirectItr&lt;Base&gt;&gt;); static_assert(std::same_as&lt;std::iter_value_t&lt;Base&gt;, std::remove_cvref_t&lt;std::iter_reference_t&lt;Base&gt;&gt;&gt;); </code></pre> <p>P.S. I have several indirect iterator definitions that wrap other iterators. The example above is representative of a custom indirect iterator. I don't have this exact class in my code.</p>
[ { "answer_id": 74491857, "author": "sayandcode", "author_id": 18620006, "author_profile": "https://Stackoverflow.com/users/18620006", "pm_score": 2, "selected": false, "text": "useSelector useSelector useSelector useSelector dispatch() useSelector 4 === 4 // true\n'itemA' === 'itemA // true\n const x = { name: 'Shashi' }\nconst fn1 = () => x;\nconst fn2 = () => x;\nconst fn3 = () => { name: 'Shashi' }\n\nfn1() === fn2(); // true\nfn1() === fn3(); // false, because the objects are different, with different references\n /* See how most keys are spread in, and will hence maintain reference equality.\nWhile certain keys like 'first', 'first.second', 'first.second[action.someId]' \nare changed with new objects, and so will break reference equality */\nfunction handwrittenReducer(state, action) {\n return {\n ...state,\n first: {\n ...state.first,\n second: {\n ...state.first.second,\n [action.someId]: {\n ...state.first.second[action.someId],\n fourth: action.someValue,\n },\n },\n },\n }\n}\n const cart1 = useSelector(state => state.cart)\nconst cart2 = useSelector(state => state.cart)\ncart1 === cart2; // true\n useSelector useSelector const cart = useSelector(state => state.cart)\n\n// extract the information you need from within the cart\nconst itemInCart = cart.items[itemId];\nconst count = itemInCart?.count || 0;\n useSelector // inside or next to the slice file\nconst selectCart = (state) => state.cart\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectCart)\n === // extract the information you need from within the cart, *within the selector*\nconst count = useSelector(state => state.cart.items[itemId]?.count || 0)\n// You don't have to use a one-liner, a multi-line function is better for readability\n useEffect const selectItemById = (state, itemId) => (state.cart.items[itemId]?.count || 0);\n\nfunction CartItemCounter({ itemId }){\n //...\n // somewhere inside a react component\n const count = useSelector((state) => selectCart(state, itemId))\n //...\n}\n const selectSomething = (state) => reallyExpensiveFn(state.cart)\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectSomething)\n const selectFilteredItems = (state) => state.itemsArray.filter(checkCondition) // the filter method will always return a new array\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectFilteredItems) // re-renders every time\n createSelector const selectFilteredItems = createSelector(\n (state) => state.itemsArray, // the first argument accesses relevant data from global state\n (itemsArray) => itemsArray.filter(checkCondition) // the second parameter conducts the transformation\n)\n\n//...\n// somewhere inside a react component\nconst cart = useSelector(selectFilteredItems) // re-renders only when needed\n createSelector selectFilteredItems createSelector createSelector createSelector const makeSelectFilteredItems = () => createSelector(\n (state) => state.itemsArray, // the first argument accesses relevant data from global state\n (itemsArray) => itemsArray.filter(checkCondition) // the second parameter conducts the transformation\n)\n\n//...\n// somewhere inside a react component\nconst selectFilteredItems = useMemo(makeSelectFilteredItems,[]); // make a new selector for each component, when it mounts\nconst cart = useSelector(selectFilteredItems) // re-renders only when needed\n makeFilteredSelector useMemo createSelector" }, { "answer_id": 74508643, "author": "timotgl", "author_id": 6367424, "author_profile": "https://Stackoverflow.com/users/6367424", "pm_score": 0, "selected": false, "text": "state.cart createSelector useSelector" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17841694/" ]
74,491,895
<p>I have this dataset:</p> <pre class="lang-js prettyprint-override"><code>const dataset = [ { date: &quot;2022-01-01&quot;, category: &quot;red&quot;, value: 10 }, { date: &quot;2022-01-01&quot;, category: &quot;blue&quot;, value: 20 }, { date: &quot;2022-01-01&quot;, category: &quot;gold&quot;, value: 30 }, { date: &quot;2022-01-01&quot;, category: &quot;green&quot;, value: 40 }, { date: &quot;2022-01-02&quot;, category: &quot;red&quot;, value: 5 }, { date: &quot;2022-01-02&quot;, category: &quot;blue&quot;, value: 15 }, { date: &quot;2022-01-02&quot;, category: &quot;gold&quot;, value: 25 }, { date: &quot;2022-01-02&quot;, category: &quot;green&quot;, value: 35 } ]; </code></pre> <p>And I need to create a stacked barchart. To do that I used the d3 <code>stack()</code> function. The result I need is this:</p> <pre class="lang-js prettyprint-override"><code>const stackedDataset = [ { date: &quot;2022-01-01&quot;, category: &quot;red&quot;, value: 10, start: 0, end: 10 }, { date: &quot;2022-01-02&quot;, category: &quot;red&quot;, value: 5, start: 0, end: 5 }, { date: &quot;2022-01-01&quot;, category: &quot;blue&quot;, value: 20, start: 10, end: 30 }, { date: &quot;2022-01-02&quot;, category: &quot;blue&quot;, value: 15, start: 5, end: 20 }, { date: &quot;2022-01-01&quot;, category: &quot;gold&quot;, value: 30, start: 30, end: 60 }, { date: &quot;2022-01-02&quot;, category: &quot;gold&quot;, value: 25, start: 20, end: 45 }, { date: &quot;2022-01-01&quot;, category: &quot;green&quot;, value: 40, start: 60, end: 100 }, { date: &quot;2022-01-02&quot;, category: &quot;green&quot;, value: 35, start: 45, end: 80 } ] </code></pre> <p>So the same data but with a <code>start</code> and <code>end</code> property computed by d3.</p> <p>I created a function that takes in input <code>dataset</code> and returns <code>stackedDataset</code>:</p> <pre class="lang-js prettyprint-override"><code>export function getStackedSeries(dataset: Datum[]) { const categories = uniq(dataset.map((d) =&gt; d[CATEGORY])) as string[]; const datasetGroupedByDateFlat = flatDataset(dataset); const stackGenerator = d3.stack().keys(categories); const seriesRaw = stackGenerator( datasetGroupedByDateFlat as Array&lt;Dictionary&lt;number&gt;&gt; ); const series = seriesRaw.flatMap((serie, si) =&gt; { const category = categories[si]; const result = serie.map((s, sj) =&gt; { return { [DATE]: datasetGroupedByDateFlat[sj][DATE] as string, [CATEGORY]: category, [VALUE]: datasetGroupedByDateFlat[sj][category] as number, start: s[0] || 0, end: s[1] || 0 }; }); return result; }); return series; } export function flatDataset( dataset: Datum[] ): Array&lt;Dictionary&lt;string | number&gt;&gt; { if (dataset.length === 0 || !DATE) { return (dataset as unknown) as Array&lt;Dictionary&lt;string | number&gt;&gt;; } const columnToBeFlatValues = uniqBy(dataset, CATEGORY).map( (d) =&gt; d[CATEGORY] ); const datasetGroupedByDate = groupBy(dataset, DATE); const datasetGroupedByMainCategoryFlat = Object.entries( datasetGroupedByDate ).map(([date, datasetForDate]) =&gt; { const categoriesObject = columnToBeFlatValues.reduce((acc, value) =&gt; { const datum = datasetForDate.find( (d) =&gt; d[DATE] === date &amp;&amp; d[CATEGORY] === value ); acc[value] = datum?.[VALUE]; return acc; }, {} as Dictionary&lt;string | number | undefined&gt;); return { [DATE]: date, ...categoriesObject }; }); return datasetGroupedByMainCategoryFlat as Array&lt;Dictionary&lt;string | number&gt;&gt;; } </code></pre> <p>As you can see, the functions are specific for <code>Datum</code> type. Is there a way to modify them to make them works for a generic type <code>T</code> that has at least the three fields <code>date, category, value</code>?</p> <p>I mean, I would like to have something like this:</p> <pre class="lang-js prettyprint-override"><code>interface StackedStartEnd { start: number end: number } function getStackedSeries&lt;T&gt;(dataset: T[]): T extends StackedStartEnd </code></pre> <p>Obviously this piece of code should be refactored to make it more generic:</p> <pre class="lang-js prettyprint-override"><code>{ [DATE]: ..., [CATEGORY]: ..., [VALUE]: ..., start: ..., end: ..., } </code></pre> <p><a href="https://codesandbox.io/s/stacked-type-7gepl9?file=/src/index.ts:45-503" rel="nofollow noreferrer">Here</a> the working code.</p> <p>I'm not a TypeScript expert so I need some help. Honestly what I tried to do was to modify the function signature but I failed and, anyway, I would like to make the functions as generic as possible and I don't know how to start. Do I need to pass to the functions also the used columns names?</p> <p>Thank you very much</p>
[ { "answer_id": 74511798, "author": "Lucas Arcanjo", "author_id": 8589377, "author_profile": "https://Stackoverflow.com/users/8589377", "pm_score": 3, "selected": true, "text": "getStackedSeries date category value start end export function getStackedSeries<T extends Datum>(\n data: T[],\n groupByProperty: PropertyType<T>\n) {\n const groupedData = groupBy(data, (d) => d[groupByProperty]);\n\n const acumulatedData = Object.entries(groupedData).flatMap(\n ([_, groupedValue]) => {\n let acumulator = 0;\n\n return groupedValue.map(({ value, ...rest }) => {\n const obj = {\n ...rest,\n value: value,\n start: acumulator,\n end: acumulator + value\n };\n\n acumulator += value;\n\n return obj;\n });\n }\n );\n\n return acumulatedData;\n}\n\n getStackedSeries() data Datum export interface Datum {\n value: number;\n}\n groupByProperty flatMap <T> const dataGroupedByDate: (Omit<{\n date: string;\n category: string;\n value: number;\n}, \"value\"> & {\n value: number;\n start: number;\n end: number;\n})[]\n" }, { "answer_id": 74549341, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "const\n dataset = [{ date: \"2022-01-01\", category: \"red\", value: 10 }, { date: \"2022-01-01\", category: \"blue\", value: 20 }, { date: \"2022-01-01\", category: \"gold\", value: 30 }, { date: \"2022-01-01\", category: \"green\", value: 40 }, { date: \"2022-01-02\", category: \"red\", value: 5 }, { date: \"2022-01-02\", category: \"blue\", value: 15 }, { date: \"2022-01-02\", category: \"gold\", value: 25 }, { date: \"2022-01-02\", category: \"green\", value: 35 }],\n result = Object\n .values(dataset\n .reduce((r, { date, category, value }) => {\n const\n start = r.date[date]?.at(-1).end ?? 0,\n end = start + value,\n object = { date, category, value, start, end };\n\n (r.date[date] ??= []).push(object);\n (r.category[category] ??= []).push(object);\n return r;\n }, { date: {}, category: {} })\n .category\n )\n .flat();\n\nconsole.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13415477/" ]
74,491,900
<p>I have a linked list for a catalog and book. I am trying to filter by author and return with the books that are of exact match, however, it says that my book type has no such attribute whenever i run it. I also try to upper case the author names so that it is consistent and match will return even if input are of different case</p> <pre><code>class Book: def __init__(self, title, author, year): if not isinstance(title, str): raise Exception(&quot;title must be a string&quot;) if not isinstance(author, str): raise Exception(&quot;author must be a string&quot;) if not isinstance(year, int): raise Exception(&quot;year must be an integer&quot;) self.title = title self.author = author self.year = year def __eq__(self, other): if isinstance(other, Book): return self.title == other.title and \ self.author == other.author and \ self.year == other.year return NotImplemented def __repr__(self): return f&quot;{repr(self.title)} by {repr(self.author)} {self.year})&quot; class Catalog: def __init__(self): self.lst = [] def filter_by_author(self, author): xs = self.lst.copy() xs = [author.capitalize() for author in xs] if author.upper() in xs: return self.lst # driver b1 = Book(&quot;1984&quot;, &quot;George Orwell&quot;, 1949) b2 = Book(&quot;Brave new world&quot;, &quot;Aldous Huxley&quot;, 1932) b3 = Book(&quot;El aleph&quot;, &quot;Jorge Louis Borges&quot;, 1949) b4 = Book(&quot;The devils of Loudun&quot;, &quot;Aldous Huxley&quot;, 1952) cat = Catalog() cat.add(b1) cat.add(b2) cat.add(b3) cat.add(b4) la = cat.filter_by_author(&quot;aldous huxley&quot;) assert la == [b2, b4] </code></pre> <p>I am trying to assert if author matches the books in the catalog, the list will return with the books</p>
[ { "answer_id": 74492047, "author": "emilyisstewpid", "author_id": 19940541, "author_profile": "https://Stackoverflow.com/users/19940541", "pm_score": 3, "selected": true, "text": ".capitalize() list comprehension book Book \"author\" author author Book author.author.capitalize() def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if book.author.lower() == author]\n def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower()]\n \"John\" in \"Johnathan\" \"John\" def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower().split()]\n \"John Nathan Last-name\".split(\" \") == [\"John\", \"Nathan\", \"Last-name\"] \" \"" }, { "answer_id": 74492219, "author": "gashik", "author_id": 20424854, "author_profile": "https://Stackoverflow.com/users/20424854", "pm_score": 0, "selected": false, "text": "class Catalog:\n def __init__(self):\n self.lst = []\n\n def add(self, b):\n self.lst.append(b)\n\n def filter_by_author(self, author):\n return [b for b in self.lst if b.author.upper() == author.upper()]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20250841/" ]
74,491,949
<p>Say I have a dataframe-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>id1</td> <td>blue</td> </tr> <tr> <td>id1</td> <td>red</td> </tr> <tr> <td>id1</td> <td>grey</td> </tr> <tr> <td>id2</td> <td>red</td> </tr> <tr> <td>id3</td> <td>red</td> </tr> <tr> <td>id3</td> <td>grey</td> </tr> </tbody> </table> </div> <p>I would like this output-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>id1</td> <td>all.mixed</td> </tr> <tr> <td>id2</td> <td>red</td> </tr> <tr> <td>id3</td> <td>red.grey</td> </tr> </tbody> </table> </div> <p>I tried this- <code>table1 &lt;- mydf %&gt;% group_by(ColA, ColB) %&gt;% count(ColB)</code> and came to this-</p> <pre><code>ColA ColB n &lt;chr&gt; &lt;chr&gt; &lt;int&gt; 1 id1 blue 1 2 id1 red 1 3 id1 grey 1 4 id2 red 1 5 id3 red 1 6 id3 grey1 1 </code></pre> <p>But I am kind of lost after this. I thought of group_by and summing up the rows in the colB, but then if I have a situation such that-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> </tr> </thead> <tbody> <tr> <td>id5</td> <td>grey</td> </tr> <tr> <td>id5</td> <td>grey</td> </tr> </tbody> </table> </div> <p>Then what do i do?</p>
[ { "answer_id": 74492047, "author": "emilyisstewpid", "author_id": 19940541, "author_profile": "https://Stackoverflow.com/users/19940541", "pm_score": 3, "selected": true, "text": ".capitalize() list comprehension book Book \"author\" author author Book author.author.capitalize() def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if book.author.lower() == author]\n def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower()]\n \"John\" in \"Johnathan\" \"John\" def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower().split()]\n \"John Nathan Last-name\".split(\" \") == [\"John\", \"Nathan\", \"Last-name\"] \" \"" }, { "answer_id": 74492219, "author": "gashik", "author_id": 20424854, "author_profile": "https://Stackoverflow.com/users/20424854", "pm_score": 0, "selected": false, "text": "class Catalog:\n def __init__(self):\n self.lst = []\n\n def add(self, b):\n self.lst.append(b)\n\n def filter_by_author(self, author):\n return [b for b in self.lst if b.author.upper() == author.upper()]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20388122/" ]
74,491,956
<p>I have updated my original post as have got a bit further and have the querying of my CW Alarms part of my code working. The below now outputs the state of my CW Alarms in the console, and in the format I want. What I'm now trying to do is take the output and upload this as a text file to an S3 bucket. Is this possible?</p> <p><strong>CW Alarm Code</strong></p> <pre><code>import { CloudWatchClient, DescribeAlarmsCommand } from &quot;@aws-sdk/client-cloudwatch&quot;; const REGION = &quot;eu-west-2&quot;; const cwclient = new CloudWatchClient({ region: REGION }); export const handler = async() =&gt; { const cwparams = {}; const cw = new DescribeAlarmsCommand(cwparams); try { const cwdata = await cwclient.send(cw); cwdata.MetricAlarms.forEach(function (item) { console.log('\n%j', {alarmname:item.AlarmName,alarmstate:item.StateValue}); }); } catch (error) { } }; </code></pre> <p><strong>Output</strong></p> <pre><code>Function Logs START RequestId: xxxxxxxxxxxxxxxxxxx Version: $LATEST 2022-11-30T09:48:34.655Z xxxxxxxxxxxxxxxxxxx INFO {&quot;alarmname&quot;:&quot;my-alarm-1&quot;,&quot;alarmstate&quot;:&quot;OK&quot;} 2022-11-30T09:48:34.655Z xxxxxxxxxxxxxxxxxxx INFO {&quot;alarmname&quot;:&quot;my-alarm-2&quot;,&quot;alarmstate&quot;:&quot;OK&quot;} END RequestId: xxxxxxxxxxxxxxxxxxx </code></pre> <p>I have looked at the sdk for the s3 PutObjectCommand and have tested the below, which allows me to upload a file with some text content, but I'm not sure how I can combine my CW Alarm data with this code, so that the &quot;Body&quot; of the text file is my CW Alarm data.</p> <p><strong>S3 Code</strong></p> <pre><code>import { S3Client, PutObjectCommand } from &quot;@aws-sdk/client-s3&quot;; export const handler = async() =&gt; { const bucketName = &quot;mybucket&quot;; const keyName = &quot;test.json&quot;; const s3 = new S3Client({}); const s3putCommand = new PutObjectCommand({ Bucket: bucketName, Key: keyName, Body: &quot;Hello&quot; // I would like this to be my CW Alarm data }); try { await s3.send(s3putCommand); console.log('Successfully uploaded data to ' + bucketName + '/' + keyName); } catch (error) { } }; </code></pre> <p><strong>Output</strong></p> <pre><code>Function Logs START RequestId: xxxxxxxxxxxxxxxxxxx Version: $LATEST 2022-11-30T09:56:45.585Z xxxxxxxxxxxxxxxxxxx INFO Successfully uploaded data to mybucket/test.json END RequestId: xxxxxxxxxxxxxxxxxxx </code></pre> <p>My goal is to end up with the test.json file looking like this:</p> <pre><code>{&quot;alarmname&quot;:&quot;my-alarm-1&quot;,&quot;alarmstate&quot;:&quot;OK&quot;} {&quot;alarmname&quot;:&quot;my-alarm-2&quot;,&quot;alarmstate&quot;:&quot;OK&quot;} </code></pre> <p>Thanks.</p>
[ { "answer_id": 74492047, "author": "emilyisstewpid", "author_id": 19940541, "author_profile": "https://Stackoverflow.com/users/19940541", "pm_score": 3, "selected": true, "text": ".capitalize() list comprehension book Book \"author\" author author Book author.author.capitalize() def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if book.author.lower() == author]\n def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower()]\n \"John\" in \"Johnathan\" \"John\" def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower().split()]\n \"John Nathan Last-name\".split(\" \") == [\"John\", \"Nathan\", \"Last-name\"] \" \"" }, { "answer_id": 74492219, "author": "gashik", "author_id": 20424854, "author_profile": "https://Stackoverflow.com/users/20424854", "pm_score": 0, "selected": false, "text": "class Catalog:\n def __init__(self):\n self.lst = []\n\n def add(self, b):\n self.lst.append(b)\n\n def filter_by_author(self, author):\n return [b for b in self.lst if b.author.upper() == author.upper()]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12019122/" ]
74,491,974
<p>I have two large tables - Table_A and Table_B - that I want to join on the ID field. &quot;ID&quot; in Table_A is a column and &quot;IDs&quot; in Table_B is an array</p> <pre><code>Table_A: ID | City | ----+------------+ 101 | London | 102 | Paris | 103 | Rome | 104 | Copenhagen | 105 | Amsterdam | 106 | Berlin | 107 | Cardiff | 108 | Lisbon | Table_B: Date | Sessions | IDs ------+----------+-------------- 06-02 | 1 | [107,102] 06-03 | 1 | [103] 11-12 | 1 | [105,107,103] 27-06 | 1 | [104,108] 31-01 | 1 | [105] 22-04 | 1 | [106,102] 08-07 | 1 | [101,105,108] 02-10 | 1 | [105] Desirable Output: Date | Sessions | ID | City ------+----------+-------------+------------- 06-02 | 1 | 107 | Cardiff | | 102 | Paris 06-03 | 1 | 103 | Rome 11-12 | 1 | 105 | Amsterdam | | 107 | Cardiff | | 103 | Rome 27-06 | 1 | 104 | Copenhagen | | 108 | Lisbon ... </code></pre> <p>I have tried using inner joins with unnest and union all but nothing is working. Any help would be appreciated.</p>
[ { "answer_id": 74492047, "author": "emilyisstewpid", "author_id": 19940541, "author_profile": "https://Stackoverflow.com/users/19940541", "pm_score": 3, "selected": true, "text": ".capitalize() list comprehension book Book \"author\" author author Book author.author.capitalize() def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if book.author.lower() == author]\n def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower()]\n \"John\" in \"Johnathan\" \"John\" def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower().split()]\n \"John Nathan Last-name\".split(\" \") == [\"John\", \"Nathan\", \"Last-name\"] \" \"" }, { "answer_id": 74492219, "author": "gashik", "author_id": 20424854, "author_profile": "https://Stackoverflow.com/users/20424854", "pm_score": 0, "selected": false, "text": "class Catalog:\n def __init__(self):\n self.lst = []\n\n def add(self, b):\n self.lst.append(b)\n\n def filter_by_author(self, author):\n return [b for b in self.lst if b.author.upper() == author.upper()]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20539976/" ]
74,491,977
<p>We have some endpoints that we want to change but still want to keep using old ones for some time.</p> <p>Example: Current Endpoint: /download -&gt; New Endpoint: /document/download. We want to use both.</p> <p>The Endpoints are defined in a class. Current:</p> <pre><code>class Endpoints { public static final DOCUMENT_HOME = &quot;/home&quot;; public static final DOWNLOAD = &quot;/download&quot;; } @RequestMapping(Endpoints.DOCUMENT_HOME) class DocumentController { @GetMapping(value = Endpoints.DOWNLOAD) public void download(); } </code></pre> <p>New:</p> <pre><code>class Endpoints { public static final DOCUMENT_HOME = &quot;/home/document&quot;; public static final DOWNLOAD = &quot;/download&quot;; } @RequestMapping(Endpoints.DOCUMENT_HOME) class DocumentController { @GetMapping(value = Endpoints.DOWNLOAD) public void download(); } </code></pre>
[ { "answer_id": 74492047, "author": "emilyisstewpid", "author_id": 19940541, "author_profile": "https://Stackoverflow.com/users/19940541", "pm_score": 3, "selected": true, "text": ".capitalize() list comprehension book Book \"author\" author author Book author.author.capitalize() def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if book.author.lower() == author]\n def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower()]\n \"John\" in \"Johnathan\" \"John\" def filter_by_author(self, author):\n author = author.lower()\n return [book for book in self.lst if author in book.author.lower().split()]\n \"John Nathan Last-name\".split(\" \") == [\"John\", \"Nathan\", \"Last-name\"] \" \"" }, { "answer_id": 74492219, "author": "gashik", "author_id": 20424854, "author_profile": "https://Stackoverflow.com/users/20424854", "pm_score": 0, "selected": false, "text": "class Catalog:\n def __init__(self):\n self.lst = []\n\n def add(self, b):\n self.lst.append(b)\n\n def filter_by_author(self, author):\n return [b for b in self.lst if b.author.upper() == author.upper()]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5550583/" ]
74,491,999
<p>The XAML of my UserControl with name &quot;Clinical_Protocol&quot;:</p> <pre><code>&lt;Grid&gt; &lt;DataGrid Name=&quot;ClinicalProtocolDataGrid&quot; ItemsSource=&quot;{Binding DataGridItems, ElementName=Clinical_Protocol}&quot; AutoGenerateColumns=&quot;False&quot;&gt; &lt;DataGrid.Columns&gt; &lt;DataGridComboBoxColumn Header=&quot;Structure ID&quot; ItemsSource=&quot;{Binding ComboBoxItems, ElementName=Clinical_Protocol, Mode=TwoWay}&quot; SelectedItemBinding=&quot;{Binding SelectedStructureId, Mode=TwoWay}&quot; /&gt; &lt;DataGridTextColumn Header=&quot;RT ROI Type Code&quot; Binding=&quot;{Binding RtRoiInterpretedTypeCode}&quot;/&gt; &lt;DataGridTextColumn Header=&quot;RT ROI Type Description&quot; Binding=&quot;{Binding RtRoiInterpretedTypeDescription}&quot;/&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;/Grid&gt; </code></pre> <p>The dependency property for <code>ItemsSource</code> of the DataGrid in the code behind:</p> <pre class="lang-cs prettyprint-override"><code>internal ObservableCollection&lt;ClinicalProtocolDataGridItem&gt; DataGridItems { get { return (ObservableCollection&lt;ClinicalProtocolDataGridItem&gt;)GetValue(DataGridItemsProperty); } set { SetValue(DataGridItemsProperty, value); } } internal static readonly DependencyProperty DataGridItemsProperty = DependencyProperty.Register(&quot;DataGridItems&quot;, typeof(ObservableCollection&lt;ClinicalProtocolDataGridItem&gt;), typeof(ClinicalProtocolView), new PropertyMetadata(null, DataGridItemsPropertyChangedCallback)); private static void DataGridItemsPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (ClinicalProtocolView)d; control.DataGridItems = (ObservableCollection&lt;ClinicalProtocolDataGridItem&gt;)e.NewValue; } </code></pre> <p>The according <code>ClinicalProtocolDataGridItem</code> class:</p> <pre class="lang-cs prettyprint-override"><code>public class ClinicalProtocolDataGridItem { public string RtRoiInterpretedTypeCode { get; } public string RtRoiInterpretedTypeDescription { get; } public object SelectedStructureId { get; set; } public ClinicalProtocolDataGridItem(string rtRoiInterpretedTypeCode, string rtRoiInterpretedTypeDescription) { RtRoiInterpretedTypeCode = rtRoiInterpretedTypeCode ?? throw new ArgumentNullException(nameof(rtRoiInterpretedTypeCode)); RtRoiInterpretedTypeDescription = rtRoiInterpretedTypeDescription ?? throw new ArgumentNullException(nameof(rtRoiInterpretedTypeDescription)); } } </code></pre> <p>And finally the dependency property <code>ComboBoxItems</code>:</p> <pre class="lang-cs prettyprint-override"><code>public ObservableCollection&lt;ComboBoxItem&gt; ComboBoxItems { get { return (ObservableCollection&lt;ComboBoxItem&gt;)GetValue(ComboBoxItemsProperty); } set { SetValue(ComboBoxItemsProperty, value); } } public static readonly DependencyProperty ComboBoxItemsProperty = DependencyProperty.Register(&quot;ComboBoxItems&quot;, typeof(ObservableCollection&lt;ComboBoxItem&gt;), typeof(ClinicalProtocolView), new PropertyMetadata(new ObservableCollection&lt;ComboBoxItem&gt;(), PropertyChangedCallback)); private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (ClinicalProtocolView)d; control.ComboBoxItems = (ObservableCollection&lt;ComboBoxItem&gt;)e.NewValue; } </code></pre> <p>I try to populate both dependency properties with the following:</p> <pre class="lang-cs prettyprint-override"><code>private void AddSomeComboBoxItems() { ComboBoxItems = new ObservableCollection&lt;ComboBoxItem&gt; { new ComboBoxItem(){Content = &quot;S1&quot;, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center}, new ComboBoxItem(){Content = &quot;S2&quot;, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center}, new ComboBoxItem(){Content = &quot;S3&quot;, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center}, } private void AddSomeRows() { var items = new List&lt;ClinicalProtocolDataGridItem&gt; { new ClinicalProtocolDataGridItem(&quot;PTV&quot;, &quot;Description of PTV, and it is a very long description!&quot;), new ClinicalProtocolDataGridItem(&quot;OAR&quot;, &quot;Description of OAR, and it is a very long description!&quot;), }; DataGridItems = new ObservableCollection&lt;ClinicalProtocolDataGridItem&gt;(items); } </code></pre> <p>When I import it into a WPF application I get the following:</p> <p><a href="https://i.stack.imgur.com/M9kRR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M9kRR.png" alt="Combo Box Example picture" /></a></p> <p>And the error message: <code>DataGridComboBoxColumn.ItemsSource IEnumerable Cannot find governing FrameworkElement or FrameworkContentElement for target element. </code> <a href="https://i.stack.imgur.com/ofs4D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ofs4D.png" alt="Error message" /></a></p> <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.datagridcomboboxcolumn?view=windowsdesktop-7.0" rel="nofollow noreferrer">Microsoft documentation</a> says that it is possible to bind a collection of <code>ComboBoxItem</code>. What am I missing? I don't want to have a static resource, because the combo box items might change during runtime.</p>
[ { "answer_id": 74492298, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 3, "selected": true, "text": "<DataGrid Name=\"ClinicalProtocolDataGrid\"\n ItemsSource=\"{Binding DataGridItems, ElementName=Clinical_Protocol}\"\n AutoGenerateColumns=\"False\">\n <FrameworkElement.Resources>\n <!--Using a CollectionViewSource as a proxy to create a \"static link\".-->\n <CollectionViewSource\n x:Key=\"comboBoxItems\"\n Source=\"{Binding ComboBoxItems, ElementName=Clinical_Protocol}\"/>\n </FrameworkElement.Resources>\n <DataGrid.Columns>\n <DataGridComboBoxColumn\n Header=\"Structure ID\"\n ItemsSource=\"{Binding Source={StaticResource comboBoxItems}}\"\n SelectedItemBinding=\"{Binding SelectedStructureId, Mode=TwoWay}\"/>\n" }, { "answer_id": 74493200, "author": "Rekshino", "author_id": 7713750, "author_profile": "https://Stackoverflow.com/users/7713750", "pm_score": 0, "selected": false, "text": "ComboBoxItems public ObservableCollection<string> GetCbxSource()\n{\n return new ObservableCollection<string>\n {\n \"S1\",\n \"S2\",\n \"S3\",\n };\n}\n <Grid>\n <Grid.Resources>\n <ObjectDataProvider x:Key=\"cbxData\" MethodName=\"GetCbxSource\" ObjectInstance=\"{x:Reference Clinical_Protocol}\"/>\n </Grid.Resources>\n\n <DataGrid Name=\"ClinicalProtocolDataGrid\"\n ItemsSource=\"{Binding DataGridItems, ElementName=Clinical_Protocol}\"\n AutoGenerateColumns=\"False\">\n <DataGrid.Columns>\n <DataGridComboBoxColumn Header=\"Structure ID\"\n ItemsSource=\"{Binding Source= {StaticResource cbxData}}\"\n SelectedItemBinding=\"{Binding SelectedStructureId, Mode=TwoWay}\"\n />\n <DataGridTextColumn Header=\"RT ROI Type Code\" \n Binding=\"{Binding RtRoiInterpretedTypeCode}\"/>\n <DataGridTextColumn Header=\"RT ROI Type Description\"\n Binding=\"{Binding RtRoiInterpretedTypeDescription}\"/>\n </DataGrid.Columns>\n </DataGrid>\n</Grid>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74491999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072227/" ]
74,492,023
<p>I have the following code below which is generated from Drift for a live chat widget.</p> <pre><code>&lt;!-- Start of Async Drift Code --&gt; &lt;script&gt; &quot;use strict&quot;; !function() { var t = window.driftt = window.drift = window.driftt || []; if (!t.init) { if (t.invoked) return void (window.console &amp;&amp; console.error &amp;&amp; console.error(&quot;Drift snippet included twice.&quot;)); t.invoked = !0, t.methods = [ &quot;identify&quot;, &quot;config&quot;, &quot;track&quot;, &quot;reset&quot;, &quot;debug&quot;, &quot;show&quot;, &quot;ping&quot;, &quot;page&quot;, &quot;hide&quot;, &quot;off&quot;, &quot;on&quot; ], t.factory = function(e) { return function() { var n = Array.prototype.slice.call(arguments); return n.unshift(e), t.push(n), t; }; }, t.methods.forEach(function(e) { t[e] = t.factory(e); }), t.load = function(t) { var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement(&quot;script&quot;); o.type = &quot;text/javascript&quot;, o.async = !0, o.crossorigin = &quot;anonymous&quot;, o.src = &quot;https://js.driftt.com/include/&quot; + n + &quot;/&quot; + t + &quot;.js&quot;; var i = document.getElementsByTagName(&quot;script&quot;)[0]; i.parentNode.insertBefore(o, i); }; } }(); drift.SNIPPET_VERSION = '0.3.1'; drift.load('...'); &lt;/script&gt; &lt;!-- End of Async Drift Code --&gt; </code></pre> <p>And I am trying to add this code into a jsx file.</p> <p>I have tried to include the above directly into what is returned in the jsx file, but that doesn't work.</p> <p>I have also tried to put the above code into its own function and call it in what should be displayed on the screen using <code>{{}}</code> but that also didn't work.</p> <p>The code doesn't have any errors, it only reports this in the console which tells me it's just being called. <code>DRIFT_WIDGET:: widget_core:bootstrap_api finished in 201.60000002384186 ms</code></p> <p>Can someone please help in how I can add this widget to my page.</p> <p>Thank you!</p>
[ { "answer_id": 74492298, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 3, "selected": true, "text": "<DataGrid Name=\"ClinicalProtocolDataGrid\"\n ItemsSource=\"{Binding DataGridItems, ElementName=Clinical_Protocol}\"\n AutoGenerateColumns=\"False\">\n <FrameworkElement.Resources>\n <!--Using a CollectionViewSource as a proxy to create a \"static link\".-->\n <CollectionViewSource\n x:Key=\"comboBoxItems\"\n Source=\"{Binding ComboBoxItems, ElementName=Clinical_Protocol}\"/>\n </FrameworkElement.Resources>\n <DataGrid.Columns>\n <DataGridComboBoxColumn\n Header=\"Structure ID\"\n ItemsSource=\"{Binding Source={StaticResource comboBoxItems}}\"\n SelectedItemBinding=\"{Binding SelectedStructureId, Mode=TwoWay}\"/>\n" }, { "answer_id": 74493200, "author": "Rekshino", "author_id": 7713750, "author_profile": "https://Stackoverflow.com/users/7713750", "pm_score": 0, "selected": false, "text": "ComboBoxItems public ObservableCollection<string> GetCbxSource()\n{\n return new ObservableCollection<string>\n {\n \"S1\",\n \"S2\",\n \"S3\",\n };\n}\n <Grid>\n <Grid.Resources>\n <ObjectDataProvider x:Key=\"cbxData\" MethodName=\"GetCbxSource\" ObjectInstance=\"{x:Reference Clinical_Protocol}\"/>\n </Grid.Resources>\n\n <DataGrid Name=\"ClinicalProtocolDataGrid\"\n ItemsSource=\"{Binding DataGridItems, ElementName=Clinical_Protocol}\"\n AutoGenerateColumns=\"False\">\n <DataGrid.Columns>\n <DataGridComboBoxColumn Header=\"Structure ID\"\n ItemsSource=\"{Binding Source= {StaticResource cbxData}}\"\n SelectedItemBinding=\"{Binding SelectedStructureId, Mode=TwoWay}\"\n />\n <DataGridTextColumn Header=\"RT ROI Type Code\" \n Binding=\"{Binding RtRoiInterpretedTypeCode}\"/>\n <DataGridTextColumn Header=\"RT ROI Type Description\"\n Binding=\"{Binding RtRoiInterpretedTypeDescription}\"/>\n </DataGrid.Columns>\n </DataGrid>\n</Grid>\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10671368/" ]
74,492,091
<p>Can I use float data type to store the return value of millis function as shown on the code here? I saw unsigned int type to do it. But look I'm converting that millis to hour. That's why I'm trying to store in float.</p> <pre class="lang-cpp prettyprint-override"><code>#include&lt;Servo.h&gt; #include&lt;math.h&gt; Servo mark1; float dur = 2.30, del_dur = 0 ; float sys_strt = (millis()/3600000), curr_tim = (millis()/3600000), del_strt = 0; float inc_val; const int relay_on = 8; //2, output = 9; void setup() { digitalWrite(8, HIGH); mark1.attach(9); mark1.write(110);//servo on Serial.begin(9600); // pinMode(switch_on, INPUT); // pinMode(output, OUTPUT); } void loop() { if(Serial.available() &gt; 0) { inc_val = Serial.read(); Serial.print(&quot;\n&quot;); if(inc_val == 'D') // D = DURATION { delay(2000); dur = Serial.read(); sys_strt = (millis()/3600000); //mark1.write(on); } else if(inc_val == 'd') // d = delay_duration_for_future_turn_on { mark1.write(158);// servo off delay(2000); del_dur = Serial.read(); Serial.print(&quot;\n&quot;); delay (5000); dur = (Serial.read() + del_dur); del_strt = (curr_tim + del_dur); sys_strt = del_strt; //curr_tim = (millis()/1000); } } if((millis()/3600000) &gt;= 5) {digitalWrite( 8, LOW);} if(((millis()/3600000) - del_strt) &gt;= 0 &amp;&amp; ((millis()/3600000) - del_strt) &lt;=10 ) // statement for delay duration process { mark1.write(110);// servo on } if(((millis()/3600000)-sys_strt) &gt;= dur) { mark1.write(158);//servo off } } //int x = ((millis() / 1000) - off_timer_start) / 60; // if (digitalRead(switch_on) == HIGH) //{ // off_timer_start = (millis() / 1000); //digitalWrite(output, HIGH); //} //else if (x &gt;= offtime &amp;&amp; digitalRead(output == HIGH)) { //digitalWrite(output, LOW); //} //delay(1000); </code></pre> <p>I was trying to store millis return value in float variable. But not sure whether it'll work or not.</p>
[ { "answer_id": 74496954, "author": "hcheung", "author_id": 4902099, "author_profile": "https://Stackoverflow.com/users/4902099", "pm_score": 1, "selected": false, "text": "float millis() unsigned long uint32_t millis()/3600000 5*3600000 18000000 if((millis()/3600000) >= 5) // do something\n if((millis() >= 5*3600000) // do something\n unsigned long fiveHour = 5*3600000;\n\nif ((millis() >= fiveHour) // do something\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20541006/" ]
74,492,092
<p>I need to write a program that converts an octal number to decimal. However if I enter a non octal number such as 1079, the program shows an error and stops.</p> <p>I want the program to keep asking the user for a valid input until user enters a valid input.</p> <pre><code>while True: n= input(&quot;Enter an octal value to convert to decimal, binary and hexadecimal form:&quot;) n = n.strip() #removes trailing and leading spaces if n.isdigit(): for i in n: if i == &quot;8&quot; or i == &quot;9&quot;: print(&quot;Invalid octal.&quot;) break else: octToDec = int(n,8) print(n, &quot;in Decimal is: &quot;, octToDec) break else: print(&quot;Invalid input&quot;) </code></pre> <p>This is what I have come up with so far but the program breaks after printing &quot;Invalid octal.&quot;. I want it to go back to the second line of code to ask for the users input after the error.</p> <p>This converts proper octal values to decimal. It shows error if value entered is a string then goes back to second line in order to ask the user to enter new value. If a non octal value is entered. It shows an error then breaks. For example: If i enter &quot;1079&quot;, it shows:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 10, in &lt;module&gt; ValueError: invalid literal for int() with base 8: '1079' </code></pre> <p>I want it to show:</p> <pre><code>Invalid octal. Enter octal value to convert to decimal: </code></pre> <p>until user enters a valid octal number.</p>
[ { "answer_id": 74492163, "author": "hiro protagonist", "author_id": 4954037, "author_profile": "https://Stackoverflow.com/users/4954037", "pm_score": -1, "selected": false, "text": "while True:\n ans = input(\"Number in octal: \")\n try:\n number = int(ans, 8)\n break\n except ValueError:\n print(f\"{ans} can not be interpreted as ocal nubmer\")\n continue\n\n# do stuff with number...\n 8 9 int(ans, 8)" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540903/" ]
74,492,105
<p>I'd like to create div with data getting from user input by clicking btn submit, But I don't know how. I am new in react js.</p> <p>This is my App.js file:</p> <pre><code>import './App.css'; import './RegisterApp.css' import RegisterApp from './Components/RegisterApp'; function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;RegisterApp /&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>and this is my component file RegisterApp.js:</p> <pre><code>import React, {useState} from 'react' function RegisterApp() { const [name, setName] = useState('Khun Neary') const [position, setPosition] = useState('Designer') const [list, setList] = useState({name, position}) const formSubmit = (e) =&gt; { e.preventDefault() setList(...list, name) setList(...list, position) console.log(list); } return ( &lt;div className='container'&gt; &lt;form className='form-box' onSubmit={formSubmit}&gt; &lt;button&gt;Upload Profile&lt;/button&gt; &lt;input type=&quot;text&quot; placeholder='Name...' value={name} onChange={(e) =&gt; setName(e.target.value)} /&gt; &lt;input type=&quot;text&quot; placeholder='Position...' value={position} onChange={(e) =&gt; setPosition(e.target.value)} /&gt; &lt;button&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;div className='register-box'&gt; &lt;div className='sub-reg-box'&gt; &lt;div className='img-box'&gt;&lt;/div&gt; &lt;div className='detail-box'&gt; &lt;h2&gt;{name}&lt;/h2&gt; &lt;h4&gt;{position}&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } export default RegisterApp </code></pre> <p><a href="https://i.stack.imgur.com/hxrBN.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I'd like to create div element after I click submit btn and display all the data get from input by user.</p>
[ { "answer_id": 74492145, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 1, "selected": false, "text": " type=\"submit\" <button type=\"submit\">Submit</button>\n const formSubmit = (e) => { \n setList( {...list, name, position }) \n }\n list useEffect useEffect(() => {\n console.log(list)\n},[list])\n" }, { "answer_id": 74492162, "author": "Code-Apprentice", "author_id": 1440565, "author_profile": "https://Stackoverflow.com/users/1440565", "pm_score": 0, "selected": false, "text": "name position onClick setList() list setList name setName position setPosition" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17915341/" ]
74,492,111
<p>I'm trying to print the value of currently logged in username in my main.html file. My login.html file looks like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Login Form Validation&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;login.css&quot;&gt; &lt;script defer src=&quot;login.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;main id=&quot;main-holder&quot;&gt; &lt;h1 id=&quot;login-header&quot;&gt;Login&lt;/h1&gt; &lt;div id=&quot;login-error-msg-holder&quot;&gt; &lt;p id=&quot;login-error-msg&quot;&gt;Invalid username &lt;span id=&quot;error-msg-second-line&quot;&gt;and/or password&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;form id=&quot;login-form&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;username&quot; id=&quot;username-field&quot; class=&quot;login-form-field&quot; placeholder=&quot;Username&quot;&gt; &lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password-field&quot; class=&quot;login-form-field&quot; placeholder=&quot;Password&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Login&quot; id=&quot;login-form-submit&quot;&gt; &lt;/form&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And the .js file looks like this:</p> <pre><code>const loginForm = document.getElementById(&quot;login-form&quot;); const loginButton = document.getElementById(&quot;login-form-submit&quot;); const loginErrorMsg = document.getElementById(&quot;login-error-msg&quot;); loginButton.addEventListener(&quot;click&quot;, (e) =&gt; { e.preventDefault(); const username = loginForm.username.value; const password = loginForm.password.value; if (username === &quot;Erkki_Esimerkki&quot; &amp;&amp; password === &quot;projekti&quot;) { window.location.href = &quot;main.html&quot;; /* location.reload();*/ } else { loginErrorMsg.style.opacity = 1; } }) </code></pre> <p>The username should be printed in a <code>p</code> element in my main.html which the user is directed after logging in through the login.html.</p> <p>I tried creating a function in my login.html like so:</p> <pre><code> function getUsername() { let username = document.getElementById(&quot;username-field&quot;).value document.getElementById(&quot;userinfo&quot;).innerHTML += username } </code></pre> <p>And calling the function in my main.js.</p>
[ { "answer_id": 74492145, "author": "Sachila Ranawaka", "author_id": 6428638, "author_profile": "https://Stackoverflow.com/users/6428638", "pm_score": 1, "selected": false, "text": " type=\"submit\" <button type=\"submit\">Submit</button>\n const formSubmit = (e) => { \n setList( {...list, name, position }) \n }\n list useEffect useEffect(() => {\n console.log(list)\n},[list])\n" }, { "answer_id": 74492162, "author": "Code-Apprentice", "author_id": 1440565, "author_profile": "https://Stackoverflow.com/users/1440565", "pm_score": 0, "selected": false, "text": "name position onClick setList() list setList name setName position setPosition" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771634/" ]
74,492,112
<p>More of a curiosity of if and how it can be done. I sometimes find myself repeating commands with small parts of the same command modified.</p> <p>Example:</p> <pre><code>grep aaa file.txt grep bbb file.txt grep ccc file.txt </code></pre> <p>I know I could set this up with a for loop but I don't always know all of the values that may need to be changed/tested at start. I can also use keyboard movement to get back to the aaa quicker, but it's still extra keys. Not a lot with the example, but some strung together commands can result in a lot of keyboard movement needed.</p> <p>I know that variables and files can be passed to certain commands at the end, for example.</p> <pre><code>while read i; do echo &quot;$i&quot;; done &lt; ./file.txt x='./file.txt' sed 's/find/replace/' &lt;&lt;&lt;${x} </code></pre> <p>I'm curious if there is a way with bash substitution to do similar declaration at the end of the command for undeclared variables. I tried variations like <code>grep ${} file.txt &lt;&lt;&lt; 'aaa'</code> but so far nothing I've toyed with has worked out. My goal is that the passed value is not declared as a variable so I can just hit up arrow on keyboard and edit the string at the end of the command statement. Appreciate any help or insights that can be given!</p>
[ { "answer_id": 74492510, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": false, "text": "f () { grep \"$1\" file.txt; }\n f aaa\nf bbb\nf ccc\n f" }, { "answer_id": 74492530, "author": "omnivir", "author_id": 3022906, "author_profile": "https://Stackoverflow.com/users/3022906", "pm_score": 0, "selected": false, "text": "xargs -I {} grep {} file.txt <<< aaa" }, { "answer_id": 74493476, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 1, "selected": false, "text": "^old^new^ $ grep shy lyrics.txt\nYou're too shy to say it\nYou're too shy to say it\n$ ^shy^cry^\ngrep cry lyrics.txt\nNever gonna make you cry\nNever gonna make you cry\n...\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022906/" ]
74,492,124
<p>I'm having an issue with <code>TaggedOutput</code>s in Apache Beam (<code>DataflowRunner</code>) using Python 3.9. I've included the necessary pieces of code below for understanding.</p> <p>Basically the tagged output from <code>parent_check_pipeline</code> for <code>Tag.REQS_SATISFIED</code>) is not working. When the code in <code>CheckParentRequirements</code> yields that tagged output, the pipeline, basically, ends. I get the correct log that the &quot;Element ... has no parents&quot;, but the pipeline stops there and doesn't proceed to &quot;Write to Pubsub Topics.&quot; I think my meaning can be seen in the dataflow graph I included below as well.</p> <p>The pipeline definitions for each step are separated into functions for ease of testing. We've used this approach in other beam pipelines and it is working so I'm not sure what's missing here.</p> <p>Thanks in advance!</p> <h3>Other approaches</h3> <p>I've tried declaring the inputs to &quot;Write to Pubsub&quot; as a tuple:</p> <pre class="lang-py prettyprint-override"><code>p_publish_messages = ( (p_check_parents_needed[Tag.REQS_SATISFIED], p_check_parents_exist[Tag.REQS_SATISFIED]) | &quot;Write to Pubsub Topics&quot; &gt;&gt; beam.ParDo(WriteToPubsubMultiple(topic_1, topic_2)) ) </code></pre> <p>which gives the following error:</p> <pre><code> File &quot;.../lib/python3.9/site-packages/apache_beam/transforms/core.py&quot;, line 1578, in expand is_bounded = pcoll.is_bounded AttributeError: 'tuple' object has no attribute 'is_bounded' </code></pre> <p>When using the code defined in <code>publish_messages_pipeline</code> with:</p> <pre class="lang-py prettyprint-override"><code>p_publish_messages = publish_messages_pipeline([p_check_parents_needed, p_check_parents_exist], pipeline_params) </code></pre> <p>I receive:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py&quot;, line 362, in &lt;module&gt; run( File &quot;/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py&quot;, line 317, in run p_publish_messages = publish_messages_pipeline([p_check_parents_needed, p_check_parents_exist], pipeline_params) File &quot;/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py&quot;, line 206, in publish_messages_pipeline tagged_sources File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/transforms/ptransform.py&quot;, line 1095, in __ror__ return self.transform.__ror__(pvalueish, self.label) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/transforms/ptransform.py&quot;, line 622, in __ror__ p.run().wait_until_finish() File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/pipeline.py&quot;, line 574, in run return self.runner.run_pipeline(self, self._options) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/direct/direct_runner.py&quot;, line 131, in run_pipeline return runner.run_pipeline(pipeline, options) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py&quot;, line 199, in run_pipeline self._latest_run_result = self.run_via_runner_api( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py&quot;, line 212, in run_via_runner_api return self.run_stages(stage_context, stages) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py&quot;, line 442, in run_stages bundle_results = self._execute_bundle( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py&quot;, line 770, in _execute_bundle self._run_bundle( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py&quot;, line 999, in _run_bundle result, splits = bundle_manager.process_bundle( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py&quot;, line 1309, in process_bundle result_future = self._worker_handler.control_conn.push(process_bundle_req) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/portability/fn_api_runner/worker_handlers.py&quot;, line 380, in push response = self.worker.do_instruction(request) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/sdk_worker.py&quot;, line 597, in do_instruction return getattr(self, request_type)( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/sdk_worker.py&quot;, line 635, in process_bundle bundle_processor.process_bundle(instruction_id)) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/bundle_processor.py&quot;, line 1003, in process_bundle input_op_by_transform_id[element.transform_id].process_encoded( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/bundle_processor.py&quot;, line 227, in process_encoded self.output(decoded_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 528, in output _cast_to_receiver(self.receivers[output_index]).receive(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 240, in receive self.consumer.process(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 908, in process delayed_applications = self.dofn_runner.process(o) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1419, in process self._reraise_augmented(exn) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1491, in _reraise_augmented raise exn File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 623, in invoke_process self.output_handler.handle_process_outputs( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1581, in handle_process_outputs self._write_value_to_tag(tag, windowed_value, watermark_estimator) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1694, in _write_value_to_tag self.main_receivers.receive(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 240, in receive self.consumer.process(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 908, in process delayed_applications = self.dofn_runner.process(o) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1419, in process self._reraise_augmented(exn) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1491, in _reraise_augmented raise exn File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 623, in invoke_process self.output_handler.handle_process_outputs( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1581, in handle_process_outputs self._write_value_to_tag(tag, windowed_value, watermark_estimator) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1694, in _write_value_to_tag self.main_receivers.receive(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 240, in receive self.consumer.process(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/worker/operations.py&quot;, line 908, in process delayed_applications = self.dofn_runner.process(o) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1419, in process self._reraise_augmented(exn) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1507, in _reraise_augmented raise new_exn.with_traceback(tb) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1417, in process return self.do_fn_invoker.invoke_process(windowed_value) File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 623, in invoke_process self.output_handler.handle_process_outputs( File &quot;/Users/jimmy.hartman/Library/Caches/pypoetry/virtualenvs/up-ces-ingest-eventing-qyT-FGDE-py3.9/lib/python3.9/site-packages/apache_beam/runners/common.py&quot;, line 1571, in handle_process_outputs for result in results: File &quot;/Users/jimmy.hartman/projects/apiary/ces-ingest-eventing/src/dataflow/parent_check_pipeline.py&quot;, line 159, in process enc_element = json.dumps(element).encode(&quot;utf-8&quot;) File &quot;/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/__init__.py&quot;, line 231, in dumps return _default_encoder.encode(obj) File &quot;/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py&quot;, line 199, in encode chunks = self.iterencode(o, _one_shot=True) File &quot;/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py&quot;, line 257, in iterencode return _iterencode(o, 0) File &quot;/Users/jimmy.hartman/.pyenv/versions/3.9.13/lib/python3.9/json/encoder.py&quot;, line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type _InvalidUnpickledPCollection is not JSON serializable [while running 'Write to Pubsub Topics'] </code></pre> <h3>Code</h3> <pre class="lang-py prettyprint-override"><code>class CheckParentRequirements(DoFn): def process(self, element, *args, **kwargs): parents = get_parents(element) if parents: logging.getLogger(__name__).warning(f&quot;Element {element} has parents: '{parents}'&quot;) yield TaggedOutput(value=element, tag=Tag.PARENTS_NEEDED) else: logging.getLogger(__name__).warning(f&quot;Element {element} has no parents&quot;) yield TaggedOutput(value=element, tag=Tag.REQS_SATISFIED) class LookupParents(DoFn): def process(self, element): missing_parents = self.get_missing_entities(parent_id_map, element) if missing_parents: self.logger.info(f&quot;'{element}' missing parents {missing_parents}.&quot;) element.update({Key.MISSING_PARENTS: missing_parents}) yield TaggedOutput(value=element, tag=Tag.MISSING_PARENTS) else: self.logger.info(f&quot;'{element}' parents found.&quot;) yield TaggedOutput(value=element, tag=Tag.REQS_SATISFIED) def get_missing_parents(element): ... class WriteToPubsubMultiple(DoFn): def __init__(self, topic_1, topic_2): self.topic_1 = topic_1 self.topic_2 = topic_2 self.publisher = None def setup(self): self.publisher = pubsub_v1.PublisherClient() def process(self, element, *args, **kwargs): logger = logging.getLogger(__name__) enc_element = json.dumps(element).encode(&quot;utf-8&quot;) self.publisher.publish(self.topic_1, enc_element) self.publisher.publish(self.topic_2, enc_element) logger.info(&quot;Sent message messages.&quot;) yield None def parent_check_pipeline(source) -&gt; DoOutputsTuple: p_parent_check = ( source | &quot;Check Parent Requirement&quot; &gt;&gt; beam.ParDo(CheckParentRequirements()).with_outputs(Tag.PARENTS_NEEDED, Tag.REQS_SATISFIED) ) return p_parent_check def lookup_parents_pipeline(source: DoOutputsTuple, params: PipelineParams) -&gt; DoOutputsTuple: p_parents_exist = source[Tag.PARENTS_NEEDED] | &quot;Lookup Parents&quot; &gt;&gt; beam.ParDo( LookupParents(params.database_instance_id, params.database_id) ).with_outputs(Tag.MISSING_PARENTS, Tag.REQS_SATISFIED) return p_parents_exist def waiting_room_insert_pipeline(source: DoOutputsTuple, params: PipelineParams): p_waiting_room_rows = ( source[Tag.MISSING_PARENTS] | &quot;Create Bigtable Rows&quot; &gt;&gt; beam.ParDo(CreateWaitingRoomRows()) | &quot;Bigtable Window&quot; &gt;&gt; beam.WindowInto( window.GlobalWindows(), trigger=Repeatedly(AfterAny(AfterCount(100), AfterProcessingTime(10))), accumulation_mode=AccumulationMode.DISCARDING, ) | &quot;Write to Bigtable&quot; &gt;&gt; WriteToBigTable(params.project_id, params.instance, params.table) ) return p_waiting_room_rows # Not using this right now as I was troubleshooting. This is now in the `run()` method. def publish_messages_pipeline(sources: List[DoOutputsTuple], params: PipelineParams): tagged_sources = (source[Tag.REQS_SATISFIED] for source in sources) p_publish_messages = ( tagged_sources | &quot;Write to Pubsub Topics&quot; &gt;&gt; beam.ParDo(WriteToPubsubMultiple(params.topic_1, params.topic_2)) ) return p_publish_messages def run( pipeline_options, pipeline_params ): with Pipeline(options=pipeline_options) as pipeline: p_source = ( pipeline | &quot;Read from Pub/Sub&quot; &gt;&gt; io.ReadFromPubSub(subscription=input_subscription) | &quot;Parse JSON&quot; &gt;&gt; beam.Map(json.loads) ) p_check_parents_needed = parent_check_pipeline(p_source) p_check_parents_exist = lookup_parents_pipeline(p_check_parents_needed, pipeline_params) p_waiting_room_insert = waiting_room_insert_pipeline(p_check_parents_exist, pipeline_params) p_publish_messages = ( p_check_parents_needed[Tag.REQS_SATISFIED], p_check_parents_exist[Tag.REQS_SATISFIED] | &quot;Write to Pubsub Topics&quot; &gt;&gt; beam.ParDo(WriteToPubsubMultiple(topic_1, topic_2)) ) </code></pre> <h3>Dataflow graph:</h3> <p><a href="https://i.stack.imgur.com/x7oMc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x7oMc.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74499337, "author": "CaptainNabla", "author_id": 16622985, "author_profile": "https://Stackoverflow.com/users/16622985", "pm_score": 1, "selected": false, "text": "Tag.WHATEVER PTransform class ParentCheckPipeline(beam.PTransform):\n def expand(self, source):\n p_parent_check = (\n source\n | \"Check Parent Requirement\" >> beam.ParDo(CheckParentRequirements())\n .with_outputs(Tag.PARENTS_NEEDED, Tag.REQS_SATISFIED)\n )\n return p_parent_check\n expand" }, { "answer_id": 74548613, "author": "James B", "author_id": 3614254, "author_profile": "https://Stackoverflow.com/users/3614254", "pm_score": 1, "selected": true, "text": "publish_messages_pipeline def publish_messages_pipeline(sources: List[DoOutputsTuple], params: PipelineParams):\n tagged_sources = (source[Tag.REQS_SATISFIED] for source in sources)\n p_publish_messages = (\n tagged_sources\n | \"Flatten inputs\" >> beam.Flatten()\n | \"Write to Pubsub Topics\"\n >> beam.ParDo(WriteToPubsubMultipleFn(params.topic_1, params.topic_2))\n )\n return p_publish_messages\n PTransform class InsertIntoWaitingRoom(PTransform):\n def __init__(self, params: PipelineParams):\n super(InsertIntoWaitingRoom, self).__init__()\n self.params = params\n\n def expand(self, source: InputT) -> OutputT:\n return (\n source\n | \"Create Bigtable Rows\" >> beam.ParDo(CreateWaitingRoomRowsFn())\n | \"Bigtable Window\"\n >> beam.WindowInto(\n window.GlobalWindows(),\n trigger=Repeatedly(AfterAny(AfterCount(100), AfterProcessingTime(10))),\n accumulation_mode=AccumulationMode.DISCARDING,\n )\n | \"Write to Bigtable\"\n >> WriteToBigTable(\n self.params.project, self.params.instance, self.params.table\n )\n )\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3614254/" ]
74,492,167
<p>I would like to create a function in which a mathematical formula is set as argument (with only two possible variables) and use this formula within two nested loop. The idea is to be able to change the formula as I would like to create y values based on the formula. This is what I have done but I cannot apply the formula:</p> <pre><code>foo &lt;- function(formula = y~a-b){ formula = as.formula(y ~a -b) formula = formula[[3:length(formula)]] result = NULL for (a in 1:30) { for(b in 1:30){ result = c(result, noquote(formula)) } } return(result) } </code></pre>
[ { "answer_id": 74492452, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 3, "selected": true, "text": "foo <- function(formula = y ~ a - b) {\n fun <- function(a, b) {}\n body(fun) <- formula[[length(formula)]]\n result <- NULL\n for (a in 1:30) {\n for(b in 1:30) {\n result = c(result, fun(a, b))\n }\n }\n return(result)\n}\n\n# test\nresult <- foo()\n" }, { "answer_id": 74492628, "author": "langtang", "author_id": 4447540, "author_profile": "https://Stackoverflow.com/users/4447540", "pm_score": 1, "selected": false, "text": "G. Grothendieck foo() as.function() foo <- function(f) as.function(alist(a=,b=,eval(parse(text=f))))\na=1:5\nb=1:5\nf = \"(a-b)*a/b\"\nresult = apply(expand.grid(a,b),1,\\(x) foo(f)(x[1],x[2]))\n [1] 0.0000000 -0.5000000 -0.6666667 -0.7500000 -0.8000000 2.0000000 0.0000000\n [8] -0.6666667 -1.0000000 -1.2000000 6.0000000 1.5000000 0.0000000 -0.7500000\n[15] -1.2000000 12.0000000 4.0000000 1.3333333 0.0000000 -0.8000000 20.0000000\n[22] 7.5000000 3.3333333 1.2500000 0.0000000\n" }, { "answer_id": 74493768, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 1, "selected": false, "text": "alist as.function outer for foo1 <- function(fo=y ~ a - b, a=1:30, b=1:30) {\n f <- as.function(c(alist(b=, a=), fo[[3]]))\n outer(b, a, f) |> as.vector()\n}\n\n## test\nresult <- foo() ## G. Grothendieck's\nresult1 <- foo1()\n\nstopifnot(all.equal(result, result1))\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3887120/" ]
74,492,192
<p>I am new to swift .. I am trying to crate delay and print the delay time like 1 seconds and start printing the next item into list . I got the result but I am not sure make delay of each iteration and print it .. Here is the struct .</p> <pre><code>struct CartProductResult { var id: Int var title: String var quantity: Int } let cartProducts = [ CartProductResult(id: 1, title: &quot;nike shoe 1&quot;, quantity: 5), CartProductResult(id: 2, title: &quot;nike shoe 2&quot;, quantity: 2), CartProductResult(id: 3, title: &quot;soap&quot;, quantity: 6) ] </code></pre> <p>Here is the function ..</p> <pre><code>func printWithDelay(product1: CartProductResult, product2: CartProductResult, completion: (@escaping ()-&gt; Void)) { completion() } </code></pre> <p>Here is the call to the function ..</p> <pre><code>printWithDelay(product1: cartProducts[0], product2: cartProducts[1]) { let seconds = 1.0 DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { print(&quot; Wait 1 second&quot;) for cartProduct in cartProducts { print(cartProduct.id) } print(&quot;Done printing products&quot;) } } </code></pre> <p>Here is the result ,I got.. <a href="https://i.stack.imgur.com/5bgcG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5bgcG.png" alt="current result" /></a></p> <p>Here is the expected result .. <a href="https://i.stack.imgur.com/rMrVD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rMrVD.png" alt="expected result " /></a></p>
[ { "answer_id": 74492594, "author": "Kaushal Rola", "author_id": 14252468, "author_profile": "https://Stackoverflow.com/users/14252468", "pm_score": 0, "selected": false, "text": "func printWithDelay(products: [CartProductResult], completion: (@escaping ()-> Void)) {\n for product in products {\n let seconds = 1.0\n sleep(1)\n print(\" Wait 1 second\")\n print(product.id)\n }\n completion()\n}\n\nprintWithDelay(products: cartProducts) {\n print(\"Done printing products\")\n}\n" }, { "answer_id": 74493007, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 1, "selected": false, "text": "sleep() Timer printWithDelay() class ViewController: UIViewController {\n \n struct CartProductResult {\n var id: Int\n var title: String\n var quantity: Int\n }\n let cartProducts = [\n CartProductResult(id: 1, title: \"nike shoe 1\", quantity: 5),\n CartProductResult(id: 2, title: \"nike shoe 2\", quantity: 2),\n CartProductResult(id: 3, title: \"soap\", quantity: 6)\n ]\n \n func printOneProduct(_ index: Int) {\n let p = cartProducts[index]\n print(\"id:\", p.id)\n }\n func printWithDelay(products: [CartProductResult], completion: (@escaping ()-> Void)) {\n \n var idx: Int = 0\n \n // we want to print the first product immediately,\n // then step through the rest 1-second at a time\n printOneProduct(idx)\n\n Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in\n idx += 1\n if idx == products.count {\n timer.invalidate()\n completion()\n }\n self.printOneProduct(idx)\n }\n }\n \n override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {\n \n printWithDelay(products: cartProducts) {\n print(\"Done printing products\")\n }\n \n // execution continues while products are printing\n \n }\n \n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8705895/" ]
74,492,224
<p>I'm writing a program that displays a fast food menu and it allows the user to select an item. Then, the user enters the quantity of that item, and can continue selecting items with specific quantities until done. What I'm having trouble with is finding out how to calculate a running total. I am new to c# so I only know the basics. What is the best way to keep track of the running total while using multiple methods? In addition, I'm open to any criticism in my code. Thank you in advance.</p> <pre><code>using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { bool ordering = true; string userInput; double itemPrice; double itemQuantity; double subTol; string response; void pricing() { Console.Write(&quot;Enter option 1, 2, 3: &quot;); userInput = Console.ReadLine(); switch (userInput) { case &quot;1&quot;: itemPrice = 3.00; Console.WriteLine(&quot;You have picked a burger.&quot;); break; case &quot;2&quot;: itemPrice = 1.50; Console.WriteLine(&quot;You have picked fries.&quot;); break; case &quot;3&quot;: itemPrice = 1.00; Console.WriteLine(&quot;You have picked a soda.&quot;); break; default: Console.WriteLine(&quot;That is not on our menu.&quot;); pricing(); break; } } void quantity() { Console.Write(&quot;Enter quantity: &quot;); itemQuantity = Convert.ToDouble(Console.ReadLine()); } void subTotal() { subTol = itemQuantity * itemPrice; Console.WriteLine(); Console.WriteLine(&quot;Your Subtotal: &quot; + subTol); } while (ordering) { Console.WriteLine(&quot;What would you like from our menu?&quot;); Console.WriteLine(&quot;\n1. Burger ($3.00) \n2. Fries ($1.50) \n3. Soda ($1.00)&quot;); Console.WriteLine(); pricing(); quantity(); subTotal(); Console.Write(&quot;Would you like anything else? Y/N: &quot;); response = Console.ReadLine(); response = response.ToUpper(); if (response == &quot;Y&quot;) { ordering = true; } else { ordering = false; Console.WriteLine(&quot;Enjoy your meal!&quot;); } } } } } </code></pre>
[ { "answer_id": 74492594, "author": "Kaushal Rola", "author_id": 14252468, "author_profile": "https://Stackoverflow.com/users/14252468", "pm_score": 0, "selected": false, "text": "func printWithDelay(products: [CartProductResult], completion: (@escaping ()-> Void)) {\n for product in products {\n let seconds = 1.0\n sleep(1)\n print(\" Wait 1 second\")\n print(product.id)\n }\n completion()\n}\n\nprintWithDelay(products: cartProducts) {\n print(\"Done printing products\")\n}\n" }, { "answer_id": 74493007, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 1, "selected": false, "text": "sleep() Timer printWithDelay() class ViewController: UIViewController {\n \n struct CartProductResult {\n var id: Int\n var title: String\n var quantity: Int\n }\n let cartProducts = [\n CartProductResult(id: 1, title: \"nike shoe 1\", quantity: 5),\n CartProductResult(id: 2, title: \"nike shoe 2\", quantity: 2),\n CartProductResult(id: 3, title: \"soap\", quantity: 6)\n ]\n \n func printOneProduct(_ index: Int) {\n let p = cartProducts[index]\n print(\"id:\", p.id)\n }\n func printWithDelay(products: [CartProductResult], completion: (@escaping ()-> Void)) {\n \n var idx: Int = 0\n \n // we want to print the first product immediately,\n // then step through the rest 1-second at a time\n printOneProduct(idx)\n\n Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in\n idx += 1\n if idx == products.count {\n timer.invalidate()\n completion()\n }\n self.printOneProduct(idx)\n }\n }\n \n override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {\n \n printWithDelay(products: cartProducts) {\n print(\"Done printing products\")\n }\n \n // execution continues while products are printing\n \n }\n \n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540538/" ]
74,492,252
<p>I have a data frame of this format:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 1: {'mean': 1.0, 'std': 0.8}, 2: {'mean': 0.5, 'std': 0.2}, 3: {'mean': 0.2, 'std': 0.1}, 4: {'mean': 0.1, 'std': 0.1}, 5: {'mean': 0.6, 'std': 0.2} }) df 1 2 3 4 5 mean 1.0 0.5 0.2 0.1 0.6 std 0.8 0.2 0.1 0.1 0.2 </code></pre> <p>Based on these values of <code>mean</code> and <code>std</code>, I am trying to generate a big data frame of randomly generated numbers normally distributed, which has the same number of columns but more rows:</p> <pre class="lang-py prettyprint-override"><code>full_noise = [] for mean, std in enumerate(df): noise = np.random.normal(mean, std, [5, 1000]) full_noise.append(noise) </code></pre> <p>So, each column of this new data frame will have values generated on <code>mean</code> and <code>std</code> listed in the data frame above. I am definitely doing something wrong, though.</p> <p>Sorry, I am quite new to Python! I hope you can help :(</p>
[ { "answer_id": 74492402, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 2, "selected": false, "text": "df iterrows axis=1 full_noise = []\nfor _, col in df.T.iterrows():\n noise = np.random.normal(loc=col[\"mean\"], scale=col[\"std\"], size=(1000,))\n full_noise.append(pd.Series(noise))\n\nnoise_df = pd.concat(full_noise, axis=1)\n" }, { "answer_id": 74492500, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 0, "selected": false, "text": ".apply full_noise full_noise = df.apply(\n lambda col: np.random.normal(loc=col[\"mean\"], scale=col[\"std\"], size=(1_000,)),\n)\n\nprint(full_noise)\n 1 2 3 4 5\n0 0.900445 0.555275 0.206491 0.161578 0.491196\n1 1.555625 0.261742 0.196981 -0.068225 0.770397\n2 0.308983 0.256334 0.119617 0.157978 0.453351\n3 0.799080 0.255109 0.164719 -0.088953 0.462583\n4 1.263621 0.650327 0.217544 0.046004 0.893409\n.. ... ... ... ... ...\n995 1.345332 0.827836 0.320708 0.113350 0.789898\n996 1.235461 0.464576 0.270596 0.049924 0.708799\n997 1.211508 0.751700 0.230916 0.176736 0.661312\n998 1.753942 0.941567 0.097372 0.177429 0.810710\n999 1.847943 0.240993 -0.006139 0.200517 0.523238\n\n[1000 rows x 5 columns]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18134832/" ]
74,492,260
<p>How can I reduce an array of objects into one object, with unique properties. I will appreciate any help! Thank you!</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const input = [ { "a": false} , { "b": false, "c": true } , { "b": false, "c": true } , { "a": false } , { "b": false, "c": true } , { "b": false, "c": true } , { "b": false, "c": true, "b": false } ] // I tried : const object = input.reduce( (obj, item) =&gt; Object.assign(obj, { [item.key]: item.value }) , {}); console.log( object );</code></pre> </div> </div> but I get:</p> <pre><code>{ &quot;undefined&quot;: undefined } </code></pre> <p>Expected result:</p> <pre><code>{&quot;a&quot;:false,&quot;b&quot;:false,&quot;c&quot;:true} </code></pre>
[ { "answer_id": 74492402, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 2, "selected": false, "text": "df iterrows axis=1 full_noise = []\nfor _, col in df.T.iterrows():\n noise = np.random.normal(loc=col[\"mean\"], scale=col[\"std\"], size=(1000,))\n full_noise.append(pd.Series(noise))\n\nnoise_df = pd.concat(full_noise, axis=1)\n" }, { "answer_id": 74492500, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 0, "selected": false, "text": ".apply full_noise full_noise = df.apply(\n lambda col: np.random.normal(loc=col[\"mean\"], scale=col[\"std\"], size=(1_000,)),\n)\n\nprint(full_noise)\n 1 2 3 4 5\n0 0.900445 0.555275 0.206491 0.161578 0.491196\n1 1.555625 0.261742 0.196981 -0.068225 0.770397\n2 0.308983 0.256334 0.119617 0.157978 0.453351\n3 0.799080 0.255109 0.164719 -0.088953 0.462583\n4 1.263621 0.650327 0.217544 0.046004 0.893409\n.. ... ... ... ... ...\n995 1.345332 0.827836 0.320708 0.113350 0.789898\n996 1.235461 0.464576 0.270596 0.049924 0.708799\n997 1.211508 0.751700 0.230916 0.176736 0.661312\n998 1.753942 0.941567 0.097372 0.177429 0.810710\n999 1.847943 0.240993 -0.006139 0.200517 0.523238\n\n[1000 rows x 5 columns]\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7762963/" ]
74,492,265
<p>It seems to be impossible to animate the <code>.backgroundColor</code> property of an <code>SCNView</code>.</p> <p>Does anyone know how to do this?</p> <p>Please note, it is easy to animate the background of an actual scene (<code>SCNScene</code>) and I know how to do that, thanks. It is also easy to animate the background of a conventional <code>UIView</code>.</p> <p>I've not been able to figure out how to animate the <code>.backgroundColor</code> property of an <code>SCNView</code>.</p>
[ { "answer_id": 74507030, "author": "ZAY", "author_id": 7839658, "author_profile": "https://Stackoverflow.com/users/7839658", "pm_score": 2, "selected": true, "text": "viewDidLoad override func viewDidLoad() {\n super.viewDidLoad()\n \n // create a new scene\n let scene = SCNScene() // SCNScene(named: \"art.scnassets/ship.scn\")!\n \n // create and add a camera to the scene\n let cameraNode = SCNNode()\n cameraNode.camera = SCNCamera()\n scene.rootNode.addChildNode(cameraNode)\n \n // place the camera\n cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)\n \n // create and add a light to the scene\n let lightNode = SCNNode()\n lightNode.light = SCNLight()\n lightNode.light!.type = .omni\n lightNode.position = SCNVector3(x: 0, y: 10, z: 10)\n scene.rootNode.addChildNode(lightNode)\n \n // create and add an ambient light to the scene\n let ambientLightNode = SCNNode()\n ambientLightNode.light = SCNLight()\n ambientLightNode.light!.type = .ambient\n ambientLightNode.light!.color = UIColor.darkGray\n scene.rootNode.addChildNode(ambientLightNode)\n \n // retrieve the ship node\n // let ship = scene.rootNode.childNode(withName: \"ship\", recursively: true)!\n \n // animate the 3d object\n // ship.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1)))\n \n // retrieve the SCNView\n let scnView = self.view as! SCNView\n \n // set the scene to the view\n scnView.scene = scene\n \n // allows the user to manipulate the camera\n scnView.allowsCameraControl = true\n \n // show statistics such as fps and timing information\n scnView.showsStatistics = true\n \n // Configure the initial background color of the SCNView\n scnView.backgroundColor = UIColor.red\n \n // Setup a SCNAction that rotates i.Ex the HUE Value of the Background\n let animColor = SCNAction.customAction(duration: 10.0) { _ , timeElapsed in\n \n scnView.backgroundColor = UIColor.init(hue: timeElapsed/10, saturation: 1.0, brightness: 1.0, alpha: 1.0)\n \n }\n\n // Run the Action (here using the rootNode)\n scene.rootNode.runAction(animColor)\n \n // add a tap gesture recognizer\n let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))\n scnView.addGestureRecognizer(tapGesture)\n}\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294884/" ]
74,492,285
<p>I've tried to find why the error occurs, and the helper functions work perfectly fine. But still i couldn't find the solution. Could you point out where exactly my function is broken, or breaks down?</p> <p><strong>The goal is to return a number that is the smallest in its row, and greatest in its column.</strong></p> <p><strong>Here's my code:</strong></p> <pre><code>function luckyNumbers(matrix) { for (let i = 0; i &lt; matrix.length; i++) { for (let j = 0; j &lt; matrix[i].length; j++) { let ele = matrix[i][j]; if (minInRow(ele) === maxInColumn(ele)) { return ele; } } } }; matrix = [[ 5, 9, 21], [ 9, 19, 6], [12, 14, 15]] console.log(luckyNumbers(matrix)); // expected output - [12] matrix = [[ 5, 10, 8, 6], [10, 2, 7, 9], [21, 15, 19, 10]] console.log(luckyNumbers(matrix)); // expected output - [10] // --------------------- MIN_IN_ROW FUNCTION --------------------------- function minInRow(arr) { let minNum = arr[0][0]; for (let i = 0; i &lt; arr.length; i++) { for (let j = 0; j &lt; arr[i].length; j++) { let ele = arr[i][j]; if (ele &lt; minNum) { minNum = ele; } } } return minNum; }; /* console.log(minInRow([[6, 5, 11], [8, 7, 3 ], [9, 12, 1]])); */ // --------------- MAX_IN_COLUMN FUNCTION --------------------------- function maxInColumn(arr) { let maxNum = arr[0][0]; for (let i = 0; i &lt; arr.length; i++) { for (let j = 0; j &lt; arr[i].length; j++) { let ele = arr[i][j]; if (ele &gt; maxNum) { maxNum = ele; } } } return maxNum; }; /* console.log(maxInColumn([[3, 5, 6], [2, 20, 30], [9, 10, 2]])); */ // ----------------------------------------------------------------- </code></pre> <p><strong>The output i get is:</strong></p> <pre><code>let minNum = arr[0][0]; ^ TypeError: Cannot read property '0' of undefined at minInRow (/tmp/uEg6djEUrs.js:30:24) at luckyNumbers (/tmp/uEg6djEUrs.js:5:15) at Object.&lt;anonymous&gt; (/tmp/uEg6djEUrs.js:16:13) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) </code></pre>
[ { "answer_id": 74492366, "author": "PADMANABAN GOKULA", "author_id": 20450907, "author_profile": "https://Stackoverflow.com/users/20450907", "pm_score": -1, "selected": false, "text": " function luckyNumbers(matrix) {\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix.length; j++) { // you made additional lookup for the length\n let ele = matrix[i][j];\n if (minInRow(ele) === maxInColumn(ele)) {\n return ele;\n }\n }\n }\n};\n" }, { "answer_id": 74492962, "author": "alex351", "author_id": 3934886, "author_profile": "https://Stackoverflow.com/users/3934886", "pm_score": 2, "selected": true, "text": "let ele = matrix[i][j]; minInRow var matrix1 = [\n [ 5, 9, 21],\n [ 9, 19, 6],\n [12, 14, 15]\n];\n\nvar matrix2 = [\n [ 5, 10, 8, 6],\n [10, 2, 7, 9],\n [21, 15, 19, 10]\n];\n\nfunction luckyNumbers(matrix) {\n var minArray = [];\n for (let i = 0; i < matrix.length; i++) {\n var matrixRow = matrix[i];\n var min = Math.min(...matrixRow); // returns the minimum number of the row\n minArray.push(min); // add the minimum to the minimums array\n }\n return Math.max(...minArray); // returns the maximum number of all the minimums\n};\n\nconsole.log(luckyNumbers(matrix1));\nconsole.log(luckyNumbers(matrix2));" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16400935/" ]
74,492,302
<p>I have a dataframe like this:</p> <p>df:</p> <pre><code> Collection ID 0 [{'tom': 'one'}, {'tom': 'two'}] 10 1 [{'nick': 'one'}] 10 2 [{'julie': 'one'}] 14 </code></pre> <p>When the 'ID' column has duplicated values, for whichever entry of duplicates, the length of the list value of the column 'Collection' is greater, I want to set the value of a new column 'status' as 1, else 0.</p> <p>Resultant df should look like: df:</p> <pre><code> Collection ID status 0 [{'tom': 'one'}, {'tom': 'two'}] 10 1 1 [{'nick': 'one'}] 10 0 2 [{'julie': 'one'}] 14 1 </code></pre> <p>I have tried to go along the np.where function which I have found closest to my problem from Stack Overflow but failing to get an alternative of <code>df['Collection'].str.len()</code> which will give me the length of the list.</p> <pre><code>df['status']=np.where(df[&quot;Collection&quot;].str.len() &gt; 1, 1, 0) </code></pre> <p>Thanks in advance.</p> <p>df to dict value:</p> <pre><code>{'Collection': {0: [{'tom': 'one'}, {'tom': 'two'}], 1: [{'nick': 'one'}], 2: [{'julie': 'one'}]}, 'ID': {0: 10, 1: 10, 2: 14}} </code></pre>
[ { "answer_id": 74492366, "author": "PADMANABAN GOKULA", "author_id": 20450907, "author_profile": "https://Stackoverflow.com/users/20450907", "pm_score": -1, "selected": false, "text": " function luckyNumbers(matrix) {\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix.length; j++) { // you made additional lookup for the length\n let ele = matrix[i][j];\n if (minInRow(ele) === maxInColumn(ele)) {\n return ele;\n }\n }\n }\n};\n" }, { "answer_id": 74492962, "author": "alex351", "author_id": 3934886, "author_profile": "https://Stackoverflow.com/users/3934886", "pm_score": 2, "selected": true, "text": "let ele = matrix[i][j]; minInRow var matrix1 = [\n [ 5, 9, 21],\n [ 9, 19, 6],\n [12, 14, 15]\n];\n\nvar matrix2 = [\n [ 5, 10, 8, 6],\n [10, 2, 7, 9],\n [21, 15, 19, 10]\n];\n\nfunction luckyNumbers(matrix) {\n var minArray = [];\n for (let i = 0; i < matrix.length; i++) {\n var matrixRow = matrix[i];\n var min = Math.min(...matrixRow); // returns the minimum number of the row\n minArray.push(min); // add the minimum to the minimums array\n }\n return Math.max(...minArray); // returns the maximum number of all the minimums\n};\n\nconsole.log(luckyNumbers(matrix1));\nconsole.log(luckyNumbers(matrix2));" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11913986/" ]
74,492,328
<p>I have a simple numpy array made of floats and integers</p> <pre><code>array_to_save=np.array([shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]) </code></pre> <p>I would like to save this numpy array, appending it to an existing csv file by doing the following.</p> <pre><code> with open('frames_stats.csv','a') as csvfile: np.savetxt(csvfile,array_to_save,delimiter=',') </code></pre> <p>However, it saves this array not as an ordinary csv file, where there were supposed to be 4 values separated by commas, but it saves each value as a new line of the file such as follows:</p> <blockquote> <p>5.000000000000000000e-01 1.495000000000000000e+03 2.340000000000000000e+02 0.000000000000000000e+00 5.000000000000000000e-01 1.495000000000000000e+03 2.340000000000000000e+02 0.000000000000000000e+00</p> </blockquote> <p>How can I save such a csv file properly?</p>
[ { "answer_id": 74492690, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])\n" }, { "answer_id": 74492799, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 2, "selected": true, "text": "with open('frames_stats.csv','a') as csvfile:\n np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2163392/" ]
74,492,350
<p>I am working with an API that returns Dates in the format 2022-03-01T11:32:37</p> <pre><code>Created:&amp;nbsp;{this.props.proposal.OPENWHEN} Created: 2022-03-01T11:32:37 </code></pre> <p>How do i format this into DD/MM/YYY 24:00:00 ?</p> <p>Thanks In Advance</p>
[ { "answer_id": 74492690, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])\n" }, { "answer_id": 74492799, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 2, "selected": true, "text": "with open('frames_stats.csv','a') as csvfile:\n np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15222578/" ]
74,492,386
<p>So here is my code</p> <pre><code>#include&lt;math.h&gt; #include&lt;stdio.h&gt; #include&quot;hw1.h&quot; int main (int argc, char *argv[]) { int num_choices, k; char right_choices[20]; do { printf(&quot;Enter number of choices:\n&quot;); scanf(&quot;%d&quot;, &amp;num_choices); } while ((num_choices &gt; 26) || (num_choices &lt; 1)); num_choices = num_choices - 1 + 'A'; printf(&quot;Max choice:%c\n&quot;, (char)num_choices); printf(&quot;Enter answer key:\n&quot;); for( k=1; k &lt; 20; k++) scanf(&quot; %c&quot;, &amp;right_choices[20]); return 0; } </code></pre> <p>while compiling everything seems ok. While running the second scanf is supposed to run 20 times but everytime it stops at 19 and it says : &quot;zsh abort&quot;</p> <p>I tried doing it 10 times to see if that was the problem but the same message appeared at the 9th time. It always stops at n-1.</p> <p>The same code runs on linux perfectly.</p> <p>Thank you very much!</p> <p>i searched up the problem but i didnt find any usefull information</p>
[ { "answer_id": 74492690, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])\n" }, { "answer_id": 74492799, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 2, "selected": true, "text": "with open('frames_stats.csv','a') as csvfile:\n np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20541188/" ]
74,492,390
<p>let's say I have these many dataset (let's imagine 1000 datasets) :</p> <pre><code>df1 = data.frame(x = 1:10) df2 = data.frame(x = 2:11) df3 = data.frame(x = 3:5) df4 = data.frame(x = 11:20) </code></pre> <p>I want to create a list that is called L as follows</p> <pre><code>L = list(df1,df2,df3,df4) </code></pre> <p>but if I have thousands of dataframes, it would be difficult to write each dataframe namein the list. Would take forever. Would like a function that can make creating this list easier. Thanks.</p>
[ { "answer_id": 74492690, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])\n" }, { "answer_id": 74492799, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 2, "selected": true, "text": "with open('frames_stats.csv','a') as csvfile:\n np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19720935/" ]
74,492,431
<p>Yo! I am learning requests in python and i get a problem!</p> <p>when i try to get status code from the url i dont receive answer</p> <p>When I run the program, it doesn't finish or return anything. Below is a picture of the terminal and my code.</p> <pre><code>import requests import socket old_getaddrinfo = socket.getaddrinfo def new_getaddrinfo(*args, **kwargs): responses = old_getaddrinfo(*args, **kwargs) return [response for response in responses if response[0] == socket.AF_INET] socket.getaddrinfo = new_getaddrinfo res = requests.get('https://www.americanas.com.br/') print(res.status_code) if res.status_code ==200: print('O servidou disse OK') else: print('O servidor falhou!') </code></pre> <p>observation:</p> <p>I've also tried without the first part of the code,</p>
[ { "answer_id": 74492690, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])\n" }, { "answer_id": 74492799, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 2, "selected": true, "text": "with open('frames_stats.csv','a') as csvfile:\n np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20470305/" ]
74,492,437
<p><a href="https://i.stack.imgur.com/KlYZh.png" rel="nofollow noreferrer">my problem</a></p> <p>I am on windows 10 I tried reinstalling .net multiple times and re installed vscode i am really despreate for soloutions now</p>
[ { "answer_id": 74492690, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "array_to_save=np.array([[shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]])\n" }, { "answer_id": 74492799, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 2, "selected": true, "text": "with open('frames_stats.csv','a') as csvfile:\n np.savetxt(csvfile,array_to_save.reshape((1, 4)),delimiter=',')\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540532/" ]
74,492,441
<p>I have a table of properties:</p> <pre><code>+----+-----------------------------+ | prop_id | prop_name | +---------+------------------------+ | 1 | Cottage | +---------+------------------------+ | 2 | Mountain House | +---------+------------------------+ | 3 | Beach house | +---------+------------------------+ </code></pre> <p>A table of accessories:</p> <pre><code>+----+-----------------------------+ | acc_id | acc_name | +---------+------------------------+ | GAR | With garden | +---------+------------------------+ | TER | With terrace | +---------+------------------------+ | REN | Recently renovated | +---------+------------------------+ </code></pre> <p>A table that relates properties and accessories (properties2accessories):</p> <pre><code>+----+--------------+ | prop_id | acc_id | +---------+---------+ | 1 | GAR | +---------+---------+ | 1 | REN | +---------+---------+ | 2 | GAR | +---------+---------+ | 2 | REN | +---------+---------+ | 2 | TER | +---------+---------+ | 3 | GAR | +---------+---------+ | 3 | TER | +---------+---------+ </code></pre> <p>I need all the properties that have <em>ALL</em> the accessories that I pass as parameters.</p> <p>Correct examples:</p> <p>a) Properties with &quot;Garden&quot; and &quot;Recently renovated&quot;:</p> <p>I should get props: 1, 2</p> <p>b) Properties with &quot;Garden&quot; and &quot;Terrace&quot;:</p> <p>I should get props: 2, 3</p> <p>I try:</p> <pre><code>SELECT * FROM properties2accessories WHERE acc_id IN ('GAR', 'REN'); </code></pre> <p>but this get prop 3 too, that not has &quot;Recently renovated&quot;</p> <p>I'm using Postgres 13</p> <p>Any helps?</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383908/" ]
74,492,447
<p>I'm trying to extract text string from a &lt;p&gt; tag, the text string I'm interested in is separated by a &lt;br&gt; tag.</p> <pre><code>&lt;div id=&quot;foo&quot;&gt; &lt;p&gt; &quot; Data 1 : Lorem&quot; &lt;br&gt; &lt;br&gt; &quot; Data 2 : Ipsum&quot; &lt;br&gt; &lt;/p&gt; &lt;div&gt; </code></pre> <p>Desired output :</p> <pre><code>Lorem </code></pre> <p>Using <code>bs4</code>, I'm stuck at :</p> <pre><code>collection1 = soup.select('div#foo &gt; p:-soup-contains(&quot;Data 1 : &quot;)').replace(&quot;Data 1 : &quot;,&quot;&quot;).text.strip() </code></pre> <p>I don't know how to preceed to set a delimiter for the double quotes or the <code>&lt;br&gt;</code> tag? Any idea on how to proceed to get the desired output ?</p> <p>I'm trying to scrap the details information of <a href="https://www.messika.com/fr/bracelet-pm-diamant-or-rose-d-vibes-12350-pg" rel="nofollow noreferrer">this page</a>. I've tried :</p> <pre><code>try: collection = soup.select('div#ui-accordion-1-panel-1 &gt; div.tab-content-wrapper &gt; p:-soup-contains(&quot;Collection&quot;)').text.strip() except: collection = &quot;&quot; print(&quot;No Collection&quot;) </code></pre> <p>Expecting to get the whole <code>&lt;p&gt;</code> tag but exception occured. I've been using this snippet on other scraps with Selenium and it did work.</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11465465/" ]
74,492,459
<p>I have a widget that, no matter what constraints I place upon it and other widgets, including the addition of barriers, always positions itself at the top of the layout.</p> <p>This is a fairly simple arrangement of two rows of two elements each, not aligned column wise. The first element in each row is a TextView label, the second an input (Spinner). There is also a lone TextView title above the first row stretching all the way across. By my understanding and previous experience with constraint layout, this shouldn't require a barrier between the rows, and that was my initial version.</p> <p>This is the design view, where the selected element (&quot;Credentials&quot;) is supposed to be in the second row but instead appears <em>above</em> the first row, over top of the title TextView (&quot;PKIX&quot;):</p> <p><a href="https://i.stack.imgur.com/ahGqa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ahGqa.png" alt="enter image description here" /></a></p> <p>Actual result in the emulator looks much the same. The selected &quot;Credentials&quot; element is the fourth of five elements in the XML layout below. All of the other elements are in the right place.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;TextView android:id=&quot;@+id/addsrv_pkix_title&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; android:background=&quot;@drawable/bottomborder&quot; android:text=&quot;PKIX&quot; android:textAlignment=&quot;center&quot; android:layout_marginHorizontal=&quot;10sp&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_trust_lbl&quot; /&gt; &lt;TextView android:id=&quot;@+id/addsrv_trust_lbl&quot; android:text=&quot;Trust&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:paddingHorizontal=&quot;10sp&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/addsrv_trust_spin&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_pkix_title&quot; app:layout_constraintBaseline_toBaselineOf=&quot;@+id/addsrv_trust_spin&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_cred_lbl&quot; /&gt; &lt;Spinner android:id=&quot;@+id/addsrv_trust_spin&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; app:layout_constraintStart_toEndOf=&quot;@+id/addsrv_trust_lbl&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_pkix_title&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_cred_spin&quot; /&gt; &lt;TextView android:id=&quot;@+id/addsrv_cred_lbl&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;4dp&quot; android:paddingHorizontal=&quot;10sp&quot; android:text=&quot;Credentials&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/addsrv_cred_spin&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_trust_lbl&quot; app:layout_constraintBaseline_toBaselineOf=&quot;@+id/addsrv_cred_spin&quot; /&gt; &lt;Spinner android:id=&quot;@+id/addsrv_cred_spin&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; app:layout_constraintStart_toEndOf=&quot;@+id/addsrv_cred_lbl&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_trust_spin&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> <p>I'm perplexed. The <code>addsrv_cred_lbl</code> TextView (&quot;Credentials&quot;) is:</p> <ul> <li>Start aligned with parent.</li> <li>End aligned with the <code>addsrv_cred_spin</code> spinner, which appears correctly positioned; this alignment is reciprocated to create a horizontal chain. They are also baseline aligned.</li> <li>Top aligned with the bottom of the TextView above it, <code>addsrv_trust_lbl</code>. This alignment is also reciprocated.</li> </ul> <p>There's no bottom alignment yet (there's another row to go); bottom aligning it with the parent makes no difference unless I bottom align the spinner from the same row, in which case the result goes from bad to worse.</p> <p>Since this did not work, I tried to use a barrier between the rows. If I use it as a &quot;top&quot;, with the second row widgets as the constraint referents, the barrier appears at the top, above the title, regardless of what constraints are used to position it below the first row. Used as a &quot;bottom&quot;, with the first row widgets referenced and the second row chained below it (which is more logical), things are a little bit better in that the barrier appears in the right place -- but the &quot;Credentials&quot; widget is still up top.</p> <p>The design view of this looks exactly the same as the previous one except the barrier is visible below the first row. In the XML, I aslo added <code>optimizationLevel=&quot;none&quot;</code> after having read this can help with misbehaving barriers (but it made no difference). There's also a few stylistic elements added back here (such as font size) I removed for brevity before.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; app:layout_optimizationLevel=&quot;none&quot; &gt; &lt;TextView android:id=&quot;@+id/addsrv_pkix_title&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; android:background=&quot;@drawable/bottomborder&quot; android:backgroundTint=&quot;@color/tbar&quot; android:text=&quot;PKIX&quot; android:textAlignment=&quot;center&quot; android:textSize=&quot;@dimen/addsrv_bigfont&quot; android:textColor=&quot;@color/titleText&quot; android:layout_marginHorizontal=&quot;10sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_trust_lbl&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;TextView android:id=&quot;@+id/addsrv_trust_lbl&quot; android:text=&quot;Trust&quot; android:textSize=&quot;@dimen/addsrv_fontsz&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:paddingHorizontal=&quot;10sp&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/addsrv_trust_spin&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_pkix_title&quot; app:layout_constraintBaseline_toBaselineOf=&quot;@+id/addsrv_trust_spin&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_bar1&quot; app:layout_constraintHorizontal_chainStyle=&quot;packed&quot; /&gt; &lt;Spinner android:id=&quot;@+id/addsrv_trust_spin&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; app:layout_constraintStart_toEndOf=&quot;@+id/addsrv_trust_lbl&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_pkix_title&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_bar1&quot; /&gt; &lt;androidx.constraintlayout.widget.Barrier android:id=&quot;@+id/addsrv_bar1&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; app:barrierDirection=&quot;bottom&quot; app:constraint_referenced_ids=&quot;addsrv_trust_lbl,addsrv_trust_spin&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/addsrv_cred_lbl&quot; /&gt; &lt;TextView android:id=&quot;@+id/addsrv_cred_lbl&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:paddingHorizontal=&quot;10sp&quot; android:text=&quot;Credentials&quot; android:textSize=&quot;@dimen/addsrv_fontsz&quot; app:layout_constraintBaseline_toBaselineOf=&quot;@+id/addsrv_cred_spin&quot; app:layout_constraintEnd_toStartOf=&quot;@+id/addsrv_cred_spin&quot; app:layout_constraintHorizontal_chainStyle=&quot;packed&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_bar1&quot; /&gt; &lt;Spinner android:id=&quot;@+id/addsrv_cred_spin&quot; android:layout_width=&quot;0dp&quot; android:layout_height=&quot;wrap_content&quot; app:layout_constraintStart_toEndOf=&quot;@+id/addsrv_cred_lbl&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/addsrv_bar1&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> <p><strong>Am I correct in observing that some of the constraints on <code>addsrv_cred_lbl</code> are being completely ignored?</strong> Doesn't <code>topToBottom</code> mean that the top of the widget is aligned with the bottom of the other? Instead, it seems simply to mean that they will be connected with a squiggly, potentially curved and convoluted line in the design view, and the spacial relation of the two widgets is arbitrary, such that the semantic logic might as well be inverted, &quot;top = bottom, bottom = top&quot;, etc.</p> <p>Please note that <strong>I do not want to use absolute values to position anything</strong>. If the only way to get this to work is to do that, constraint layout seems a complete waste of time even in this simple case, and I'd rather just stack some liner layouts.</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1151724/" ]
74,492,464
<p>i have started this code, which looks in worksheet PCrun for &quot;yes&quot; in cell D2 then then copies A1:C9 and paste as an image to worksheet PCexport starting at cell A1. This works but there are a few more steps i am stuck on. I would like it to move on to the next range of cells A10:C18 looking in cell D11 for a yes. This needs to continue i.e D2 - C1:C9 D11 - A10:C28 D20 - A19:C27 and so on adding 9 each time and coping if there is a yes in D and pasting as an picture to the next avalible cell in worksheet PCexport.</p> <pre><code>Sub CopyIf() Dim LastRow As Long, i As Long, erow As Long Dim wsStr As String Dim ws As Worksheet, wsC As Worksheet Dim wb As Workbook, wbM As Workbook Dim C As Range LastRow = Worksheets(&quot;PCexport&quot;).Range(&quot;A&quot; &amp; Rows.Count).End(xlUp).Row Set wb = ActiveWorkbook Set wsC = wb.Sheets(&quot;PCrun&quot;) erow = wsC.Cells(Rows.Count, 1).End(xlUp).Row Worksheets(&quot;PCrun&quot;).Activate For i = 1 To LastRow If wsC.Cells(2, 4).Value = &quot;YES&quot; Then erow = erow + 9 wsC.Range(wsC.Cells(1, 1), wsC.Cells(9, 3)).CopyPicture 'avoid select Sheets(&quot;PCexport&quot;).Range(&quot;A1&quot;).PasteSpecial End If Next i End Sub </code></pre>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16504005/" ]
74,492,475
<p>Write a function that returns only negative odd numbers from an array.</p> <pre><code>const arr = [4, -7, -6] </code></pre> <p>I first tried:</p> <pre><code>let negativeOdd = arr.filter(n =&gt; n % 2 === 1 &amp;&amp; n &lt; 0); return negativeOdd; </code></pre> <p>result was an empty array. <code>[]</code>. The answer should be <code>[-5]</code>.</p> <p>But when I replaced <code>n % 2 === 1</code> with <code>n % 2 !== 0</code>, it workded. I am new to JS and was hopeing somenone could help me understand why this is happening. Thank you.</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20504727/" ]
74,492,512
<p>I'm creating a quiz and I try to shuffle answers but one of them keeps repeating. Up to 4 times, sometimes even four (I have 4 answers overall). I have a project deadline soon, please help me. Thank you in advance</p> <p>`</p> <pre><code>const questions = [{ question: &quot;What is the name of Ellie's mom?&quot;, answer: [&quot;Jessica&quot;, &quot;Monica&quot;, &quot;Anna&quot;, &quot;Tess&quot;], correct: &quot;3&quot;, }, { question: &quot;Around how old is Joel in The Last of Us Part II?&quot;, answer: [&quot;40s&quot;, &quot;50s&quot;, &quot;60s&quot;, &quot;70s&quot;], correct: &quot;2&quot;, }, { question: &quot;What is Manny's rank in the WLF?&quot;, answer: [&quot;Sergeant&quot;, &quot;Captain&quot;, &quot;Lieutenant&quot;, &quot;Corporal&quot;], correct: &quot;3&quot;, }, { question: &quot;What item does Ellie keep of Sam's that can be seen in her room at the start of The Last of Us Part II?&quot;, answer: [&quot;PS3&quot;, &quot;Toy robot&quot;, &quot;Cassette player&quot;, &quot;Animals of the Past book&quot;], correct: &quot;2&quot;, }, { question: &quot;Which game does NOT get referenced in The Last of US Part II?&quot;, answer: [&quot;Deus Ex&quot;, &quot;God of War&quot;, &quot;Jak and Daxter&quot;, &quot;Crash Bandicoot&quot;], correct: &quot;2&quot;, } ]; /* Getting elements from the DOM */ let headerContainer = document.getElementById(&quot;header&quot;); let listContainer = document.getElementById(&quot;list&quot;); let submitBtn = document.getElementById(&quot;submit&quot;); let startBtn = document.getElementById(&quot;start&quot;); let quiz = document.getElementById(&quot;quiz&quot;); let score = 0; let questionIndex = 0; startBtn.onclick = function () { startBtn.classList.add(&quot;hidden&quot;); quiz.classList.remove(&quot;hidden&quot;); document.getElementById(&quot;description&quot;).classList.add(&quot;hidden&quot;); }; function clearPage() { headerContainer.innerHTML = &quot;&quot;; listContainer.innerHTML = &quot;&quot;; } clearPage(); showQuestion(); submitBtn.onclick = checkAnswer; /*A function to show questions*/ function showQuestion() { /*Show a question*/ let headerTemplate = `&lt;h2 class=&quot;title&quot;&gt;%title%&lt;/h2&gt;`; let title = headerTemplate.replace('%title%', questions[questionIndex].question); headerContainer.innerHTML = title; /*Show answers*/ let answerNumber = 1; for (var item of questions[questionIndex].answer) { const questionTemplate = `&lt;li&gt; &lt;label&gt; &lt;input value=&quot;%number%&quot; type=&quot;radio&quot; class=&quot;answer&quot; name=&quot;answer&quot;&gt; &lt;span&gt;%answer%&lt;/span&gt; &lt;/label&gt; &lt;/li&gt;`; let answers=questions[questionIndex].answer; let currentIndex = answers.length, randomIndex; randomIndex = Math.floor(Math.random() * currentIndex); let answerText = questionTemplate.replace('%answer%', answers[randomIndex]).replace(&quot;%number%&quot;, answerNumber); listContainer.innerHTML += answerText; answerNumber++; } let progress = `&lt;p&gt;${questionIndex+1} out of ${questions.length}&lt;/p&gt;`; document.getElementById(&quot;progress&quot;).innerHTML = progress; let scoreBoard = `&lt;p&gt;Score: ${score} out of ${questions.length}&lt;/p&gt;`; document.getElementById(&quot;score&quot;).innerHTML = scoreBoard; } </code></pre> <p>`</p> <p>I tried a for loop and I tried to shuffle array different ways that I found on the internet but all of them work the way I have now.</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450499/" ]
74,492,519
<p>I don' t know how to insert a row in the child table that has an attribute that references to the column ID (primary key of the father Table)in the same transaction because i dont know the father primary key if i don't commit the transaction. Is there a way to solve this problem?</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18805621/" ]
74,492,523
<p>That is my manifest code which download, install and remove installer on a host.</p> <pre><code>class googlechrome_2 { package { 'GoogleChrome': ensure =&gt; installed, source =&gt; 'C:\Soft\ChromeSetup.msi', install_options =&gt; ['/qn'], require =&gt; File['GoogleChromeMsi'], } file { 'GoogleChromeMsi': ensure =&gt; file, path =&gt; 'C:\Soft\ChromeSetup.msi', source =&gt; 'puppet:///files/production/ChromeSetup.msi', } exec { 'msi_removing': command =&gt; 'C:\Windows\System32\cmd.exe /c del C:\Soft\ChromeSetup.msi', } } </code></pre> <p>In this case my windows host always download chromesetup.msi regardless if google chrome already installed or not. How can I realize kind of &quot;if condition&quot; here to avoid downloading msi package each time in case if this package already installed?</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450805/" ]
74,492,553
<p>I've actually read every stackoverflow post related to my problem, but I can't solve it, every attempt brings me a new problem.</p> <p>This is the <strong>structure</strong>: <a href="https://i.stack.imgur.com/8ZN75.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8ZN75.jpg" alt="enter image description here" /></a></p> <p><strong>package.json</strong>:</p> <pre><code>{ .. &quot;type&quot;: &quot;module&quot;, &quot;main&quot;: &quot;index.ts&quot;, &quot;scripts&quot;: { &quot;dev&quot;: &quot;ts-node-esm ./src/index.ts&quot;, &quot;start&quot;: &quot;ts-node-esm ./src/index.ts&quot;, &quot;build&quot;: &quot;tsc --build&quot;, &quot;clean&quot;: &quot;tsc --build --clean&quot; }, ... } </code></pre> <p><strong>tsconfig.json</strong>:</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;module&quot;: &quot;esnext&quot;, &quot;noImplicitAny&quot;: false, &quot;sourceMap&quot;: true, &quot;resolveJsonModule&quot;: true, &quot;moduleResolution&quot;: &quot;Node&quot;, &quot;allowSyntheticDefaultImports&quot;: true, &quot;esModuleInterop&quot;: true, &quot;outDir&quot;: &quot;dist&quot;, }, &quot;include&quot;: [ &quot;src/*&quot; ] } </code></pre> <p><strong>index.ts</strong> imports <strong>myModule.ts</strong> like this:</p> <pre><code>... import request from 'request'; import {connection} from &quot;../config/db.js&quot;; import { MyModule } from '../assets/ts/myModule.js'; </code></pre> <p>I start the development app with this command and everything works fine::</p> <pre><code>npm run dev &gt; myApp@1.0.0 dev &gt; ts-node-esm ./src/index.ts </code></pre> <p>now i want to build the application for production. i wanted to use pm2 but i had several problems.</p> <p>what is the best approach and the most performing solution to put my application into production?</p>
[ { "answer_id": 74492636, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT\n\"prop_id\"\nFROM properties2accessories p \nWHERE (\"acc_id\" = 'GAR') \nAND EXISTS (SELECT 1 FROM properties2accessories WHERE \"acc_id\" = 'REN' AND \"prop_id\" = p.\"prop_id\")\n SELECT 2\n" }, { "answer_id": 74492826, "author": "Bjarni Ragnarsson", "author_id": 11993679, "author_profile": "https://Stackoverflow.com/users/11993679", "pm_score": 1, "selected": false, "text": "SELECT prop_id from (\n select prop_id, array_agg(acc_id) acc_array\n FROM properties2accessories\n group by prop_id) d\nWHERE array['GAR', 'REN'] <@ acc_array;\n" }, { "answer_id": 74492960, "author": "Frank Heikens", "author_id": 271959, "author_profile": "https://Stackoverflow.com/users/271959", "pm_score": 1, "selected": false, "text": "SELECT prop_id\nFROM properties2accessories\nWHERE acc_id IN ('GAR', 'REN')\nGROUP BY prop_id\nHAVING ARRAY_AGG(acc_id) @> ARRAY['GAR', 'REN'];\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5600753/" ]
74,492,557
<p>I've written a program to randomly assign teams to four people for a World Cup sweepstakes. The code works fine, but it's ugly. How do I shuffle the variables Seed1, Seed2, ... Seed8 with a loop? How do I print which teams have been assigned to each player with more professional looking code?</p> <pre><code>import random Teams = [&quot;Alice&quot;, &quot;Bob&quot;,&quot;Charlie&quot;, &quot;Delilah&quot;] random.shuffle(Teams) Seed1 = [&quot;Brazil&quot;, &quot;Argentina&quot;, &quot;France&quot;, &quot;Spain&quot;] Seed2 = [&quot;England&quot;, &quot;Germany&quot;, &quot;Netherlands&quot;, &quot;Portugal&quot;] Seed3 = [&quot;Belgium&quot;, &quot;Denmark&quot;, &quot;Uruguay&quot;, &quot;Croatia&quot;] Seed4 = [&quot;Serbia&quot;, &quot;Switzerland&quot;, &quot;Senegal&quot;, &quot;Mexico&quot;] Seed5 = [&quot;USA&quot;, &quot;Poland&quot;, &quot;Ecuador&quot;, &quot;Morocco&quot;] Seed6 = [&quot;Wales&quot;, &quot;Japan&quot;, &quot;Ghana&quot;, &quot;Canada&quot;] Seed7 = [&quot;Qatar&quot;, &quot;South Korea&quot;, &quot;Iran&quot;, &quot;Cameroon&quot;] Seed8 = [&quot;Australia&quot;, &quot;Saudi Arabia&quot;, &quot;Tunisia&quot;, &quot;Costa Rica&quot;] random.shuffle(Seed1) random.shuffle(Seed2) random.shuffle(Seed3) random.shuffle(Seed4) random.shuffle(Seed5) random.shuffle(Seed6) random.shuffle(Seed7) random.shuffle(Seed8) for a in range(4): print(Teams[a] + &quot; = &quot; +Seed1[a]+ &quot; , &quot; + Seed2[a]+ &quot; , &quot; + Seed3[a]+ &quot; , &quot; + Seed4[a]+ &quot; , &quot; + Seed5[a]+ &quot; , &quot; + Seed6[a]+ &quot; , &quot; + Seed7[a]+ &quot; , &quot; + Seed8[a]) </code></pre> <p>To be clear I'm looking for something like:</p> <pre><code>for a in range(1,9): random.shuffle(range[a]) </code></pre> <p>but that throws up an error</p>
[ { "answer_id": 74492648, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 3, "selected": true, "text": "import random\n\nteams = [\"Alice\", \"Bob\", \"Charlie\", \"Delilah\"]\nrandom.shuffle(teams)\n\nseeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n [\"Belgium\", \"Denmark\", \"Uruguay\", \"Croatia\"],\n [\"Serbia\", \"Switzerland\", \"Senegal\", \"Mexico\"],\n [\"USA\", \"Poland\", \"Ecuador\", \"Morocco\"],\n [\"Wales\", \"Japan\", \"Ghana\", \"Canada\"],\n [\"Qatar\", \"South Korea\", \"Iran\", \"Cameroon\"],\n [\"Australia\", \"Saudi Arabia\", \"Tunisia\", \"Costa Rica\"],\n]\nfor seed in seeds:\n random.shuffle(seed)\n\nfor i in range(4):\n print(f\"{teams[i]} =\", \", \".join(seed[i] for seed in seeds))\n" }, { "answer_id": 74492659, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "Teams = [\"Alice\", \"Bob\",\"Charlie\", \"Delilah\"]\n seeds = [seed1, seed2, ...]\n seed1 = seeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n ...\n ]\n for seed in seeds:\n random.shuffle(seed)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14156986/" ]
74,492,599
<p>i need help to shorten this code a lot</p> <p>im trying to make the month selection witch is repeating shorter or into a function preferable but cant make it work, id like to make the month selection a function but cant due to having to call in different csv files what you guys got? csv files (<a href="https://send.tresorit.com/a#1NoM7CSW08PLTTNbtHMcHw" rel="nofollow noreferrer">https://send.tresorit.com/a#1NoM7CSW08PLTTNbtHMcHw</a>) password:&quot;csvtest&quot;</p> <pre><code>import pandas as pd def year(): print(&quot;Type '2018' to select the data of 2018&quot;) print(&quot;Type '2019' to select the data of 2019&quot;) print(&quot;Type '2020' to select the data of 2020&quot;) print(&quot;Type '0' to close selection&quot;) def select_the_month_of_Etherium(): year() while True: b=int(input(&quot;Select the year:&quot;)) if b == 2018: df8 = pd.read_csv(&quot;C:\\Users\\seena\\OneDrive\\Desktop\\2022-11-18 20.55.00\\Project csv ETHERIUM2018&quot; &quot;.csv&quot;)#importing a csv file a = int(input(&quot;Enter the month(Number Only):&quot;)) print(&quot;Type '0' to close selection&quot;) if a == 1: c = df8.loc[0] print(c) elif a == 2: c = df8.loc[1] print(c) elif a == 3: c = df8.loc[2] print(c) elif a == 4: c = df8.loc[3] print(c) elif a == 5: c = df8.loc[4] print(c) elif a == 6: c = df8.loc[5] print(c) elif a == 7: c = df8.loc[6] print(c) elif a == 8: c = df8.loc[7] print(c) elif a == 9: c = df8.loc[8] print(c) elif a == 10: c = df8.loc[9] print(c) elif a == 11: c = df8.loc[10] print(c) elif a == 12: c = df8.loc[11] print(c) else: print(&quot;Invalid choice&quot;) elif b == 2019: df8 = pd.read_csv(&quot;C:\\Users\\seena\\OneDrive\\Desktop\\2022-11-18 20.55.00\\Project csv ETHERIUM Y(2).csv&quot;)#importing a csv file a = int(input(&quot;Enter the month(Number Only):&quot;)) print(&quot;Type '0' to close selection&quot;) if a == 1: c = df8.loc[0] print(c) elif a == 2: c = df8.loc[1] print(c) elif a == 3: c = df8.loc[2] print(c) elif a == 4: c = df8.loc[3] print(c) elif a == 5: c = df8.loc[4] print(c) elif a == 6: c = df8.loc[5] print(c) elif a == 7: c = df8.loc[6] print(c) elif a == 8: c = df8.loc[7] print(c) elif a == 9: c = df8.loc[8] print(c) elif a == 10: c = df8.loc[9] print(c) elif a == 11: c = df8.loc[10] print(c) elif a == 12: c = df8.loc[11] print(c) else: print(&quot;Invalid choice&quot;) elif b == 2020: df8 = pd.read_csv(&quot;C:\\Users\\seena\\OneDrive\\Desktop\\2022-11-18 20.55.00\\Project csv ETHERIUM Y(3).csv&quot;)#importing a csv file a = int(input(&quot;Enter the month(Number Only):&quot;)) print(&quot;Type '0' to close selection&quot;) if a == 1: c = df8.loc[0] print(c) elif a == 2: c = df8.loc[1] print(c) elif a == 3: c = df8.loc[2] print(c) elif a == 4: c = df8.loc[3] print(c) elif a == 5: c = df8.loc[4] print(c) elif a == 6: c = df8.loc[5] print(c) elif a == 7: c = df8.loc[6] print(c) elif a == 8: c = df8.loc[7] print(c) elif a == 9: c = df8.loc[8] print(c) elif a == 10: c = df8.loc[9] print(c) elif a == 11: c = df8.loc[10] print(c) elif a == 12: c = df8.loc[11] print(c) else: print(&quot;Invalid choice&quot;) elif b == 0: break else : print(&quot;Invalid choice&quot;) select_the_month_of_Etherium() </code></pre>
[ { "answer_id": 74492648, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 3, "selected": true, "text": "import random\n\nteams = [\"Alice\", \"Bob\", \"Charlie\", \"Delilah\"]\nrandom.shuffle(teams)\n\nseeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n [\"Belgium\", \"Denmark\", \"Uruguay\", \"Croatia\"],\n [\"Serbia\", \"Switzerland\", \"Senegal\", \"Mexico\"],\n [\"USA\", \"Poland\", \"Ecuador\", \"Morocco\"],\n [\"Wales\", \"Japan\", \"Ghana\", \"Canada\"],\n [\"Qatar\", \"South Korea\", \"Iran\", \"Cameroon\"],\n [\"Australia\", \"Saudi Arabia\", \"Tunisia\", \"Costa Rica\"],\n]\nfor seed in seeds:\n random.shuffle(seed)\n\nfor i in range(4):\n print(f\"{teams[i]} =\", \", \".join(seed[i] for seed in seeds))\n" }, { "answer_id": 74492659, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "Teams = [\"Alice\", \"Bob\",\"Charlie\", \"Delilah\"]\n seeds = [seed1, seed2, ...]\n seed1 = seeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n ...\n ]\n for seed in seeds:\n random.shuffle(seed)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20541297/" ]
74,492,619
<p>I'm seeing a difference in text/font quality between MainMenu and ContextMenu items in my desktop app. In the screenshot below, the first line was taken from a ContextMenu and the second line from a MainMenu (which arguably looks much better). The third line is from a ContextMenu with <code>TextOptions.TextFormattingMode=&quot;Display&quot;</code> applied, and while this is a slight improvement on the first it's still not as good as the MainMenu.</p> <p><a href="https://i.stack.imgur.com/luFJH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/luFJH.png" alt="enter image description here" /></a></p> <p>I've used the &quot;Snoop&quot; tool to confirm that font styling is the same between the main menu and context menu (size, weight, family, etc.) so I'm assuming this is a rendering quality/clear type issue?</p> <p>The font family is &quot;Roboto&quot; (as I'm using the &quot;<a href="https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit" rel="nofollow noreferrer">Material Design in XAML</a>&quot; NuGet package), and it is a .Net6 project if that makes a difference.</p>
[ { "answer_id": 74492648, "author": "Matteo Zanoni", "author_id": 13384774, "author_profile": "https://Stackoverflow.com/users/13384774", "pm_score": 3, "selected": true, "text": "import random\n\nteams = [\"Alice\", \"Bob\", \"Charlie\", \"Delilah\"]\nrandom.shuffle(teams)\n\nseeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n [\"Belgium\", \"Denmark\", \"Uruguay\", \"Croatia\"],\n [\"Serbia\", \"Switzerland\", \"Senegal\", \"Mexico\"],\n [\"USA\", \"Poland\", \"Ecuador\", \"Morocco\"],\n [\"Wales\", \"Japan\", \"Ghana\", \"Canada\"],\n [\"Qatar\", \"South Korea\", \"Iran\", \"Cameroon\"],\n [\"Australia\", \"Saudi Arabia\", \"Tunisia\", \"Costa Rica\"],\n]\nfor seed in seeds:\n random.shuffle(seed)\n\nfor i in range(4):\n print(f\"{teams[i]} =\", \", \".join(seed[i] for seed in seeds))\n" }, { "answer_id": 74492659, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "Teams = [\"Alice\", \"Bob\",\"Charlie\", \"Delilah\"]\n seeds = [seed1, seed2, ...]\n seed1 = seeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n ...\n ]\n for seed in seeds:\n random.shuffle(seed)\n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981831/" ]
74,492,631
<p>I need some guidance on what to use for a simple app that shows and saves speed.</p> <p>Right now I have an app with main activity and LocationService. It does the saving well but i can't find a way to update the UI continuously. I have made other apps with the location code in mainActivity but I want the transmission to continue when screen is closed, So i tried a service but it looks like ill have to implement location provider in mainActivity for the UI?</p> <p>Is there a functionality im missing?</p> <p>How do I mkae this app?</p> <p>Here is my lattest version i CAN'T send speed back to UI.</p> <p><strong>LocationService</strong></p> <pre><code>public class LocationService extends Service { FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference(Build.MANUFACTURER+&quot; &quot;+Build.DEVICE); DatabaseReference myLiveRef = myRef.child(&quot;LiveSpeed&quot;); DatabaseReference myPastsRef = myRef.child(&quot;PastSpeeds&quot;); FusedLocationProviderClient fusedLocationClient; LocationRequest locationRequest; LocationCallback locationCallback; private float speed; private final IBinder mBinder = new MyBinder(); class MyBinder extends Binder { public LocationService getService(){ return LocationService.this; } } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); stopSelf(); } @Override public IBinder onBind(Intent intent) { Log.d(&quot;TAGZ&quot;,&quot;onBInd&quot;); return mBinder; } private void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()); } @Override public void onCreate() { super.onCreate(); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); if (Build.VERSION.SDK_INT &gt; Build.VERSION_CODES.O) createNotificationChanel() ; else startForeground( 1, new Notification() ); locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1000) .setWaitForAccurateLocation(false) .setMinUpdateIntervalMillis(500) .setMaxUpdateDelayMillis(1500) .build(); locationCallback = new LocationCallback() { @Override public void onLocationResult(@NonNull LocationResult locationResult) { Location location = locationResult.getLastLocation(); speed = location.getSpeed()*3.6f; myLiveRef.setValue(speed); DatabaseReference newPastRef = myPastsRef.push(); newPastRef.setValue(String.valueOf(Calendar.getInstance().getTime())+&quot; |||||||| &quot;+ speed +&quot; KM/H&quot;); } }; startLocationUpdates(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); fusedLocationClient.removeLocationUpdates(locationCallback); } @RequiresApi(api = Build.VERSION_CODES.O) private void createNotificationChanel() { String notificationChannelId = &quot;Location channel id&quot;; String channelName = &quot;Background Service&quot;; NotificationChannel chan = new NotificationChannel( notificationChannelId, channelName, NotificationManager.IMPORTANCE_NONE ); chan.setLightColor(Color.BLUE); chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(chan); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, notificationChannelId); Notification notification = notificationBuilder.setOngoing(true) .setContentTitle(&quot;Location updates:&quot;) .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .build(); startForeground(2, notification); } } </code></pre> <p><strong>MainActivity</strong></p> <pre><code>public class MainActivity extends AppCompatActivity { private static final int MY_FINE_LOCATION_REQUEST = 99; private static final int MY_BACKGROUND_LOCATION_REQUEST = 100; TextView textView; Intent mServiceIntent; Button startServiceBtn, stopServiceBtn; private LocationService mLocationService; private boolean mBound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startServiceBtn = findViewById(R.id.start_service_btn); stopServiceBtn = findViewById(R.id.stop_service_btn); textView = findViewById(R.id.textView); startServiceBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle(&quot;Background permission&quot;); alertDialog.setMessage(getString(R.string.background_location_permission_message)); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, &quot;Start service anyway&quot;, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { starServiceFunc(); dialog.dismiss(); } }); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, &quot;Grant background Permission&quot;, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { requestBackgroundLocationPermission(); dialog.dismiss(); } }); alertDialog.show(); }else if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED){ starServiceFunc(); } } else{ starServiceFunc(); } }else if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle(&quot;ACCESS_FINE_LOCATION&quot;); alertDialog.setMessage(&quot;Location permission required&quot;); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, &quot;Ok&quot;, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { requestFineLocationPermission(); dialog.dismiss(); } }); alertDialog.show(); } else { requestFineLocationPermission(); } } } }); stopServiceBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { stopServiceFunc(); } }); } @Override protected void onResume() { super.onResume(); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { LocationService.MyBinder binder = (LocationService.MyBinder) service; mLocationService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName name) { mBound = false; } }; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); Toast.makeText(this, Integer.toString(requestCode), Toast.LENGTH_LONG).show(); if ( requestCode == MY_FINE_LOCATION_REQUEST){ if (grantResults.length !=0 /*grantResults.isNotEmpty()*/ &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { requestBackgroundLocationPermission(); } } else { Toast.makeText(this, &quot;ACCESS_FINE_LOCATION permission denied&quot;, Toast.LENGTH_LONG).show(); if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse(&quot;lauchmodesdemo.youtube.codetutor.com.speedtest&quot;) )); } } }else if (requestCode == MY_BACKGROUND_LOCATION_REQUEST){ if (grantResults.length!=0 /*grantResults.isNotEmpty()*/ &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, &quot;Background location Permission Granted&quot;, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, &quot;Background location permission denied&quot;, Toast.LENGTH_LONG).show(); } } } private void starServiceFunc(){ mLocationService = new LocationService(); mServiceIntent = new Intent(this, mLocationService.getClass()); if (!Util.isMyServiceRunning(mLocationService.getClass(), this)) { startService(mServiceIntent); bindService(mServiceIntent,connection, Context.BIND_AUTO_CREATE); Toast.makeText(this, getString(R.string.service_start_successfully), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.service_already_running), Toast.LENGTH_SHORT).show(); } } private void stopServiceFunc(){ if (Util.isMyServiceRunning(mLocationService.getClass(), this)) { stopService(mServiceIntent); Toast.makeText(this, &quot;Service stopped!!&quot;, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, &quot;Service is already stopped!!&quot;, Toast.LENGTH_SHORT).show(); } } private void requestBackgroundLocationPermission() { if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, MY_BACKGROUND_LOCATION_REQUEST); } } private void requestFineLocationPermission() { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, MY_FINE_LOCATION_REQUEST); } } </code></pre> <p><strong>Util</strong></p> <pre><code>public class Util { public static boolean isMyServiceRunning(Class&lt;?&gt; serviceClass, Activity mActivity) { ActivityManager manager = (ActivityManager) mActivity.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } } </code></pre>
[ { "answer_id": 74492924, "author": "Boyan Iliev", "author_id": 15367035, "author_profile": "https://Stackoverflow.com/users/15367035", "pm_score": 1, "selected": false, "text": "public static class NewGPSCoordinates\n{\n public final Location mlocation;\n \n public NewGPSCoordinates(Location location)\n {\n this.mlocation = location;\n }\n}\n EventBus.getDefault().post(new MessageEvents.NewGPSCoordinates(mLocation));\n @Subscribe(threadMode = ThreadMode.MAIN)\npublic void onMessageEvent(MessageEvents.NewGPSCoordinates event)\n{\n Log.i(TAG, \"NewGPSCoordinates: \" + event.mlocation);\n}\n" }, { "answer_id": 74531950, "author": "Graziano", "author_id": 10750674, "author_profile": "https://Stackoverflow.com/users/10750674", "pm_score": 0, "selected": false, "text": "Application Activity WAKE_LOCK GPSApplication.java GPSService.java" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12787982/" ]
74,492,646
<p>I am trying to implement cypress-cucumber-preprocessor for Cypress 11 with TypeScript, but I am unsure what I miss. Here are the steps that I do:</p> <ol> <li>Install it with the following command:</li> </ol> <blockquote> <p>npm install @badeball/cypress-cucumber-preprocessor</p> </blockquote> <ol start="2"> <li>Here is my problem. I am unsure how to implement the plugin inside the &quot;cypress.config.ts&quot; file. The issue is that I am still using the workaround for old implemented plugins with 'return require('./cypress/plugins/index.js')(on, config)'. Is there a way to use both implementations (one for calling the 'index.js' file and the second for adding the cypress-cucumber-preprocessor plugin)? I am not sure how to process it.</li> </ol> <pre><code>import { addCucumberPreprocessorPlugin } from &quot;@badeball/cypress-cucumber-preprocessor&quot;; export default defineConfig({ projectId: '7emkc5', reporter: 'mochawesome', reporterOptions: { reportDir: 'cypress/report/mochawesome-report', overwrite: false, html: true, json: true, timestamp: 'dd-mm-yyyy_HH-MM-ss', }, chromeWebSecurity: false, e2e: { // We've imported your old cypress plugins here. // You may want to clean this up later by importing these. setupNodeEvents(on, config) { return require('./cypress/plugins/index.js')(on, config) }, specPattern: 'cypress/e2e/**/*.{js,jsx,ts,tsx}', }, }) I am using the last version of Cypress 11.1.0 and typescript. </code></pre>
[ { "answer_id": 74495876, "author": "Cristian Antonio Rosas Ayala", "author_id": 20543270, "author_profile": "https://Stackoverflow.com/users/20543270", "pm_score": 2, "selected": false, "text": "npm i @bahmutov/cypress-esbuild-preprocessor \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10395384/" ]
74,492,673
<pre><code>// PARENT const [data, setData] = useState(0); const clickHandler = () =&gt; { setData(prevState =&gt; prevState + 1); } return ( &lt;div&gt; &lt;RerenderCheck data={data} /&gt; &lt;button onClick={clickHandler}&gt;Click&lt;/button&gt; &lt;/div&gt; ) // CHILD const RerenderCheck = (props) =&gt; { const [count, setCount] = useState(props.data); return &lt;div&gt;{count}&lt;/div&gt;; }; </code></pre> <p>Everything seems to work just fine except for the count in child component. I'm expecting the state &quot;count&quot; in child component to change whenever the parent component gets re-rendered.</p> <pre><code>const RerenderCheck = (props) =&gt; { return &lt;div&gt;{props.data}&lt;/div&gt;; }; </code></pre> <p>This one works perfectly fine. I kind of get what's happening but would like to hear from others.</p>
[ { "answer_id": 74495876, "author": "Cristian Antonio Rosas Ayala", "author_id": 20543270, "author_profile": "https://Stackoverflow.com/users/20543270", "pm_score": 2, "selected": false, "text": "npm i @bahmutov/cypress-esbuild-preprocessor \n" } ]
2022/11/18
[ "https://Stackoverflow.com/questions/74492673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19831427/" ]