qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,517,966
<p>I need to do number of inputs that it dynamic's number , and for every input other name because I want to use in these inputs.</p> <p>I call to the function in jsx with that</p> <pre><code>Array.apply(null, { length: numberInputs}).map((e, i) =&gt; ( &lt;InputsNumber key={i} /&gt; )) </code></pre> <p>and I tried do for loop but because the function InputsNumber return tags of html it doesn't work well and the number is dynamic but all the number there same as my dynamic's number inputs</p>
[ { "answer_id": 74517893, "author": "szeak", "author_id": 1597791, "author_profile": "https://Stackoverflow.com/users/1597791", "pm_score": 0, "selected": false, "text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n" }, { "answer_id": 74517896, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": false, "text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74517966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19916813/" ]
74,518,002
<p>I have a function that contains a data.table with specific values:</p> <pre><code> add_q &lt;- function () { DT = data.table (X = c(&quot;A&quot;, &quot;A1&quot;, &quot;B&quot;, &quot;B1&quot;), Y = c(&quot;C&quot;, &quot;C1&quot;, &quot;D&quot;, &quot;D1&quot;))} </code></pre> <p>This will give my two columns X and Y with the values. I want to make a 3rd column that would have the values YES for values that have A, C, A1, C1 and the value NO for the rest.</p> <p>How to do that?</p>
[ { "answer_id": 74517893, "author": "szeak", "author_id": 1597791, "author_profile": "https://Stackoverflow.com/users/1597791", "pm_score": 0, "selected": false, "text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n" }, { "answer_id": 74517896, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": false, "text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19766411/" ]
74,518,006
<p>I am connecting to an api and returning some data on screen using the below:</p> <pre><code>return ( &lt;&gt; {Object.values(items).map((item, index) =&gt; { return &lt;pre&gt;{JSON.stringify(item, null, 2)}&lt;/pre&gt; &lt;/&gt; })} </code></pre> <p>This returns an object to the front end that looks like this.</p> <pre><code>[ { &quot;type&quot;: &quot;player&quot;, &quot;id&quot;: &quot;account.ac12c743e8044d42a6eafeffa2c3a8cf&quot;, &quot;attributes&quot;: { &quot;name&quot;: &quot;JohnnyUtah&quot;, &quot;stats&quot;: null, &quot;titleId&quot;: &quot;pubg&quot;, &quot;shardId&quot;: &quot;stadia&quot;, &quot;patchVersion&quot;: &quot;&quot; }, &quot;relationships&quot;: { &quot;assets&quot;: { &quot;data&quot;: [] }, &quot;matches&quot;: { &quot;data&quot;: [ { &quot;type&quot;: &quot;match&quot;, &quot;id&quot;: &quot;473019a4-fe3b-420a-b00e-b99ff2cd8c73&quot; </code></pre> <p>I would like to as an example get just the id as shown below:</p> <pre><code>&quot;id&quot;: &quot;account.ac12c743e8044d42a6eafeffa2c3a8cf&quot; </code></pre> <p>However I have an object with an array of objects inside of it and I don't know how to access this.</p> <p>I am familiar with the array map function which I believe I need to use, but I don't know how to get inside that array in the object being returned.</p> <p>I'm therefore struggling to see how I get at this value.</p> <hr /> <p>Adding full code as this may help clarify things:</p> <pre><code>import React, { useEffect, useState } from 'react' function Player() { const [player,setPlayer] = useState('JohnnyUtah') const [items,setItems] = useState([]) useEffect(() =&gt; { const apiKey = &quot;key&quot;; const options = { &quot;headers&quot;: { &quot;Accept&quot;: &quot;application/vnd.api+json&quot;, &quot;Authorization&quot;: `Bearer ${apiKey}` } } fetch(`https://api.pubg.com/shards/stadia/players?filter[playerNames]=${player}`, options) .then(response =&gt; response.json()) .then(json =&gt; setItems(json)) }, [player]) return ( &lt;&gt; &lt;div&gt; &lt;button onClick={() =&gt; setplayer('JohnnyUtah')}&gt;JohnnyUtah&lt;/button&gt; &lt;button onClick={() =&gt; setplayer('Binder')}&gt;Binder&lt;/button&gt; &lt;button onClick={() =&gt; setplayer('MartinSheehanUK')}&gt;MartinSheehanUK&lt;/button&gt; &lt;/div&gt; &lt;h1&gt;{player}&lt;/h1&gt; &lt;div&gt; &lt;h2&gt;This shows all&lt;/h2&gt; {data.map((item) =&gt; ( &lt;li key={item.id}&gt;{item.id}&lt;/li&gt; ))} &lt;/div&gt; &lt;div&gt; &lt;h2&gt;This shows only one&lt;/h2&gt; {data[0].id} &lt;/div&gt; &lt;/&gt; ) }; export default Player </code></pre> <p>Just showing the absolute latest version of my code which is still not returning any results for me:</p> <pre><code>import React, { useEffect, useState } from 'react' function Player() { const [player,setPlayer] = useState('JohnnyUtah') const [items,setItems] = useState([]) useEffect(() =&gt; { const apiKey = &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5MTI0M2U5MC1iMjk5LTAxM2EtN2Q5ZC0xNzRhYzM1YTM1ZGYiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNjUyMTkyMTI4LCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6InB1YnJnLWxlYWRlcmJvIn0.veCjNiRtCzchj2Gli-aZt_0YQjtMvey3io-UUDa0zpQ&quot;; const options = { &quot;headers&quot;: { &quot;Accept&quot;: &quot;application/vnd.api+json&quot;, &quot;Authorization&quot;: `Bearer ${apiKey}` } } fetch(`https://api.pubg.com/shards/stadia/players?filter[playerNames]=${player}`, options) .then(response =&gt; response.json()) .then(json =&gt; setItems(json)) }, [player]) return ( &lt;&gt; &lt;div&gt; &lt;button onClick={() =&gt; setPlayer('JohnnyUtah')}&gt;JohnnyUtah&lt;/button&gt; &lt;button onClick={() =&gt; setPlayer('Binder')}&gt;Binder&lt;/button&gt; &lt;button onClick={() =&gt; setPlayer('MartinSheehanUK')}&gt;MartinSheehanUK&lt;/button&gt; &lt;/div&gt; &lt;h1&gt;{player}&lt;/h1&gt; {items !==undefined &amp;&amp; items.length&gt;0 ? items.map((item) =&gt; ( &lt;li key={item.id}&gt;{item.id}&lt;/li&gt; )): &lt;div&gt;No result found&lt;/div&gt;} &lt;/&gt; ) }; </code></pre>
[ { "answer_id": 74517893, "author": "szeak", "author_id": 1597791, "author_profile": "https://Stackoverflow.com/users/1597791", "pm_score": 0, "selected": false, "text": "SELECT\n CASE WHEN column_a = true\n THEN column_a\n ELSE CASE WHEN column_b = true\n THEN column_b\n ELSE CASE WHEN column_c = true\n THEN column_c ELSE null\n END\n END\n END as RESULT\nFROM table\nWHERE user_id = 'u2'\n" }, { "answer_id": 74517896, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": false, "text": "select t.user_id, f.col\nfrom the_table t\n left join lateral (\n values \n ('column_a', t.column_a), \n ('column_b', t.column_b), \n ('column_c', t.column_c)\n ) as f(col, value) on f.value\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310998/" ]
74,518,013
<p>Giving this dictionary:</p> <pre class="lang-py prettyprint-override"><code> d = {'x': '999999999', 'y': ['888888888', '333333333'], 'z': '666666666', 'p': ['0000000', '11111111', '22222222'] } </code></pre> <p>is it possible to make a <code>set</code> of <code>tuples</code> ?</p> <p>The output should be <code>{( x, 999999999),(y,888888888, 333333333),...}</code></p> <p>I tried this : <code>x_set = {(k, v) for k, values in d.items() for v in values} </code></p>
[ { "answer_id": 74518174, "author": "akash.ilangovan", "author_id": 15007641, "author_profile": "https://Stackoverflow.com/users/15007641", "pm_score": 2, "selected": false, "text": "x_set = set()\nfor k, v in d.items():\n items = [k]\n if(type(v) == list):\n items.extend(v)\n else:\n items.append(v)\n x_set.add(tuple(items))\n" }, { "answer_id": 74518254, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 1, "selected": false, "text": "d = {'x': '999999999',\n'y': ['888888888', '333333333'],\n'z': '666666666',\n'p': ['0000000', '11111111', '22222222'] }\n\ntuple_set = set(tuple([k] + list(map(int, v)) if isinstance(v,list) else [k, int(v)]) for k,v in d.items())\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20139720/" ]
74,518,028
<p>I made a simple text with a transition, appearing from left to right when I hover it in CSS.</p> <p>My code is very simple, as seen in the snippet.</p> <p>So of course, when I remove my mouse cursor, it is animated in the other direction and the text disappears from right to left. BUT I'd like it to disappear from left to right and then reset so it can appear again from left to right, and that's where I'm stuck.</p> <p>What would be your approach to get such an effect?</p> <p>Thanks!</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>.text{ transition: max-width 700ms linear; max-width: 0%; overflow: hidden; white-space: nowrap; } .container:hover .text{ max-width: 100%; } .container{ padding: 10px 0 10px 0; width: fit-content; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="text"&gt;THIS IS MY TEXT&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74519070, "author": "Joydip Paul", "author_id": 12241962, "author_profile": "https://Stackoverflow.com/users/12241962", "pm_score": 0, "selected": false, "text": " <p class=\"text\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Saepe, praesentium.</p>\n \n.text{\n transition: max-width 700ms linear;\n opacity: 0;\n height: 20px;\n overflow: hidden;\n max-width: 0px;\n }\n \n .text:hover{\n opacity: 1;\n max-width: 100%;\n }\n" }, { "answer_id": 74521599, "author": "A Haworth", "author_id": 10867454, "author_profile": "https://Stackoverflow.com/users/10867454", "pm_score": 1, "selected": false, "text": ".text {\n display: inline-block;\n width: fit-content;\n animation: out linear 700ms forwards;\n transform: translateX(100%);\n}\n\n@keyframes out {\n 0% {\n transform: translateX(0%);\n }\n 100% {\n transform: translateX(100%);\n }\n}\n\n.container:hover .text {\n transform: translateX(0%);\n animation: in linear 700ms;\n}\n\n@keyframes in {\n 0% {\n transform: translateX(-100%);\n }\n 100% {\n transform: translateX(0%);\n }\n}\n\n.container {\n padding: 10px 0 10px 0;\n width: fit-content;\n rheight: fit-content;\n animation: reveal 700ms linear;\n overflow: hidden;\n}\n\n@keyframes reveal {\n 0%,\n 99% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n} <div class=\"container\">\n <div class=\"text\">THIS IS MY TEXT</div>\n</div>" }, { "answer_id": 74523611, "author": "Bidou", "author_id": 17863882, "author_profile": "https://Stackoverflow.com/users/17863882", "pm_score": 1, "selected": false, "text": ".text{\n animation: out linear 700ms forwards;\n}\n\n.container:hover .text{\n animation: in linear 700ms;\n}\n\n.container{\n padding: 10px 0 10px 0;\n width: fit-content;\n animation: reveal 700ms linear;\n}\n\n@keyframes in {\n 0% {\n clip-path: polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%);\n }\n 100% {\n clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);\n }\n}\n\n@keyframes out {\n 0% {\n clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);\n }\n 100% {\n clip-path: polygon(100% 0%, 100% 0%, 100% 100%, 100% 100%);\n }\n}\n\n@keyframes reveal {\n 0%,\n 99% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n} <div class=\"container\">\n<div class=\"text\">THIS IS MY TEXT</div>\n</div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17863882/" ]
74,518,071
<p>I'm trying to code a countdown timer to Christmas day. Below is what I have. However, <code>days</code> is coming out as <code>3</code> for some reason. If I set the <code>then</code> date up <code>22nd December</code> - it will calculate it right but any dates after that it seems to start from <code>1</code> - meaning if I set it to <code>2022-12-23 00:00:00</code>, days is outputting <code>1</code>, <code>2022-12-24 00:00:00</code> will give me <code>2</code> days to the countdown. I'm a bit confused what is happening here...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> const [days, setDays] = useState(0); const [hours, setHours] = useState(0); const [minutes, setMinutes] = useState(0); const [seconds, setSeconds] = useState(0); useEffect(() =&gt; { setInterval(() =&gt; { const now = moment(); const then = moment("2022-12-23 00:00:00", "YYYY-MM-DD hh:mm:ss"); const countdown = moment(then - now); setDays(countdown.format("D")); setHours(countdown.format("HH")); setMinutes(countdown.format("mm")); setSeconds(countdown.format("ss")); }, 1000); }, []);</code></pre> </div> </div> </p>
[ { "answer_id": 74519070, "author": "Joydip Paul", "author_id": 12241962, "author_profile": "https://Stackoverflow.com/users/12241962", "pm_score": 0, "selected": false, "text": " <p class=\"text\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Saepe, praesentium.</p>\n \n.text{\n transition: max-width 700ms linear;\n opacity: 0;\n height: 20px;\n overflow: hidden;\n max-width: 0px;\n }\n \n .text:hover{\n opacity: 1;\n max-width: 100%;\n }\n" }, { "answer_id": 74521599, "author": "A Haworth", "author_id": 10867454, "author_profile": "https://Stackoverflow.com/users/10867454", "pm_score": 1, "selected": false, "text": ".text {\n display: inline-block;\n width: fit-content;\n animation: out linear 700ms forwards;\n transform: translateX(100%);\n}\n\n@keyframes out {\n 0% {\n transform: translateX(0%);\n }\n 100% {\n transform: translateX(100%);\n }\n}\n\n.container:hover .text {\n transform: translateX(0%);\n animation: in linear 700ms;\n}\n\n@keyframes in {\n 0% {\n transform: translateX(-100%);\n }\n 100% {\n transform: translateX(0%);\n }\n}\n\n.container {\n padding: 10px 0 10px 0;\n width: fit-content;\n rheight: fit-content;\n animation: reveal 700ms linear;\n overflow: hidden;\n}\n\n@keyframes reveal {\n 0%,\n 99% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n} <div class=\"container\">\n <div class=\"text\">THIS IS MY TEXT</div>\n</div>" }, { "answer_id": 74523611, "author": "Bidou", "author_id": 17863882, "author_profile": "https://Stackoverflow.com/users/17863882", "pm_score": 1, "selected": false, "text": ".text{\n animation: out linear 700ms forwards;\n}\n\n.container:hover .text{\n animation: in linear 700ms;\n}\n\n.container{\n padding: 10px 0 10px 0;\n width: fit-content;\n animation: reveal 700ms linear;\n}\n\n@keyframes in {\n 0% {\n clip-path: polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%);\n }\n 100% {\n clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);\n }\n}\n\n@keyframes out {\n 0% {\n clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);\n }\n 100% {\n clip-path: polygon(100% 0%, 100% 0%, 100% 100%, 100% 100%);\n }\n}\n\n@keyframes reveal {\n 0%,\n 99% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n} <div class=\"container\">\n<div class=\"text\">THIS IS MY TEXT</div>\n</div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3752986/" ]
74,518,079
<p>I am storing field in redis <code>setex</code> to see if field is already present for an email which is being sent to the function.</p>
[ { "answer_id": 74519070, "author": "Joydip Paul", "author_id": 12241962, "author_profile": "https://Stackoverflow.com/users/12241962", "pm_score": 0, "selected": false, "text": " <p class=\"text\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Saepe, praesentium.</p>\n \n.text{\n transition: max-width 700ms linear;\n opacity: 0;\n height: 20px;\n overflow: hidden;\n max-width: 0px;\n }\n \n .text:hover{\n opacity: 1;\n max-width: 100%;\n }\n" }, { "answer_id": 74521599, "author": "A Haworth", "author_id": 10867454, "author_profile": "https://Stackoverflow.com/users/10867454", "pm_score": 1, "selected": false, "text": ".text {\n display: inline-block;\n width: fit-content;\n animation: out linear 700ms forwards;\n transform: translateX(100%);\n}\n\n@keyframes out {\n 0% {\n transform: translateX(0%);\n }\n 100% {\n transform: translateX(100%);\n }\n}\n\n.container:hover .text {\n transform: translateX(0%);\n animation: in linear 700ms;\n}\n\n@keyframes in {\n 0% {\n transform: translateX(-100%);\n }\n 100% {\n transform: translateX(0%);\n }\n}\n\n.container {\n padding: 10px 0 10px 0;\n width: fit-content;\n rheight: fit-content;\n animation: reveal 700ms linear;\n overflow: hidden;\n}\n\n@keyframes reveal {\n 0%,\n 99% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n} <div class=\"container\">\n <div class=\"text\">THIS IS MY TEXT</div>\n</div>" }, { "answer_id": 74523611, "author": "Bidou", "author_id": 17863882, "author_profile": "https://Stackoverflow.com/users/17863882", "pm_score": 1, "selected": false, "text": ".text{\n animation: out linear 700ms forwards;\n}\n\n.container:hover .text{\n animation: in linear 700ms;\n}\n\n.container{\n padding: 10px 0 10px 0;\n width: fit-content;\n animation: reveal 700ms linear;\n}\n\n@keyframes in {\n 0% {\n clip-path: polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%);\n }\n 100% {\n clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);\n }\n}\n\n@keyframes out {\n 0% {\n clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);\n }\n 100% {\n clip-path: polygon(100% 0%, 100% 0%, 100% 100%, 100% 100%);\n }\n}\n\n@keyframes reveal {\n 0%,\n 99% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n} <div class=\"container\">\n<div class=\"text\">THIS IS MY TEXT</div>\n</div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400992/" ]
74,518,088
<p>I want to create a custom ListView that wrap the children with something common (and a few logic to disable them). However the children contents are <strong>unknown and different for each child</strong> and is managed by the parent.</p> <p>Input (from, say, <code>Index.razor</code> and the component is <code>MyList.razor</code>):</p> <pre class="lang-html prettyprint-override"><code>&lt;!-- Other code --&gt; &lt;MyList&gt; &lt;Child Title=&quot;Paragraph&quot;&gt; &lt;p&gt;May have any HTML content&lt;/p&gt; &lt;/Child&gt; &lt;Child Title=&quot;Link&quot;&gt; &lt;a href=&quot;://example.com&quot;&gt;Example Link&lt;/a&gt; &lt;/Child&gt; &lt;Child Title=&quot;Custom HTML&quot;&gt; &lt;div&gt;Could be anything in here&lt;/div&gt; &lt;button onclick=&quot;this.OnButtonClicked&quot;&gt;Click Me&lt;/button&gt; &lt;/Child&gt; &lt;/MyList&gt; </code></pre> <p>The result:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;list&quot;&gt; &lt;div class=&quot;child&quot;&gt; &lt;p&gt;Row 1: Paragraph @*Title here*@&lt;/p&gt; &lt;div class=&quot;row-content&quot;&gt; @*HTML content here*@ &lt;p&gt;May have any HTML content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;child&quot;&gt; &lt;p&gt;Row 2: Link @*Title here*@&lt;/p&gt; &lt;div class=&quot;row-content&quot;&gt; @*HTML content here*@ &lt;a href=&quot;://example.com&quot;&gt;Example Link&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- More --&gt; &lt;/div&gt; </code></pre> <p>I have tried <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/components/templated-components" rel="nofollow noreferrer">templated components</a> but the template is fixed for all chidden. <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent" rel="nofollow noreferrer">Dynamically-rendered ASP.NET Core Razor components</a> would require me to make a component class for each child which is not very desirable. Is there any solution to my question?</p> <hr /> <p>This is my best attempt so far but I do not know how to pass the <code>RenderFragment</code>s to the children:</p> <pre class="lang-html prettyprint-override"><code>&lt;app-board&gt; @{ var i = 0; } @foreach (var row in this.Rows) { var z = i; &lt;fieldset class=&quot;board-row&quot; disabled=&quot;@(this.CurrentStep &lt; z)&quot;&gt; &lt;board-col&gt; &lt;span class=&quot;step-num&quot;&gt;@(z)&lt;/span&gt; &lt;span class=&quot;step-title&quot;&gt;@(row.Title)&lt;/span&gt; &lt;/board-col&gt; &lt;board-col&gt; @(row.Html) &lt;/board-col&gt; &lt;/fieldset&gt; } &lt;/app-board&gt; </code></pre> <pre class="lang-cs prettyprint-override"><code>public partial class AppBoard { [Parameter, AllowNull] public IReadOnlyList&lt;AppBoardRow&gt; Rows { get; set; } [Parameter] public int CurrentStep { get; set; } = -1; public record AppBoardRow(string Title, RenderFragment Html); } </code></pre> <p>I don't know how I can use it in <code>Index.razor</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;AppBoard&gt; &lt;!-- What's here? --&gt; &lt;/AppBoard&gt; </code></pre>
[ { "answer_id": 74518433, "author": "AlirezaK", "author_id": 4444757, "author_profile": "https://Stackoverflow.com/users/4444757", "pm_score": 1, "selected": false, "text": "@page \"/ParentComponent\"\n\n<h1 class=\"text-danger\">Parent Child Component</h1>\n\n<ChildComponent Title=\"This title is passed as a parameter from the Parent Component\">\n A `Render Fragment` from the parent!\n</ChildComponent>\n\n<ChildComponent Title=\"This is the second child component\"></ChildComponent>\n\n@code {\n\n} \n <div>\n <div class=\"alert alert-info\">@Title</div>\n <div class=\"alert alert-success\">\n @if (ChildContent == null)\n {\n <span> Hello, from Empty Render Fragment </span>\n }\n else\n {\n <span>@ChildContent</span>\n }\n </div>\n</div>\n\n\n@code {\n [Parameter]\n public string Title { get; set; }\n\n [Parameter]\n public RenderFragment ChildContent { get; set; }\n}\n RenderFragment" }, { "answer_id": 74519220, "author": "Brian Parker", "author_id": 1492496, "author_profile": "https://Stackoverflow.com/users/1492496", "pm_score": 0, "selected": false, "text": "RenderFragment<T> TItem @typeparam TItem\n\n@foreach(var item in Data)\n{\n @ChildContent(item)\n}\n\n@code {\n [Parameter, EditorRequired]\n public RenderFragment<TItem> ChildContent { get; set; } = default!;\n\n [Parameter, EditorRequired]\n public IEnumerable<TItem> Data { get; set; } = default!;\n}\n context ChildContent <T> T context [Parameter, EditorRequired]\npublic Renderframent ChildContent { get; set;}\n <ParentComponent Data=myList >\n <ChildComponent1 Title=\"Paragraph\">\n <p>May have any HTML content</p>\n </ChildComponent1>\n</ParentComponent>\n\n@code {\n private List<ListItem> myList;\n}\n ParentComponent context Name context.Name context @typeparam TItem\n\n@ChildContent(Item)\n\n@code {\n [Parameter, EditorRequired]\n public RenderFragment<TItem> ChildContent { get; set; } = default!;\n\n [Parameter, EditorRequired]\n public TItem Item { get; set; } = default!;\n}\n <ParentComponent Data=myList >\n <ChildComponent1 Title=\"Paragraph\" Item=context>\n <p>May have any HTML content</p>\n </ChildComponent1>\n @context\n</ParentComponent>\n\n <ParentComponent Data=myList Context=\"parentContext\" >\n <ChildComponent1 Title=\"Paragraph\" Item=parentContext>\n @context.Name //\n @parentContext.Name // Both valid here\n <p>May have any HTML content</p>\n </ChildComponent1>\n @parentContext.Name\n</ParentComponent>\n\n" }, { "answer_id": 74520759, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 2, "selected": true, "text": "<div class=\"list bg-secondary p-2\">\n @ChildContent\n</div>\n\n@code {\n [Parameter] public RenderFragment? ChildContent { get; set; }\n}\n <div class=\"child bg-dark text-white p-2 m-3\">\n <p>Row @(this.Row): @this.Title </p>\n <div class=\"row-content\">\n @ChildContent\n </div>\n</div>\n\n@code {\n [Parameter] public RenderFragment? ChildContent { get; set; }\n [Parameter, EditorRequired] public string Title { get; set; } = \"No title Provided\";\n [Parameter, EditorRequired] public int Row { get; set; }\n}\n @page \"/\"\n\n<PageTitle>Index</PageTitle>\n\n<h1>Hello, world!</h1>\n\nWelcome to your new app.\n\n<SurveyPrompt Title=\"How is Blazor working for you?\" />\n\n<MyList>\n <MyListChild Row=1 Title=\"Paragraph\">\n <p>May have any HTML content</p>\n </MyListChild>\n <MyListChild Row=2 Title=\"Link\">\n <a href=\"http://example.com\">Example Link</a>\n </MyListChild>\n <MyListChild Row=3 Title=\"Custom HTML\">\n <div>The last time this button was clicked is @Message</div>\n <button class=\"btn btn-primary\" @onclick=\"this.OnButtonClicked\">Click Me</button>\n </MyListChild>\n</MyList>\n\n@code {\n private string Message = DateTime.Now.ToLongTimeString();\n\n private void OnButtonClicked()\n => this.Message = DateTime.Now.ToLongTimeString();\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653457/" ]
74,518,177
<p>I am a beginner. I have this problem I am not sure if I will be able to explain it adequately but let's see:</p> <p>I have an array called userid and another array called username. I want the user to give me his/her id after that I wish that the name user will type has to be the same array number from the username array for example if the user types 5 then his/her name must be &quot;f&quot; otherwise user can't go any further.</p> <p>I don't know what to type in if statement?</p> <pre><code>class Program { static void Main(string[] args) { string[] userid = {&quot;0&quot; , &quot;1&quot; , &quot;2&quot; , &quot;3&quot; , &quot;4&quot; , &quot;5&quot;}; string[] username = { &quot;a&quot; , &quot;b&quot; , &quot;c&quot; , &quot;d&quot; , &quot;e&quot; , &quot;f&quot;}; Console.Write(&quot;please type user id: \t&quot;); string useridreply= Console.ReadLine(); Console.Write(&quot;please type user name: \t&quot;); string usernamereply = Console.ReadLine(); if (usernamereply == username[useridreply]) { } } } </code></pre>
[ { "answer_id": 74518433, "author": "AlirezaK", "author_id": 4444757, "author_profile": "https://Stackoverflow.com/users/4444757", "pm_score": 1, "selected": false, "text": "@page \"/ParentComponent\"\n\n<h1 class=\"text-danger\">Parent Child Component</h1>\n\n<ChildComponent Title=\"This title is passed as a parameter from the Parent Component\">\n A `Render Fragment` from the parent!\n</ChildComponent>\n\n<ChildComponent Title=\"This is the second child component\"></ChildComponent>\n\n@code {\n\n} \n <div>\n <div class=\"alert alert-info\">@Title</div>\n <div class=\"alert alert-success\">\n @if (ChildContent == null)\n {\n <span> Hello, from Empty Render Fragment </span>\n }\n else\n {\n <span>@ChildContent</span>\n }\n </div>\n</div>\n\n\n@code {\n [Parameter]\n public string Title { get; set; }\n\n [Parameter]\n public RenderFragment ChildContent { get; set; }\n}\n RenderFragment" }, { "answer_id": 74519220, "author": "Brian Parker", "author_id": 1492496, "author_profile": "https://Stackoverflow.com/users/1492496", "pm_score": 0, "selected": false, "text": "RenderFragment<T> TItem @typeparam TItem\n\n@foreach(var item in Data)\n{\n @ChildContent(item)\n}\n\n@code {\n [Parameter, EditorRequired]\n public RenderFragment<TItem> ChildContent { get; set; } = default!;\n\n [Parameter, EditorRequired]\n public IEnumerable<TItem> Data { get; set; } = default!;\n}\n context ChildContent <T> T context [Parameter, EditorRequired]\npublic Renderframent ChildContent { get; set;}\n <ParentComponent Data=myList >\n <ChildComponent1 Title=\"Paragraph\">\n <p>May have any HTML content</p>\n </ChildComponent1>\n</ParentComponent>\n\n@code {\n private List<ListItem> myList;\n}\n ParentComponent context Name context.Name context @typeparam TItem\n\n@ChildContent(Item)\n\n@code {\n [Parameter, EditorRequired]\n public RenderFragment<TItem> ChildContent { get; set; } = default!;\n\n [Parameter, EditorRequired]\n public TItem Item { get; set; } = default!;\n}\n <ParentComponent Data=myList >\n <ChildComponent1 Title=\"Paragraph\" Item=context>\n <p>May have any HTML content</p>\n </ChildComponent1>\n @context\n</ParentComponent>\n\n <ParentComponent Data=myList Context=\"parentContext\" >\n <ChildComponent1 Title=\"Paragraph\" Item=parentContext>\n @context.Name //\n @parentContext.Name // Both valid here\n <p>May have any HTML content</p>\n </ChildComponent1>\n @parentContext.Name\n</ParentComponent>\n\n" }, { "answer_id": 74520759, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 2, "selected": true, "text": "<div class=\"list bg-secondary p-2\">\n @ChildContent\n</div>\n\n@code {\n [Parameter] public RenderFragment? ChildContent { get; set; }\n}\n <div class=\"child bg-dark text-white p-2 m-3\">\n <p>Row @(this.Row): @this.Title </p>\n <div class=\"row-content\">\n @ChildContent\n </div>\n</div>\n\n@code {\n [Parameter] public RenderFragment? ChildContent { get; set; }\n [Parameter, EditorRequired] public string Title { get; set; } = \"No title Provided\";\n [Parameter, EditorRequired] public int Row { get; set; }\n}\n @page \"/\"\n\n<PageTitle>Index</PageTitle>\n\n<h1>Hello, world!</h1>\n\nWelcome to your new app.\n\n<SurveyPrompt Title=\"How is Blazor working for you?\" />\n\n<MyList>\n <MyListChild Row=1 Title=\"Paragraph\">\n <p>May have any HTML content</p>\n </MyListChild>\n <MyListChild Row=2 Title=\"Link\">\n <a href=\"http://example.com\">Example Link</a>\n </MyListChild>\n <MyListChild Row=3 Title=\"Custom HTML\">\n <div>The last time this button was clicked is @Message</div>\n <button class=\"btn btn-primary\" @onclick=\"this.OnButtonClicked\">Click Me</button>\n </MyListChild>\n</MyList>\n\n@code {\n private string Message = DateTime.Now.ToLongTimeString();\n\n private void OnButtonClicked()\n => this.Message = DateTime.Now.ToLongTimeString();\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498886/" ]
74,518,179
<pre><code>def add(x, y): return x + y def multiple(x, y): return x * y def subtrack(x, y): return x - y def divide(x, y): return x / y print('select your operation please') print('1-Add') print('2-Multiple') print('3-subtrack') print('4-Divide') chose=int(input('enter your selection please: ')) num1=int(input('enter your first num please: ')) num2=int(input('enter your second num please: ')) if chose == '1': print(num1,'+',num2,'=',add(num1,num2)) elif chose == '2': print(num1,'*',num2,'=',multiple(num1,num2)) elif chose == '3': print(num1, '-', num2, '=', subtrack(num1,num2)) elif chose == '4': print(num1,'/',num2,'=',divide(num1,num2)) else: print(&quot;invalid number operation&quot;) </code></pre> <p>this code always go to else I tried to put if in if to force code to go to it but still go to else some solutions please</p>
[ { "answer_id": 74518230, "author": "Dylan Baars", "author_id": 20562315, "author_profile": "https://Stackoverflow.com/users/20562315", "pm_score": 1, "selected": false, "text": "if chose == '1' if chose == 1 '" }, { "answer_id": 74518234, "author": "Connor Stoop", "author_id": 2111137, "author_profile": "https://Stackoverflow.com/users/2111137", "pm_score": 1, "selected": false, "text": "chose int string char if chose == 1:\n print(num1,'+',num2,'=',add(num1,num2))\nelif chose == 2:\n print(num1,'*',num2,'=',multiple(num1,num2))\nelif chose == 3:\n print(num1, '-', num2, '=', subtrack(num1,num2))\nelif chose == 4:\n print(num1,'/',num2,'=',divide(num1,num2))\nelse:\n print(\"invalid number operation\")\n" }, { "answer_id": 74518284, "author": "Pradeep Yenkuwale", "author_id": 7633739, "author_profile": "https://Stackoverflow.com/users/7633739", "pm_score": 0, "selected": false, "text": "int if chose == '1': int chose=int(input('enter your selection please: '))\nif chose == 1:\n print(num1,'+',num2,'=',add(num1,num2))\nelif chose == 2:\n print(num1,'*',num2,'=',multiple(num1,num2))\nelif chose == 3:\n print(num1, '-', num2, '=', subtrack(num1,num2))\nelif chose == 4:\n print(num1,'/',num2,'=',divide(num1,num2))\nelse:\n print(\"invalid number operation\")\n str chose=str(input('enter your selection please: '))'=\nif chose == '1':\n print(num1,'+',num2,'=',add(num1,num2))\nelif chose == '2':\n print(num1,'*',num2,'=',multiple(num1,num2))\nelif chose == '3':\n print(num1, '-', num2, '=', subtrack(num1,num2))\nelif chose == '4':\n print(num1,'/',num2,'=',divide(num1,num2))\nelse:\n print(\"invalid number operation\")\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20240519/" ]
74,518,190
<p>I have a specific question relating a foreach loop in C# and Blazor Web Assembly.</p> <p>This is my foreach loop containing a keyvaluepair: `</p> <pre><code>@foreach (KeyValuePair&lt;int, string&gt; pair in detail.Years2Value.OrderBy(x =&gt; x.Key)) { &lt;td colspan=&quot;1&quot;&gt;&lt;input type=&quot;text&quot; class=&quot;radius form-control&quot; style=&quot;background-color:transparent; border:0.1px&quot; readonly=&quot;readonly&quot; value=@pair.Value&gt;&lt;/td&gt; } &lt;td colspan=&quot;1&quot; class=&quot;border-left border-right&quot;&gt;&lt;/td&gt; </code></pre> <p>` I want to display all values in a range and in a Region. After each region it should create an empty row to make it look better and more organized. Thats why I am adding a td after the foreach. This creates following problem: --&gt; See Picture below! after the last foreach in my last Region is done, I don't want to create a new td but I don´t know how to achieve this.</p> <p><img src="https://i.stack.imgur.com/jFZNz.png" alt="Picture showing the problem" /></p> <p>If I just delete the line of code with the td after the foreach then all regions will stick more or less together and it don´t look so good anymore because the missing &quot;separation&quot; of each region.</p> <p>Is there a way to break the foreach only after the 3rd region is done and then don´t do the new td with an if sentence or something similar?</p> <p>I hope you guys can help me here. Sorry if there is any information missing or something is not clear. I will try to explain it again if something is not clear.</p> <p>Thank you</p>
[ { "answer_id": 74532917, "author": "eduard", "author_id": 3215635, "author_profile": "https://Stackoverflow.com/users/3215635", "pm_score": 1, "selected": true, "text": "@*Loop through all the KeyValuePairs in the Dictionary<int,string> *@\n@for (int i = 1; i < orderedYearsToValue.Count(); i++)\n{\n <td colspan=\"1\">\n @*Select element and its value at the current index*@\n <input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@orderedYearsToValue.ElementAt(i).Value>\n </td>\n @*If the current index is not at the last item, add an empty line *@\n @if (i != orderedYearsToValue.Count()-1)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n} \n \n@code {\n\n private Dictionary<int, string> orderedYearsToValue;\n \n ... your code\n \n private void OrderValues() {\n orderedYearsToValue = detail.Years2Value.OrderBy(x => x.Key);\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n if(isSpecialist) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n }\n else\n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n if(isSpecialist) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n else \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n" }, { "answer_id": 74534037, "author": "Vikram Reddy", "author_id": 20552709, "author_profile": "https://Stackoverflow.com/users/20552709", "pm_score": 1, "selected": false, "text": "int i = 1;\n@foreach (KeyValuePair<int, string> pair in detail.Years2Value.OrderBy(x => x.Key))\n{\n <td colspan=\"1\"><input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@pair.Value></td>\n if(i < detail.Years2Value.Count)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n i++;\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19094279/" ]
74,518,202
<p>so I'm using Redux-Toolkit Query on my project, and I have an authSlice, where I keep the authenticated user info and an access_token.</p> <p>I also keep this info in local storage so whenever I reload the page I can get the values from the local storage and save them in the state.</p> <p>The catch is that I have a RequiredAuth component that checks if the user trying to access specific routes is authenticated, by checking if there is an access_token in the state, it works fine except that if I reload this page while I'm authenticated I will be redirected to my login page.</p> <p>The RequiredAuth component code:</p> <pre><code>import { useLocation, Navigate, Outlet } from &quot;react-router-dom&quot;; import { useSelector } from &quot;react-redux&quot;; import { selectToken } from &quot;./authSlice&quot;; const RequireAuth = () =&gt; { const token = useSelector(selectToken) const location = useLocation() return ( token ? &lt;Outlet /&gt; : &lt;Navigate to=&quot;/auth/login&quot; state={{ from: location}} replace /&gt; ) } export default RequireAuth </code></pre> <p>Code that gets user info and token from local storage when the page is reloaded and adds it to state:</p> <pre><code>import { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { setCredentials, selectToken } from '../features/auth/authSlice'; const Header = () =&gt; { const dispatch = useDispatch() const [user, setUser] = useState(JSON.parse(localStorage.getItem('profile'))) const stateToken = useSelector(selectToken) useEffect(() =&gt; { if(user?.access_token &amp;&amp; !stateToken) { dispatch(setCredentials({ user: user.user, access_token: user.access_token })) } }, []) // Omited code, not relevant return ( &lt;header className='nav-bar'&gt; // Omited code, not relevant &lt;/header&gt; ) } export default Header </code></pre> <p>I believe whenever I reload a page where a user needs to be authenticated this happens: in the &quot;RequiredAuth&quot; I will get a null access_token from the state, so I get redirected and only then my useEffect will copy the local storage data to the state.</p> <p>I fixed this problem by changing the RequiredAuth component to this:</p> <pre><code>import { useLocation, Navigate, Outlet } from &quot;react-router-dom&quot;; const RequireAuth = () =&gt; { const profile = JSON.parse(localStorage.getItem('profile')) const location = useLocation() return ( profile?.access_token ? &lt;Outlet /&gt; : &lt;Navigate to=&quot;/auth/login&quot; state={{ from: location}} replace /&gt; ) } export default RequireAuth </code></pre> <p>But I would like to know if there is a better way to keep data in state after reloading a page in order to solve this problem because getting it from local storage feels counterintuitive, since the data will be stored in the state after the useEffect logic completes.</p>
[ { "answer_id": 74532917, "author": "eduard", "author_id": 3215635, "author_profile": "https://Stackoverflow.com/users/3215635", "pm_score": 1, "selected": true, "text": "@*Loop through all the KeyValuePairs in the Dictionary<int,string> *@\n@for (int i = 1; i < orderedYearsToValue.Count(); i++)\n{\n <td colspan=\"1\">\n @*Select element and its value at the current index*@\n <input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@orderedYearsToValue.ElementAt(i).Value>\n </td>\n @*If the current index is not at the last item, add an empty line *@\n @if (i != orderedYearsToValue.Count()-1)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n} \n \n@code {\n\n private Dictionary<int, string> orderedYearsToValue;\n \n ... your code\n \n private void OrderValues() {\n orderedYearsToValue = detail.Years2Value.OrderBy(x => x.Key);\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n if(isSpecialist) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n }\n else\n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n if(isSpecialist) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n else \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n" }, { "answer_id": 74534037, "author": "Vikram Reddy", "author_id": 20552709, "author_profile": "https://Stackoverflow.com/users/20552709", "pm_score": 1, "selected": false, "text": "int i = 1;\n@foreach (KeyValuePair<int, string> pair in detail.Years2Value.OrderBy(x => x.Key))\n{\n <td colspan=\"1\"><input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@pair.Value></td>\n if(i < detail.Years2Value.Count)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n i++;\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14984532/" ]
74,518,206
<p>I have two tables in my database, with this sample data:</p> <p>table 1: main</p> <pre><code>m_id eID sDate eDate 1 75 2022-12-01 NULL </code></pre> <p>table 2: details</p> <pre><code>m_id cc_id cu_id perc 1 1 1 40 1 1 2 40 1 1 3 20 </code></pre> <p>Here's what I would like to achieve in SQL Server:</p> <pre><code>m_id eID sDate eDate cc_id^1 cu_id^1 perc^1 cc_id^2 cu_id^2 perc^2 cc_id^3 cu_id^3 perc^3 1 75 2022-12-01 NULL 1 1 40 1 2 40 1 3 20 </code></pre> <p>So, the three rows in the 'details' table should be concatenated to the single row in the 'main' table.</p> <p>I read about and tried the PIVOT Function, but I think it's not exactly what I'm looking for. To me, it seems PIVOT is using each unique value in the 'details' table as column header and then counts the number of instances of it. For example like this:</p> <pre><code>m_id eID sDate eDate 40 1 75 2022-12-01 NULL 2 </code></pre> <p>So, basically using 40 as a column header and then fill its value with 2, as there are two instances of 40 in the perc column in the 'details' table.</p> <p>I spent an entire day searching via Google and trying the PIVOT function without luck.</p>
[ { "answer_id": 74532917, "author": "eduard", "author_id": 3215635, "author_profile": "https://Stackoverflow.com/users/3215635", "pm_score": 1, "selected": true, "text": "@*Loop through all the KeyValuePairs in the Dictionary<int,string> *@\n@for (int i = 1; i < orderedYearsToValue.Count(); i++)\n{\n <td colspan=\"1\">\n @*Select element and its value at the current index*@\n <input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@orderedYearsToValue.ElementAt(i).Value>\n </td>\n @*If the current index is not at the last item, add an empty line *@\n @if (i != orderedYearsToValue.Count()-1)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n} \n \n@code {\n\n private Dictionary<int, string> orderedYearsToValue;\n \n ... your code\n \n private void OrderValues() {\n orderedYearsToValue = detail.Years2Value.OrderBy(x => x.Key);\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n if(isSpecialist) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n }\n else\n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n if(isSpecialist) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n else \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n" }, { "answer_id": 74534037, "author": "Vikram Reddy", "author_id": 20552709, "author_profile": "https://Stackoverflow.com/users/20552709", "pm_score": 1, "selected": false, "text": "int i = 1;\n@foreach (KeyValuePair<int, string> pair in detail.Years2Value.OrderBy(x => x.Key))\n{\n <td colspan=\"1\"><input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@pair.Value></td>\n if(i < detail.Years2Value.Count)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n i++;\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6512333/" ]
74,518,222
<p>At a workplace they recycle punchcard ids (for some strange reason). So it is common to have past employees clashing with current employees. As a workaround I want to have employee punchcard id, employee name+surname as the unique primary key (fingers crossed, perhaps add date-of-birth and even passport if available). That can be accomplished with <code>PRIMARY KEY (pid,name,surname)</code>.</p> <p>The complication is that another table now wants to reference an employee by its above primary key.</p> <p>Alas, said PK has no name! How can I reference it?</p> <p>I tried these but no joy:</p> <pre><code>PRIMARY KEY id (pid, name, surname), </code></pre> <pre><code>INDEX id (pid, name, surname), PRIMARY KEY id, </code></pre> <pre><code>INDEX id (pid, name, surname) PRIMARY KEY, </code></pre> <p>Can you advise on how to achieve this or even how to reference a composite primary key?</p> <p>Update: The table to store employees is <code>em</code>. The table which references an employee is <code>co</code> (a comment made by an employee).</p> <p>Ideally I would use <code>pid</code> (punchcard id) as the unique id of each employee. But since <code>pid</code>s are recycled, this is not unique. And so I resorted to creating a composite key or an index which will be unique and can reference that as a unique employee id. Below are the 2 tables without the composite key. For brevity, I abbreviated table names and omitted surname etc. So the question is, how can I reference an employee whose id is composite from another table <code>co</code>.</p> <pre><code>CREATE TABLE em ( pid INT NOT NULL, name VARCHAR(10) NOT NULL ); CREATE TABLE co ( id INT primary key auto_increment, em INT, content VARCHAR(100) NOT NULL, constraint co2em_em_fk foreign key (em) references em(pid) ); </code></pre>
[ { "answer_id": 74532917, "author": "eduard", "author_id": 3215635, "author_profile": "https://Stackoverflow.com/users/3215635", "pm_score": 1, "selected": true, "text": "@*Loop through all the KeyValuePairs in the Dictionary<int,string> *@\n@for (int i = 1; i < orderedYearsToValue.Count(); i++)\n{\n <td colspan=\"1\">\n @*Select element and its value at the current index*@\n <input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@orderedYearsToValue.ElementAt(i).Value>\n </td>\n @*If the current index is not at the last item, add an empty line *@\n @if (i != orderedYearsToValue.Count()-1)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n} \n \n@code {\n\n private Dictionary<int, string> orderedYearsToValue;\n \n ... your code\n \n private void OrderValues() {\n orderedYearsToValue = detail.Years2Value.OrderBy(x => x.Key);\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n if(isSpecialist) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n }\n else\n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n for (int i = 0; i < myOrderedCountries.Count(); i++) \n{\n if(detail != null) \n {\n foreach(KeyValuePair<int, string> in myOrderedYearsToValue) \n {\n if(isSpecialist) \n {\n <td colspan=\"1\"><input type=\"text\" ...></td>\n }\n else \n {\n <td colspan=\"1\"><input type=\"different text\" ...></td>\n }\n \n if(i < myOrderedCountries.Count() - 1) {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n }\n}\n" }, { "answer_id": 74534037, "author": "Vikram Reddy", "author_id": 20552709, "author_profile": "https://Stackoverflow.com/users/20552709", "pm_score": 1, "selected": false, "text": "int i = 1;\n@foreach (KeyValuePair<int, string> pair in detail.Years2Value.OrderBy(x => x.Key))\n{\n <td colspan=\"1\"><input type=\"text\" class=\"radius form-control\" style=\"background-color:transparent; border:0.1px\" readonly=\"readonly\" value=@pair.Value></td>\n if(i < detail.Years2Value.Count)\n {\n <td colspan=\"1\" class=\"border-left border-right\"></td>\n }\n i++;\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385390/" ]
74,518,256
<p>I have a simulation I create on unity and I have an issue that when I build and run my project and open it on my UI menu(there is only some buttons), and for some reason my GPU is on more then 50%. I tried to delete evreything on my scene and create a new camera and build it and I get the same result. maybe it can be relevent but Im using URP. this is my profiler from the build mode:</p> <p><a href="https://i.stack.imgur.com/jeXkc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jeXkc.png" alt="enter image description here" /></a></p> <p>and this is my task manager: <a href="https://i.stack.imgur.com/3H4s2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3H4s2.png" alt="enter image description here" /></a> [<img src="https://i.stack.imgur.com/1MWAh.png" alt="enter image description here" />][3[![] ]</p> <p>this issue happen on other computers on the GPU1</p> <p><a href="https://i.stack.imgur.com/6alDg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6alDg.jpg" alt="enter image description here" /></a> someone have an idea what causing it?</p>
[ { "answer_id": 74641210, "author": "Noam Riahi", "author_id": 9343039, "author_profile": "https://Stackoverflow.com/users/9343039", "pm_score": 1, "selected": true, "text": "void Start()\n{\n Application.targetFrameRate = 30;\n}\n void OnDestroy()\n {\n Application.targetFrameRate = -1;\n }\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9343039/" ]
74,518,262
<p>I have a css styling problem:</p> <p>I created a header with text inside. The header has two pseudo elements: <code>::before</code> and <code>::after</code>. Both elements lay on top of the header element. How do I get the <code>h1</code> to stay in front of everything??</p> <p>Here is my code example: (got code snippets removed?? i didnt found the button where to add)</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>header { position: fixed; left: 0; right: 0; top: 0; z-index: 99; background-image: url("Bild1.svg"); background-size: 100% 100%; text-align: center; padding: 1px 20px; } header::after { content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-image: url("Bild2.svg"); background-size: 100% 100%; opacity: .5; } header::before { content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: -10px; background-image: url("Bild3.svg"); background-size: 100% 100%; opacity: .5; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt; &lt;h1&gt;Title Text&lt;/h1&gt; &lt;/header&gt;</code></pre> </div> </div> </p> <p>Here is a image how it looks:</p> <p><a href="https://i.stack.imgur.com/Gj3QG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gj3QG.png" alt="enter image description here" /></a></p> <p>As you can see the Text is behind both elements.</p> <p>I tried to fix it using z-index but nothing worked for me. U have and ideas?</p>
[ { "answer_id": 74641210, "author": "Noam Riahi", "author_id": 9343039, "author_profile": "https://Stackoverflow.com/users/9343039", "pm_score": 1, "selected": true, "text": "void Start()\n{\n Application.targetFrameRate = 30;\n}\n void OnDestroy()\n {\n Application.targetFrameRate = -1;\n }\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17148835/" ]
74,518,268
<p>I am running a Java Program to download data from a Stock API. The URL is</p> <pre><code>https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&amp;resolution=5&amp;from=1668448858&amp;to=1668880918 </code></pre> <p>If I run this URL from the browser I get a JSON as a response. However if I run it from a Java program I get a 403 forbidden. I looked up the Developer tools in Chrome and setup all the HTTP Request Headers in the Java program. I added User-Agent/Cookie etc etc. However I still get the Forbidden 403 error.</p> <p>Below are the HTTP Headers that I have set: <a href="https://i.stack.imgur.com/Q0N58.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q0N58.png" alt="enter image description here" /></a></p> <p>Below is the stacktrace that I get in my Java program.</p> <pre><code>java.io.IOException: Server returned HTTP response code: 403 for URL: https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&amp;resolution=5&amp;from=1668448858&amp;to=1668880918 at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997) at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589) at java.base/java.net.URLConnection.getContent(URLConnection.java:753) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404) at ai.jeet.test.DataDownload.main(DataDownload.java:36) </code></pre> <p>When I run this API call via Postman I get a forbideen 403 but also get a HTML response which says enable Cookies and Javascript.</p> <p>I fail to understand how a Server can differentiate between a Web Request call. Obviously I am doing something wrong but I can't figure out what :-(</p>
[ { "answer_id": 74548420, "author": "Manish Kasera", "author_id": 1312806, "author_profile": "https://Stackoverflow.com/users/1312806", "pm_score": 1, "selected": false, "text": " curl -v 'https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918' -H 'User-Agent: Mozilla' -o /dev/null\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 2606:4700::6812:9a:443...\n* Connected to tvc4.investing.com (2606:4700::6812:9a) port 443 (#0)\n* ALPN, offering h2\n* ALPN, offering http/1.1\n* successfully set certificate verify locations:\n* CAfile: /etc/ssl/cert.pem\n* CApath: none\n* (304) (OUT), TLS handshake, Client hello (1):\n} [323 bytes data]\n* (304) (IN), TLS handshake, Server hello (2):\n{ [122 bytes data]\n* (304) (IN), TLS handshake, Unknown (8):\n{ [19 bytes data]\n* (304) (IN), TLS handshake, Certificate (11):\n{ [2326 bytes data]\n* (304) (IN), TLS handshake, CERT verify (15):\n{ [80 bytes data]\n* (304) (IN), TLS handshake, Finished (20):\n{ [36 bytes data]\n* (304) (OUT), TLS handshake, Finished (20):\n} [36 bytes data]\n* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256\n* ALPN, server accepted to use h2\n* Server certificate:\n* subject: C=US; ST=California; L=San Francisco; O=Cloudflare, Inc.; CN=investing.com\n* start date: Aug 1 00:00:00 2022 GMT\n* expire date: Aug 1 23:59:59 2023 GMT\n* subjectAltName: host \"tvc4.investing.com\" matched cert's \"*.investing.com\"\n* issuer: C=US; O=Cloudflare, Inc.; CN=Cloudflare Inc ECC CA-3\n* SSL certificate verify ok.\n* Using HTTP2, server supports multiplexing\n* Connection state changed (HTTP/2 confirmed)\n* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n* Using Stream ID: 1 (easy handle 0x137012600)\n> GET /49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918 HTTP/2\n> Host: tvc4.investing.com\n> accept: */*\n> user-agent: Mozilla\n>\n* Connection state changed (MAX_CONCURRENT_STREAMS == 256)!\n< HTTP/2 403\n< date: Wed, 23 Nov 2022 14:22:29 GMT\n< content-type: text/html; charset=UTF-8\n< cache-control: max-age=15\n< expires: Wed, 23 Nov 2022 14:22:44 GMT\n< x-frame-options: SAMEORIGIN\n< set-cookie: __cf_bm=uwoeNXvcnmEDY7ACRnFQEDqGZN4Yfx2_cyXbho.D6.M-1669213349-0-AUqobigV2idaMayGrBR+OdyTBo8pbjfS77vjhSh6bA4wiaBuz79/5kbwvXwD2loYoHJt1BsTguMEYh7WRm2ikPo=; path=/; expires=Wed, 23-Nov-22 14:52:29 GMT; domain=.investing.com; HttpOnly; Secure; SameSite=None\n< server: cloudflare\n< cf-ray: 76ea8eab8cbbb06a-ATL\n< alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\n<\n{ [972 bytes data]\n100 4537 0 4537 0 0 23760 0 --:--:-- --:--:-- --:--:-- 25346\n* Connection #0 to host tvc4.investing.com left intact\n curl -v 'https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918' -H 'User-Agent: Mozilla/5.0' -o /dev/null\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 2606:4700::6812:19a:443...\n* Connected to tvc4.investing.com (2606:4700::6812:19a) port 443 (#0)\n* ALPN, offering h2\n* ALPN, offering http/1.1\n* successfully set certificate verify locations:\n* CAfile: /etc/ssl/cert.pem\n* CApath: none\n* (304) (OUT), TLS handshake, Client hello (1):\n} [323 bytes data]\n* (304) (IN), TLS handshake, Server hello (2):\n{ [122 bytes data]\n* (304) (IN), TLS handshake, Unknown (8):\n{ [19 bytes data]\n* (304) (IN), TLS handshake, Certificate (11):\n{ [2326 bytes data]\n* (304) (IN), TLS handshake, CERT verify (15):\n{ [79 bytes data]\n* (304) (IN), TLS handshake, Finished (20):\n{ [36 bytes data]\n* (304) (OUT), TLS handshake, Finished (20):\n} [36 bytes data]\n* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256\n* ALPN, server accepted to use h2\n* Server certificate:\n* subject: C=US; ST=California; L=San Francisco; O=Cloudflare, Inc.; CN=investing.com\n* start date: Aug 1 00:00:00 2022 GMT\n* expire date: Aug 1 23:59:59 2023 GMT\n* subjectAltName: host \"tvc4.investing.com\" matched cert's \"*.investing.com\"\n* issuer: C=US; O=Cloudflare, Inc.; CN=Cloudflare Inc ECC CA-3\n* SSL certificate verify ok.\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Using HTTP2, server supports multiplexing\n* Connection state changed (HTTP/2 confirmed)\n* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n* Using Stream ID: 1 (easy handle 0x13800b600)\n> GET /49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918 HTTP/2\n> Host: tvc4.investing.com\n> accept: */*\n> user-agent: Mozilla/5.0\n>\n* Connection state changed (MAX_CONCURRENT_STREAMS == 256)!\n< HTTP/2 200\n< date: Wed, 23 Nov 2022 14:22:13 GMT\n< content-type: text/html; charset=utf-8\n< access-control-allow-origin: https://tvc-invdn-com.investing.com\n< x-requested-with: XMLHttpRequest\n< access-control-allow-methods: POST, GET, OPTIONS, PUT, DELETE\n< access-control-allow-headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, accept, sessionid, x-csrftoken, content-type\n< x-benchmark-1a: 0ms, mem alloc - 768.00Kb start\n< x-benchmark-1b: 3ms, mem alloc - 1024.00Kb getPairIdBySymbol\n< x-benchmark-1c: 3ms, mem alloc - 1024.00Kb getIntervalByResolution\n< x-benchmark-1d: 15ms, mem alloc - 1024.00Kb getPairDataAndAttributes in TradingviewConnector::findCandles\n< x-benchmark-1e: 23ms, mem alloc - 3.50Mb getCandles in TradingviewConnector::findCandles\n< x-benchmark-1f: 24ms, mem alloc - 3.75Mb end of TradingviewConnector::findCandles\n< x-benchmark-1g: 25ms, mem alloc - 3.50Mb findCandles\n< vary: Accept-Encoding,User-Agent\n< content-security-policy: upgrade-insecure-requests; block-all-mixed-content\n< cf-cache-status: DYNAMIC\n< set-cookie: __cf_bm=z7PZf80TAcglrPBqnAC0p4ApGjbAfRvCP6uZDBinzzs-1669213333-0-AYMziboPajXlvpP44SA/dGfK246VFdm8eaSnco06Ug7FiLfKcTheS1UjW4S8yD0EEJFSW7kqengoBx6dH8W7YLg=; path=/; expires=Wed, 23-Nov-22 14:52:13 GMT; domain=.investing.com; HttpOnly; Secure; SameSite=None\n< server: cloudflare\n< cf-ray: 76ea8e461cc9ad68-ATL\n< alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\n<\n{ [314 bytes data]\n100 19882 0 19882 0 0 61780 0 --:--:-- --:--:-- --:--:-- 62719\n* Connection #0 to host tvc4.investing.com left intact\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102040/" ]
74,518,307
<p>I'm a neophyte with c++. I wrote this code but the result for q have to be 1.0, but the code give me, changing the variable's order when I recall function &quot;intercetta&quot;, for example -34, 0, 9.75. Why?</p> <pre><code>#include &lt;iostream&gt; using namespace std; float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) { return m = ((y2 - y1) / (x2 - x1)); } float intercetta(float m, float x1, float y1, float q) { return q = y1 - m * x1; } int main() { float x1, x2, y1, y2, m=0, q=0; x1 = 3.5; x2 = 6.5; y1 = 9.75; y2 = 17.25; cout &lt;&lt; &quot;m= &quot; &lt;&lt; coefficienteAngolare(x1, x2, y1, y2, m) &lt;&lt; endl; cout &lt;&lt; &quot;q= &quot; &lt;&lt; intercetta(x1, y1, m, q) &lt;&lt; endl; } </code></pre>
[ { "answer_id": 74548420, "author": "Manish Kasera", "author_id": 1312806, "author_profile": "https://Stackoverflow.com/users/1312806", "pm_score": 1, "selected": false, "text": " curl -v 'https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918' -H 'User-Agent: Mozilla' -o /dev/null\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 2606:4700::6812:9a:443...\n* Connected to tvc4.investing.com (2606:4700::6812:9a) port 443 (#0)\n* ALPN, offering h2\n* ALPN, offering http/1.1\n* successfully set certificate verify locations:\n* CAfile: /etc/ssl/cert.pem\n* CApath: none\n* (304) (OUT), TLS handshake, Client hello (1):\n} [323 bytes data]\n* (304) (IN), TLS handshake, Server hello (2):\n{ [122 bytes data]\n* (304) (IN), TLS handshake, Unknown (8):\n{ [19 bytes data]\n* (304) (IN), TLS handshake, Certificate (11):\n{ [2326 bytes data]\n* (304) (IN), TLS handshake, CERT verify (15):\n{ [80 bytes data]\n* (304) (IN), TLS handshake, Finished (20):\n{ [36 bytes data]\n* (304) (OUT), TLS handshake, Finished (20):\n} [36 bytes data]\n* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256\n* ALPN, server accepted to use h2\n* Server certificate:\n* subject: C=US; ST=California; L=San Francisco; O=Cloudflare, Inc.; CN=investing.com\n* start date: Aug 1 00:00:00 2022 GMT\n* expire date: Aug 1 23:59:59 2023 GMT\n* subjectAltName: host \"tvc4.investing.com\" matched cert's \"*.investing.com\"\n* issuer: C=US; O=Cloudflare, Inc.; CN=Cloudflare Inc ECC CA-3\n* SSL certificate verify ok.\n* Using HTTP2, server supports multiplexing\n* Connection state changed (HTTP/2 confirmed)\n* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n* Using Stream ID: 1 (easy handle 0x137012600)\n> GET /49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918 HTTP/2\n> Host: tvc4.investing.com\n> accept: */*\n> user-agent: Mozilla\n>\n* Connection state changed (MAX_CONCURRENT_STREAMS == 256)!\n< HTTP/2 403\n< date: Wed, 23 Nov 2022 14:22:29 GMT\n< content-type: text/html; charset=UTF-8\n< cache-control: max-age=15\n< expires: Wed, 23 Nov 2022 14:22:44 GMT\n< x-frame-options: SAMEORIGIN\n< set-cookie: __cf_bm=uwoeNXvcnmEDY7ACRnFQEDqGZN4Yfx2_cyXbho.D6.M-1669213349-0-AUqobigV2idaMayGrBR+OdyTBo8pbjfS77vjhSh6bA4wiaBuz79/5kbwvXwD2loYoHJt1BsTguMEYh7WRm2ikPo=; path=/; expires=Wed, 23-Nov-22 14:52:29 GMT; domain=.investing.com; HttpOnly; Secure; SameSite=None\n< server: cloudflare\n< cf-ray: 76ea8eab8cbbb06a-ATL\n< alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\n<\n{ [972 bytes data]\n100 4537 0 4537 0 0 23760 0 --:--:-- --:--:-- --:--:-- 25346\n* Connection #0 to host tvc4.investing.com left intact\n curl -v 'https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918' -H 'User-Agent: Mozilla/5.0' -o /dev/null\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 2606:4700::6812:19a:443...\n* Connected to tvc4.investing.com (2606:4700::6812:19a) port 443 (#0)\n* ALPN, offering h2\n* ALPN, offering http/1.1\n* successfully set certificate verify locations:\n* CAfile: /etc/ssl/cert.pem\n* CApath: none\n* (304) (OUT), TLS handshake, Client hello (1):\n} [323 bytes data]\n* (304) (IN), TLS handshake, Server hello (2):\n{ [122 bytes data]\n* (304) (IN), TLS handshake, Unknown (8):\n{ [19 bytes data]\n* (304) (IN), TLS handshake, Certificate (11):\n{ [2326 bytes data]\n* (304) (IN), TLS handshake, CERT verify (15):\n{ [79 bytes data]\n* (304) (IN), TLS handshake, Finished (20):\n{ [36 bytes data]\n* (304) (OUT), TLS handshake, Finished (20):\n} [36 bytes data]\n* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256\n* ALPN, server accepted to use h2\n* Server certificate:\n* subject: C=US; ST=California; L=San Francisco; O=Cloudflare, Inc.; CN=investing.com\n* start date: Aug 1 00:00:00 2022 GMT\n* expire date: Aug 1 23:59:59 2023 GMT\n* subjectAltName: host \"tvc4.investing.com\" matched cert's \"*.investing.com\"\n* issuer: C=US; O=Cloudflare, Inc.; CN=Cloudflare Inc ECC CA-3\n* SSL certificate verify ok.\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Using HTTP2, server supports multiplexing\n* Connection state changed (HTTP/2 confirmed)\n* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n* Using Stream ID: 1 (easy handle 0x13800b600)\n> GET /49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918 HTTP/2\n> Host: tvc4.investing.com\n> accept: */*\n> user-agent: Mozilla/5.0\n>\n* Connection state changed (MAX_CONCURRENT_STREAMS == 256)!\n< HTTP/2 200\n< date: Wed, 23 Nov 2022 14:22:13 GMT\n< content-type: text/html; charset=utf-8\n< access-control-allow-origin: https://tvc-invdn-com.investing.com\n< x-requested-with: XMLHttpRequest\n< access-control-allow-methods: POST, GET, OPTIONS, PUT, DELETE\n< access-control-allow-headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, accept, sessionid, x-csrftoken, content-type\n< x-benchmark-1a: 0ms, mem alloc - 768.00Kb start\n< x-benchmark-1b: 3ms, mem alloc - 1024.00Kb getPairIdBySymbol\n< x-benchmark-1c: 3ms, mem alloc - 1024.00Kb getIntervalByResolution\n< x-benchmark-1d: 15ms, mem alloc - 1024.00Kb getPairDataAndAttributes in TradingviewConnector::findCandles\n< x-benchmark-1e: 23ms, mem alloc - 3.50Mb getCandles in TradingviewConnector::findCandles\n< x-benchmark-1f: 24ms, mem alloc - 3.75Mb end of TradingviewConnector::findCandles\n< x-benchmark-1g: 25ms, mem alloc - 3.50Mb findCandles\n< vary: Accept-Encoding,User-Agent\n< content-security-policy: upgrade-insecure-requests; block-all-mixed-content\n< cf-cache-status: DYNAMIC\n< set-cookie: __cf_bm=z7PZf80TAcglrPBqnAC0p4ApGjbAfRvCP6uZDBinzzs-1669213333-0-AYMziboPajXlvpP44SA/dGfK246VFdm8eaSnco06Ug7FiLfKcTheS1UjW4S8yD0EEJFSW7kqengoBx6dH8W7YLg=; path=/; expires=Wed, 23-Nov-22 14:52:13 GMT; domain=.investing.com; HttpOnly; Secure; SameSite=None\n< server: cloudflare\n< cf-ray: 76ea8e461cc9ad68-ATL\n< alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\n<\n{ [314 bytes data]\n100 19882 0 19882 0 0 61780 0 --:--:-- --:--:-- --:--:-- 62719\n* Connection #0 to host tvc4.investing.com left intact\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508454/" ]
74,518,337
<p>I am trying to write a schema for swagger api docs which have nested objects and arrays. the output does give error but &quot; unknow type: &quot; .</p> <p>The schema i have in my node models.js file</p> <p><a href="https://i.stack.imgur.com/UUnlW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UUnlW.png" alt="The schema" /></a></p> <p>The swagger code: `</p> <pre><code> @swagger components: schema: Buyer: type: object properties: id: type: string Buyer_name: type: string Buyer_Delivery_Address: type: object properties: address_line: type: String City: type:String Postal_Code: type:Number Country: type: String Buyer_Phone: type: Number Buyer_Cart: type: object properties: Product_ID: type: Number Product_Name: type:String Product_quantity: type:Number Product_Price: type:Number @swagger /buyer: get: summary: The get data from database description: displaying all data from database responses: 200: description: success fullydisplaying all data from database content: application/json: schema: type: array items: $ref: '#components/schema/Buyer' </code></pre> <p>`</p> <p>The Output on Swagger ui</p> <p><a href="https://i.stack.imgur.com/HxSou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HxSou.png" alt="The output on swagger UI" /></a></p> <p>i want to display the proper types in nested fields.</p>
[ { "answer_id": 74548420, "author": "Manish Kasera", "author_id": 1312806, "author_profile": "https://Stackoverflow.com/users/1312806", "pm_score": 1, "selected": false, "text": " curl -v 'https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918' -H 'User-Agent: Mozilla' -o /dev/null\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 2606:4700::6812:9a:443...\n* Connected to tvc4.investing.com (2606:4700::6812:9a) port 443 (#0)\n* ALPN, offering h2\n* ALPN, offering http/1.1\n* successfully set certificate verify locations:\n* CAfile: /etc/ssl/cert.pem\n* CApath: none\n* (304) (OUT), TLS handshake, Client hello (1):\n} [323 bytes data]\n* (304) (IN), TLS handshake, Server hello (2):\n{ [122 bytes data]\n* (304) (IN), TLS handshake, Unknown (8):\n{ [19 bytes data]\n* (304) (IN), TLS handshake, Certificate (11):\n{ [2326 bytes data]\n* (304) (IN), TLS handshake, CERT verify (15):\n{ [80 bytes data]\n* (304) (IN), TLS handshake, Finished (20):\n{ [36 bytes data]\n* (304) (OUT), TLS handshake, Finished (20):\n} [36 bytes data]\n* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256\n* ALPN, server accepted to use h2\n* Server certificate:\n* subject: C=US; ST=California; L=San Francisco; O=Cloudflare, Inc.; CN=investing.com\n* start date: Aug 1 00:00:00 2022 GMT\n* expire date: Aug 1 23:59:59 2023 GMT\n* subjectAltName: host \"tvc4.investing.com\" matched cert's \"*.investing.com\"\n* issuer: C=US; O=Cloudflare, Inc.; CN=Cloudflare Inc ECC CA-3\n* SSL certificate verify ok.\n* Using HTTP2, server supports multiplexing\n* Connection state changed (HTTP/2 confirmed)\n* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n* Using Stream ID: 1 (easy handle 0x137012600)\n> GET /49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918 HTTP/2\n> Host: tvc4.investing.com\n> accept: */*\n> user-agent: Mozilla\n>\n* Connection state changed (MAX_CONCURRENT_STREAMS == 256)!\n< HTTP/2 403\n< date: Wed, 23 Nov 2022 14:22:29 GMT\n< content-type: text/html; charset=UTF-8\n< cache-control: max-age=15\n< expires: Wed, 23 Nov 2022 14:22:44 GMT\n< x-frame-options: SAMEORIGIN\n< set-cookie: __cf_bm=uwoeNXvcnmEDY7ACRnFQEDqGZN4Yfx2_cyXbho.D6.M-1669213349-0-AUqobigV2idaMayGrBR+OdyTBo8pbjfS77vjhSh6bA4wiaBuz79/5kbwvXwD2loYoHJt1BsTguMEYh7WRm2ikPo=; path=/; expires=Wed, 23-Nov-22 14:52:29 GMT; domain=.investing.com; HttpOnly; Secure; SameSite=None\n< server: cloudflare\n< cf-ray: 76ea8eab8cbbb06a-ATL\n< alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\n<\n{ [972 bytes data]\n100 4537 0 4537 0 0 23760 0 --:--:-- --:--:-- --:--:-- 25346\n* Connection #0 to host tvc4.investing.com left intact\n curl -v 'https://tvc4.investing.com/49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918' -H 'User-Agent: Mozilla/5.0' -o /dev/null\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 2606:4700::6812:19a:443...\n* Connected to tvc4.investing.com (2606:4700::6812:19a) port 443 (#0)\n* ALPN, offering h2\n* ALPN, offering http/1.1\n* successfully set certificate verify locations:\n* CAfile: /etc/ssl/cert.pem\n* CApath: none\n* (304) (OUT), TLS handshake, Client hello (1):\n} [323 bytes data]\n* (304) (IN), TLS handshake, Server hello (2):\n{ [122 bytes data]\n* (304) (IN), TLS handshake, Unknown (8):\n{ [19 bytes data]\n* (304) (IN), TLS handshake, Certificate (11):\n{ [2326 bytes data]\n* (304) (IN), TLS handshake, CERT verify (15):\n{ [79 bytes data]\n* (304) (IN), TLS handshake, Finished (20):\n{ [36 bytes data]\n* (304) (OUT), TLS handshake, Finished (20):\n} [36 bytes data]\n* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256\n* ALPN, server accepted to use h2\n* Server certificate:\n* subject: C=US; ST=California; L=San Francisco; O=Cloudflare, Inc.; CN=investing.com\n* start date: Aug 1 00:00:00 2022 GMT\n* expire date: Aug 1 23:59:59 2023 GMT\n* subjectAltName: host \"tvc4.investing.com\" matched cert's \"*.investing.com\"\n* issuer: C=US; O=Cloudflare, Inc.; CN=Cloudflare Inc ECC CA-3\n* SSL certificate verify ok.\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Using HTTP2, server supports multiplexing\n* Connection state changed (HTTP/2 confirmed)\n* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n* Using Stream ID: 1 (easy handle 0x13800b600)\n> GET /49137b20ec52f5d1133789e270e21db8/1668879605/56/56/23/history?symbol=18325&resolution=5&from=1668448858&to=1668880918 HTTP/2\n> Host: tvc4.investing.com\n> accept: */*\n> user-agent: Mozilla/5.0\n>\n* Connection state changed (MAX_CONCURRENT_STREAMS == 256)!\n< HTTP/2 200\n< date: Wed, 23 Nov 2022 14:22:13 GMT\n< content-type: text/html; charset=utf-8\n< access-control-allow-origin: https://tvc-invdn-com.investing.com\n< x-requested-with: XMLHttpRequest\n< access-control-allow-methods: POST, GET, OPTIONS, PUT, DELETE\n< access-control-allow-headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, accept, sessionid, x-csrftoken, content-type\n< x-benchmark-1a: 0ms, mem alloc - 768.00Kb start\n< x-benchmark-1b: 3ms, mem alloc - 1024.00Kb getPairIdBySymbol\n< x-benchmark-1c: 3ms, mem alloc - 1024.00Kb getIntervalByResolution\n< x-benchmark-1d: 15ms, mem alloc - 1024.00Kb getPairDataAndAttributes in TradingviewConnector::findCandles\n< x-benchmark-1e: 23ms, mem alloc - 3.50Mb getCandles in TradingviewConnector::findCandles\n< x-benchmark-1f: 24ms, mem alloc - 3.75Mb end of TradingviewConnector::findCandles\n< x-benchmark-1g: 25ms, mem alloc - 3.50Mb findCandles\n< vary: Accept-Encoding,User-Agent\n< content-security-policy: upgrade-insecure-requests; block-all-mixed-content\n< cf-cache-status: DYNAMIC\n< set-cookie: __cf_bm=z7PZf80TAcglrPBqnAC0p4ApGjbAfRvCP6uZDBinzzs-1669213333-0-AYMziboPajXlvpP44SA/dGfK246VFdm8eaSnco06Ug7FiLfKcTheS1UjW4S8yD0EEJFSW7kqengoBx6dH8W7YLg=; path=/; expires=Wed, 23-Nov-22 14:52:13 GMT; domain=.investing.com; HttpOnly; Secure; SameSite=None\n< server: cloudflare\n< cf-ray: 76ea8e461cc9ad68-ATL\n< alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\n<\n{ [314 bytes data]\n100 19882 0 19882 0 0 61780 0 --:--:-- --:--:-- --:--:-- 62719\n* Connection #0 to host tvc4.investing.com left intact\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18955011/" ]
74,518,386
<p>I have been playing around with a pandas data frame with 414,000 rows.</p> <p>Built into pandas is an exponential moving average computed by:</p> <pre><code>series.ewm(span=period).mean() </code></pre> <p>The above executes in &lt; 0.3 seconds. I am however in search of trying to use a weighted moving average (which has a linear linear weighting of each element). I came across the following function:</p> <pre><code>def WMA(self, s, period): return s.rolling(period).apply(lambda x: (np.arange(period)+1*x).sum()/(np.arange(period)+1).sum(), raw=True) </code></pre> <p>The <strong>above function took 27 seconds</strong> to execute. I noticed the arange function could be cached and produced the following:</p> <pre><code>def WMA(self, s, period): weights = np.arange(period)+1 weights_sum = weights.sum() return s.rolling(period).apply(lambda x: (weights*x).sum()/weights_sum, raw=True) </code></pre> <p>The above function took <strong>11 seconds</strong>, which is a noticeable improvement.</p> <p>What I'm trying to figure out is if there is some way I can further optimize this (ideally replace the apply function) but genuinely am not sure how to go about it.</p> <p>Any ideas would be appreciated!</p>
[ { "answer_id": 74519701, "author": "Skeletor", "author_id": 16957329, "author_profile": "https://Stackoverflow.com/users/16957329", "pm_score": 2, "selected": true, "text": "np import numpy as np\nimport pandas as pd\n\nd1 = pd.DataFrame(np.random.randint(0, 10, size=(500_000))) # x=500_000\n\np = 50\nw = np.arange(p)+1\nw_s = w.sum()\n\n########## for comparison purpose ##########\n# 1.47 s ± 12.5 ms per loop (mean ± std. dev. of 7 runs, 2 loops each)\nr = d1.rolling(p).apply(lambda x: (w*x).sum()/w_s, raw=True)\n\n# 62.1 ms ± 4.57 ms per loop (mean ± std. dev. of 7 runs, 2 loops each)\nswv = np.lib.stride_tricks.sliding_window_view(d1.values.flatten(), window_shape=p)\nsw = (swv*w).sum(axis=1) / w_s\n\n########## for comparison purpose ##########\nnp.array_equal(r.iloc[p - 1:].values.flatten(), sw) # True\n ~23.67x sw 0 x-p r p x p -> nan" }, { "answer_id": 74526917, "author": "Deftness", "author_id": 4352047, "author_profile": "https://Stackoverflow.com/users/4352047", "pm_score": 1, "selected": false, "text": "nan # THIS USES LOWER LEVEL NUMPY TO GREATLY SPEED IT UP!\n def WMA(self, s, period):\n w = np.arange(period)+1\n w_s = w.sum() \n swv = sliding_window_view(s.values.flatten(), window_shape=period)\n sw = (swv * w).sum(axis=1) / w_s\n\n # Need to now return it as a normal series\n sw = np.concatenate((np.full(period - 1, np.nan), sw))\n return pd.Series(sw)\n" }, { "answer_id": 74560129, "author": "padu", "author_id": 16591526, "author_profile": "https://Stackoverflow.com/users/16591526", "pm_score": 0, "selected": false, "text": "apply import pandas as pd\nimport numpy as np\nfrom time import monotonic\nfrom parallel_pandas import ParallelPandas\n\n\ndef WMA(s, period):\n weights = np.arange(period) + 1\n weights_sum = weights.sum()\n return s.rolling(period).apply(lambda x: (weights * x).sum() / weights_sum, raw=True)\n\n\ndef parallel_wma(s, period):\n weights = np.arange(period) + 1\n weights_sum = weights.sum()\n # p_apply is parallel apply method\n return s.rolling(period).p_apply(lambda x: (weights * x).sum() / weights_sum, raw=True)\n\n\nif __name__ == '__main__':\n # initialize parallel-pandas\n ParallelPandas.initialize(n_cpu=16, disable_pr_bar=True)\n \n #create series of length 500 000\n s = pd.Series(np.random.randint(0, 5, size=500_000))\n period = 50\n\n start = monotonic()\n res = WMA(s, period)\n print(f'synchronous wma time took: {monotonic() - start:.2f} s.')\n\n start = monotonic()\n res2 = parallel_wma(s, period)\n print(f'parallel wma time took: {monotonic() - start:.2f} s.')\n Output:\n synchronous wma time took: 1.16 s.\n parallel wma time took: 0.22 s.\n\n 1.16/0.22 ~ 5.3 numpy" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4352047/" ]
74,518,418
<p>I have such a task</p> <p>I have file storage, about <strong>50GB</strong></p> <p>Almost all files are 100KB -&gt; 3MB. And there are tracing files of ~25mb - but these files are downloaded very often</p> <p>My task is to configure the software in such a way as to ensure maximum download performance from my Linux Server</p> <p>Server:</p> <ul> <li>System: Ubuntu 20</li> <li>Disk: SSD NVMe</li> <li>RAM 64 GB</li> <li>CPU: 12</li> <li>Internet: 1 Gbit/s</li> </ul> <p>I tried the following combinations</p> <ol> <li>Nginx</li> <li>Varnish + Nginx</li> </ol> <p>but I am facing the problem that the file download speed is up to 1 MB per second - even though I changed the settings in Nginx</p> <ul> <li>Average download time 16 sec = 25MB - from my server</li> <li>2-3 seconds - 25MB - from the Firebase server</li> </ul> <p>What software can be suitable for solving my problem? or in what direction do I need to look?</p>
[ { "answer_id": 74519676, "author": "Thijs Feryn", "author_id": 12892695, "author_profile": "https://Stackoverflow.com/users/12892695", "pm_score": 1, "selected": false, "text": "varnishd -s /etc/varnish/default.vcl" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8183510/" ]
74,518,424
<p>I have the following json format, basically it is a huge file with several of such entries.</p> <pre><code> [ { &quot;id&quot;: &quot;kslhe6em&quot;, &quot;version&quot;: &quot;R7.8.0.00_BNK&quot;, &quot;hostname&quot;: &quot;abacus-ap-hf-test-001:8080&quot;, &quot;status&quot;: &quot;RUNNING&quot;, }, { &quot;id&quot;: &quot;2bkaiupm&quot;, &quot;version&quot;: &quot;R7.8.0.00_BNK&quot;, &quot;hostname&quot;: &quot;abacus-ap-hotfix-001:8080&quot;, &quot;status&quot;: &quot;RUNNING&quot;, }, { &quot;id&quot;: &quot;rz5savbi&quot;, &quot;version&quot;: &quot;R7.8.0.00_BNK&quot;, &quot;hostname&quot;: &quot;abacus-ap-hf-test-005:8080&quot;, &quot;status&quot;: &quot;RUNNING&quot;, }, ] </code></pre> <p>I wanted to fetch all the hostname values that starts with &quot;abacus-ap-hf-test&quot; and without &quot;:8080&quot; into a variable and then wanted to use those values for further commands over a for loop something like below. But, am bit confused how can I extract such informaion.</p> <pre><code>HOSTAME=&quot;abacus-ap-hf-test-001 abacus-ap-hf-test-005&quot; for HOSTANAME in $HOSTNAME do sh ./trigger.sh done </code></pre>
[ { "answer_id": 74519676, "author": "Thijs Feryn", "author_id": 12892695, "author_profile": "https://Stackoverflow.com/users/12892695", "pm_score": 1, "selected": false, "text": "varnishd -s /etc/varnish/default.vcl" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10286342/" ]
74,518,429
<p>Alright so that seems easy but i couldnt find any solution or responses to it. I simply have a dataframe with a column full of nulls, and i just want to fill it with &quot;s&quot; or &quot;n&quot; randomly.</p> <p>I tried this `</p> <pre><code>df.foreach(f=&gt;{ if(random) f.get(4) = &quot;s&quot; else{f.get(4) = &quot;n&quot;} }) </code></pre> <p>`</p> <p>But doesnt work, cause i think f is just a list, not the actual value The pseudo would be something like that:</p> <pre><code>for(i=0;i&lt;max_rows;i++) if(prob&lt;.5) {df[i][&quot;column_field&quot;] == &quot;s&quot;} else {df[i][&quot;column_field&quot;] == &quot;n&quot;} </code></pre>
[ { "answer_id": 74519676, "author": "Thijs Feryn", "author_id": 12892695, "author_profile": "https://Stackoverflow.com/users/12892695", "pm_score": 1, "selected": false, "text": "varnishd -s /etc/varnish/default.vcl" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562262/" ]
74,518,435
<p>I want to search in a List of Strings, but the search query does not need to be in order as the result.</p> <p>Let's say I have a list of strings</p> <pre><code>List&lt;String&gt; a = [ Fracture of right arm, Fracture of left arm, Fracture of right leg, Fracture of left leg, ]; </code></pre> <p>and I want to implement a search filter that when I type <code>fracture right</code> the result would be</p> <pre><code>Fracture of right leg Fracture of right arm </code></pre> <p>How do I do this in Flutter? Because flutter <code>contains()</code> only detects when I type <code>fracture **of** right</code></p>
[ { "answer_id": 74519676, "author": "Thijs Feryn", "author_id": 12892695, "author_profile": "https://Stackoverflow.com/users/12892695", "pm_score": 1, "selected": false, "text": "varnishd -s /etc/varnish/default.vcl" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562344/" ]
74,518,449
<p>This is my query within my controller (index action):</p> <pre><code> @tags = ActiveRecord::Base.connection.execute( &lt;&lt;~SQL SELECT t.id, t.name, t.member_tags_count, ( SELECT json_agg(mt.member_id) as member_ids FROM member_tags mt WHERE mt.tag_id = t.id) FROM tags t ORDER BY LOWER(t.name) SQL ) render json: @tags </code></pre> <p>It runs in 1.9ms and returns the following:</p> <pre><code>#&lt;PG::Result:0x000000010e368580 status=PGRES_TUPLES_OK ntuples=31 nfields=4 cmd_tuples=31&gt; (ruby) @tags.first {&quot;id&quot;=&gt;1, &quot;name&quot;=&gt;&quot;Avengers&quot;, &quot;member_tags_count&quot;=&gt;3, &quot;member_ids&quot;=&gt;&quot;[1, 3, 7]&quot;} </code></pre> <p><strong>Problem:</strong> the <code>member_ids</code> should be an array of integers for an API, but it is currently returning as a string.</p> <p><strong>Question:</strong> is there a way to return <code>member_ids</code> as an array without looping through the <code>@tags</code> result to <code>JSON.parse</code> it?</p> <p>Below is my current implementation so I can move on, but it seems messy and takes 4x longer (5.7ms) to run.</p> <pre><code> @tags = Tag .joins(:member_tags) .order('LOWER(name)') .group(:id) .pluck( :id, :name, :member_tags_count, 'array_agg(member_tags.member_id)' ).map do |column| { id: column[0], name: column[1], member_tags_count: column[2], member_ids: column[3] } end render json: @tags </code></pre> <p>The above returns:</p> <pre><code>(ruby) @tags.first {:id=&gt;1, :name=&gt;&quot;Avengers&quot;, :member_tags_count=&gt;3, :member_ids=&gt;[1, 3, 7]} </code></pre>
[ { "answer_id": 74518872, "author": "max", "author_id": 544825, "author_profile": "https://Stackoverflow.com/users/544825", "pm_score": 1, "selected": false, "text": "json_agg array_agg query = Tag\n .joins(:member_tags)\n .order(Tag.arel_table[:name].lower)\n .group(:id)\n .select(\n :id,\n :name,\n :member_tags_count,\n Arel::Nodes::NamedFunction.new(\n 'json_agg', \n [MemberTag.arel_table[:member_id]]\n ).as('member_ids')\n )\n@tags = Tag.connection.select_all(query.arel).map(&:to_h)\n .pluck .select_all" }, { "answer_id": 74519235, "author": "mechnicov", "author_id": 10608621, "author_profile": "https://Stackoverflow.com/users/10608621", "pm_score": -1, "selected": false, "text": "as_json pluck select @tags = Tag\n .joins(:member_tags)\n .order('LOWER(name)')\n .group(:id)\n .select(\n :id,\n :name,\n :member_tags_count,\n 'array_agg(member_tags.member_id) AS member_ids'\n ).as_json\n\nrender json: @tags\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/427499/" ]
74,518,477
<p>A collection is defined in a view, where links for each element's successive and previous items need to be generated. (a css-only lightbox. While the index of those items is accessible,</p> <pre><code>&lt;% @gallery.each_with_index do |article_gallery, index| %&gt; &lt;%= succ = @gallery[index + 1] %&gt;&lt;%= succ.inspect %&gt; &lt;%= prev = @gallery[index - 1] %&gt; &lt;% end %&gt; </code></pre> <p>The inspection of the object returns the expected object</p> <pre><code>#&lt;ArticleGallery id: 1, article_id: 16, image: &quot;Screen_Shot_2022-11-17_at_07.46.05.png&quot;, position: 2, [...]&gt; </code></pre> <p>But it's id cannot be accessed. if <code>succ.id</code> in lieu of <code>succ.inspect</code> is called it is deemed to now be a nil object.</p> <pre><code>undefined method `id' for nil:NilClass @output_buffer.safe_append=' '.freeze;@output_buffer.append=( succ = @gallery[index + 1] );@output_buffer.append=( succ.id );@output_buffer.safe_append=' </code></pre> <p>What is the proper way to access an attribute for the relative previous or successive object?</p>
[ { "answer_id": 74518872, "author": "max", "author_id": 544825, "author_profile": "https://Stackoverflow.com/users/544825", "pm_score": 1, "selected": false, "text": "json_agg array_agg query = Tag\n .joins(:member_tags)\n .order(Tag.arel_table[:name].lower)\n .group(:id)\n .select(\n :id,\n :name,\n :member_tags_count,\n Arel::Nodes::NamedFunction.new(\n 'json_agg', \n [MemberTag.arel_table[:member_id]]\n ).as('member_ids')\n )\n@tags = Tag.connection.select_all(query.arel).map(&:to_h)\n .pluck .select_all" }, { "answer_id": 74519235, "author": "mechnicov", "author_id": 10608621, "author_profile": "https://Stackoverflow.com/users/10608621", "pm_score": -1, "selected": false, "text": "as_json pluck select @tags = Tag\n .joins(:member_tags)\n .order('LOWER(name)')\n .group(:id)\n .select(\n :id,\n :name,\n :member_tags_count,\n 'array_agg(member_tags.member_id) AS member_ids'\n ).as_json\n\nrender json: @tags\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291357/" ]
74,518,514
<p>I have this string variable.</p> <p><code>x &lt;- &quot;[2,3,3,5]&quot;</code></p> <p>I want to get the average of this. How can I achieve this on R?</p>
[ { "answer_id": 74518547, "author": "user438383", "author_id": 5784757, "author_profile": "https://Stackoverflow.com/users/5784757", "pm_score": 2, "selected": false, "text": "library(stringr)\nlibrary(dplyr)\n\nstr_split(x, \",\")[[1]] %>% \n str_remove_all(\"\\\\[|\\\\]\") %>% \n as.numeric %>% \n mean\n [1] 3.25\n" }, { "answer_id": 74518558, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": false, "text": "mean(as.numeric(strsplit(x, '\\\\D')[[1]]), na.rm = TRUE)\n#> [1] 3.25\n" }, { "answer_id": 74518708, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 0, "selected": false, "text": "parse eval stringr::str_replace_all(x, c(\"\\\\[\" = \"c\\\\(\", \"\\\\]\" = \"\\\\)\")) %>% parse(text = .) %>% eval() %>% mean()\n" }, { "answer_id": 74518827, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 2, "selected": false, "text": "mean(jsonlite::fromJSON(x))\n# [1] 3.25\n x <- \"[2,3,3,5]\"\n" }, { "answer_id": 74518968, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 2, "selected": false, "text": "[] c() eval > mean(eval(str2lang(paste0(\"c\", chartr(\"[]\", \"()\", x)))))\n[1] 3.25\n scan substr > mean(scan(text = substr(x, 2, nchar(x) - 1), sep = \",\", quiet = TRUE))\n[1] 3.25\n py_eval > library(reticulate)\n\n> mean(py_eval(x))\n[1] 3.25\n" }, { "answer_id": 74521731, "author": "Carl Witthoft", "author_id": 884372, "author_profile": "https://Stackoverflow.com/users/884372", "pm_score": 0, "selected": false, "text": "x <- \"[2,37,1, -45]\"\nRgames> mean(as.numeric(strsplit(x, '\\\\D')[[1]]), na.rm = TRUE)\n[1] 21.25\nRgames> mean(as.numeric(str_extract_all(x, \"[0-9]\")[[1]]))\n[1] 3.666667\nRgames> mean(c(2,37,1,-45))\n[1] -1.25\n x <- \"[4.8,-65]\" Rgames> stringr::str_replace_all(x, c(\"\\\\[\" = \"c\\\\(\", \"\\\\]\" = \"\\\\)\")) %>% parse(text = .) %>% eval() %>% mean()\n[1] -1.25\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14440209/" ]
74,518,539
<p>In Azure Devops while creating queries. anybody knows what is the use of 'Query Text' Parameter?</p> <p>Not able to figure out what is this used for</p>
[ { "answer_id": 74518547, "author": "user438383", "author_id": 5784757, "author_profile": "https://Stackoverflow.com/users/5784757", "pm_score": 2, "selected": false, "text": "library(stringr)\nlibrary(dplyr)\n\nstr_split(x, \",\")[[1]] %>% \n str_remove_all(\"\\\\[|\\\\]\") %>% \n as.numeric %>% \n mean\n [1] 3.25\n" }, { "answer_id": 74518558, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": false, "text": "mean(as.numeric(strsplit(x, '\\\\D')[[1]]), na.rm = TRUE)\n#> [1] 3.25\n" }, { "answer_id": 74518708, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 0, "selected": false, "text": "parse eval stringr::str_replace_all(x, c(\"\\\\[\" = \"c\\\\(\", \"\\\\]\" = \"\\\\)\")) %>% parse(text = .) %>% eval() %>% mean()\n" }, { "answer_id": 74518827, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 2, "selected": false, "text": "mean(jsonlite::fromJSON(x))\n# [1] 3.25\n x <- \"[2,3,3,5]\"\n" }, { "answer_id": 74518968, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 2, "selected": false, "text": "[] c() eval > mean(eval(str2lang(paste0(\"c\", chartr(\"[]\", \"()\", x)))))\n[1] 3.25\n scan substr > mean(scan(text = substr(x, 2, nchar(x) - 1), sep = \",\", quiet = TRUE))\n[1] 3.25\n py_eval > library(reticulate)\n\n> mean(py_eval(x))\n[1] 3.25\n" }, { "answer_id": 74521731, "author": "Carl Witthoft", "author_id": 884372, "author_profile": "https://Stackoverflow.com/users/884372", "pm_score": 0, "selected": false, "text": "x <- \"[2,37,1, -45]\"\nRgames> mean(as.numeric(strsplit(x, '\\\\D')[[1]]), na.rm = TRUE)\n[1] 21.25\nRgames> mean(as.numeric(str_extract_all(x, \"[0-9]\")[[1]]))\n[1] 3.666667\nRgames> mean(c(2,37,1,-45))\n[1] -1.25\n x <- \"[4.8,-65]\" Rgames> stringr::str_replace_all(x, c(\"\\\\[\" = \"c\\\\(\", \"\\\\]\" = \"\\\\)\")) %>% parse(text = .) %>% eval() %>% mean()\n[1] -1.25\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1608636/" ]
74,518,542
<p>Trying to add header in prime ng sidebar component but its not working</p> <pre><code>&lt;p-sidebar [(visible)]=&quot;visibleSidebar1&quot;&gt;   &lt;ng-template p-Template=&quot;header&quot;&gt; &lt;p&gt;&quot;Header&quot;&lt;/p&gt; &lt;/ng-template&gt; My content goes here &lt;/p-sidebar&gt; </code></pre>
[ { "answer_id": 74545813, "author": "Vino", "author_id": 18615238, "author_profile": "https://Stackoverflow.com/users/18615238", "pm_score": 0, "selected": false, "text": "<p-sidebar [(visible)]=\"visibleSidebar1\"><app-shared-component></app-shared-component></p-sidebar>\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18615238/" ]
74,518,545
<p>I am passing a prop called product which has a list of objects inside a variable images. I want to display first image with id number 1 on the frontend. Also if I want to iterate through the images what would be the best way. I have attached the object image as seen on postman as a photo. I am trying to display this line in the card &lt;Card.Img src={product.images} /&gt;</p> <pre><code>{ function Product({ product }) { return ( &lt;Card className=&quot;my-3 p-3 rounded&quot;&gt; &lt;Link to={`/product/${product._id}`}&gt; &lt;Card.Img src={product.images} /&gt; &lt;/Link&gt; &lt;Card.Body&gt; &lt;Link to={`/product/${product._id}`}&gt; &lt;Card.Title as=&quot;div&quot;&gt; &lt;strong&gt;{product.name}&lt;/strong&gt; &lt;/Card.Title&gt; &lt;/Link&gt; &lt;Card.Text as=&quot;div&quot;&gt; &lt;div className=&quot;my-3&quot;&gt; &lt;Rating value={product.rating} text={`${product.numReviews} reviews`} color={'#f8e825'} /&gt; &lt;/div&gt; &lt;/Card.Text&gt; &lt;Card.Text as=&quot;h3&quot;&gt; ${product.price} &lt;/Card.Text&gt; &lt;/Card.Body&gt; &lt;/Card&gt; ) } </code></pre> <p><a href="https://i.stack.imgur.com/AbMVe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AbMVe.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74545813, "author": "Vino", "author_id": 18615238, "author_profile": "https://Stackoverflow.com/users/18615238", "pm_score": 0, "selected": false, "text": "<p-sidebar [(visible)]=\"visibleSidebar1\"><app-shared-component></app-shared-component></p-sidebar>\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7036949/" ]
74,518,604
<p>I'm trying to find a way to do something which is probably quite simple. I want to get the average values and standard deviations of &quot;A&quot;, &quot;B&quot; and &quot;C&quot; for each day in the following dataset:</p> <pre><code>M &lt;- c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;, &quot;B&quot;, &quot;C&quot;, &quot;C&quot;, &quot;C&quot;,&quot;C&quot;, &quot;C&quot; ) DCol &lt;- c(&quot;19800101&quot;,&quot;19800102&quot;, &quot;19800103&quot;, &quot;19800104&quot;, &quot;19800105&quot;,&quot;19800101&quot;,&quot;19800102&quot;, &quot;19800103&quot;, &quot;19800104&quot;, &quot;19800105&quot;,&quot;19800101&quot;,&quot;19800102&quot;, &quot;19800103&quot;, &quot;19800104&quot;, &quot;19800105&quot;) V1 &lt;- c(-6.8,-6.5,-6.05,-6.5,-5.2,-7.08,-5.7,-4.6,-4.6,-6.8,-6.5,-6.05,-6.5,-5.2, -7.06) V2 &lt;- c(-11.04,-11.1,-10.9,-10.6,-9.6,-11.6,-11.6,-9.7,-8.8,-11.1,-10.9,-10.6,-9.6,-11.6, -10.0) V3 &lt;- c(1.1,1.3,1.8,1.6,0.6,1.1,1.3,1.5,1.7,0.6,1.1,1.3,1.5,1.7, 1.1) df &lt;- data.frame(M, DCol, V1, V2, V3) </code></pre> <p>df Where M is a climate model, DCol is a series of dates, and V 1:V3 the results by model. So the data frame looks as follows:</p> <pre><code> M DCol V1 V2 V3 [1,] &quot;A&quot; &quot;19800101&quot; &quot;-6.8&quot; &quot;-11.04&quot; &quot;1.1&quot; [2,] &quot;A&quot; &quot;19800102&quot; &quot;-6.5&quot; &quot;-11.1&quot; &quot;1.3&quot; [3,] &quot;A&quot; &quot;19800103&quot; &quot;-6.05&quot; &quot;-10.9&quot; &quot;1.8&quot; [4,] &quot;A&quot; &quot;19800104&quot; &quot;-6.5&quot; &quot;-10.6&quot; &quot;1.6&quot; [5,] &quot;A&quot; &quot;19800105&quot; &quot;-5.2&quot; &quot;-9.6&quot; &quot;0.6&quot; [6,] &quot;B&quot; &quot;19800101&quot; &quot;-7.08&quot; &quot;-11.6&quot; &quot;1.1&quot; [7,] &quot;B&quot; &quot;19800102&quot; &quot;-5.7&quot; &quot;-11.6&quot; &quot;1.3&quot; [8,] &quot;B&quot; &quot;19800103&quot; &quot;-4.6&quot; &quot;-9.7&quot; &quot;1.5&quot; [9,] &quot;B&quot; &quot;19800104&quot; &quot;-4.6&quot; &quot;-8.8&quot; &quot;1.7&quot; [10,] &quot;B&quot; &quot;19800105&quot; &quot;-6.8&quot; &quot;-11.1&quot; &quot;0.6&quot; [11,] &quot;C&quot; &quot;19800101&quot; &quot;-6.5&quot; &quot;-10.9&quot; &quot;1.1&quot; [12,] &quot;C&quot; &quot;19800102&quot; &quot;-6.05&quot; &quot;-10.6&quot; &quot;1.3&quot; [13,] &quot;C&quot; &quot;19800103&quot; &quot;-6.5&quot; &quot;-9.6&quot; &quot;1.5&quot; [14,] &quot;C&quot; &quot;19800104&quot; &quot;-5.2&quot; &quot;-11.6&quot; &quot;1.7&quot; [15,] &quot;C&quot; &quot;19800105&quot; &quot;-7.06&quot; &quot;-10&quot; &quot;1.1&quot; </code></pre> <p>The resulting output in this instance would be a five row dataset with DCol, V1, V2, V3, and if possible standard deviations in adjacent columns.</p> <pre><code> Date period Model RCP Date meanTemp maxTemp minTemp precipitation windSpeed rad humidity 101908 2 HadGEM2-ES 26 19800101 -6.60 -5.9 -7.3 0.04 0.8217593 8.101852 100.0 101909 2 HadGEM2-ES 26 19800102 -6.20 -5.0 -7.4 0.08 2.2453704 9.259259 100.0 101910 2 HadGEM2-ES 26 19800103 -5.70 -5.0 -6.4 0.28 1.9444444 8.101852 94.7 101911 2 HadGEM2-ES 26 19800104 -5.70 -5.0 -6.4 0.08 1.0416667 8.101852 97.5 101912 2 HadGEM2-ES 26 19800105 -6.20 -5.0 -7.4 0.00 1.1226852 9.259259 98.5 </code></pre> <p>A sample of the whole dataset, I have to say I don't understand the aggregate function well enough to know why it isn't working here. Thanks in advance.</p>
[ { "answer_id": 74518753, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "df %>% \n as_tibble() %>% \n type.convert(as.is = TRUE) %>% \n dplyr::group_by(DCol) %>%\n summarise(across(c(V1, V2, V3), list(mean = mean, sd = sd), .names = \"{col}_{fn}\"))\n\n DCol V1_mean V1_sd V2_mean V2_sd V3_mean V3_sd\n <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n1 19800101 -6.79 0.290 -11.2 0.370 1.1 0 \n2 19800102 -6.08 0.401 -11.1 0.5 1.3 0 \n3 19800103 -5.72 0.993 -10.1 0.723 1.6 0.173 \n4 19800104 -5.43 0.971 -10.3 1.42 1.67 0.0577\n5 19800105 -6.35 1.01 -10.2 0.777 0.767 0.289\n as_tibble type.convert(as.is=TRUE) library(dplyr)\nlibrary(tibble)\n\ndf %>% \n as_tibble() %>% \n type.convert(as.is = TRUE) %>% \n group_by(M) %>%\n mutate(across(c(V1, V2, V3), list(mean = mean, sd = sd), .names = \"{col}_{fn}\"))\n M DCol V1 V2 V3 V1_mean V1_sd V2_mean V2_sd V3_mean V3_sd\n <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n 1 A 19800101 -6.8 -11.0 1.1 -6.21 0.625 -10.6 0.617 1.28 0.466\n 2 A 19800102 -6.5 -11.1 1.3 -6.21 0.625 -10.6 0.617 1.28 0.466\n 3 A 19800103 -6.05 -10.9 1.8 -6.21 0.625 -10.6 0.617 1.28 0.466\n 4 A 19800104 -6.5 -10.6 1.6 -6.21 0.625 -10.6 0.617 1.28 0.466\n 5 A 19800105 -5.2 -9.6 0.6 -6.21 0.625 -10.6 0.617 1.28 0.466\n 6 B 19800101 -7.08 -11.6 1.1 -5.76 1.17 -10.6 1.25 1.24 0.422\n 7 B 19800102 -5.7 -11.6 1.3 -5.76 1.17 -10.6 1.25 1.24 0.422\n 8 B 19800103 -4.6 -9.7 1.5 -5.76 1.17 -10.6 1.25 1.24 0.422\n 9 B 19800104 -4.6 -8.8 1.7 -5.76 1.17 -10.6 1.25 1.24 0.422\n10 B 19800105 -6.8 -11.1 0.6 -5.76 1.17 -10.6 1.25 1.24 0.422\n11 C 19800101 -6.5 -10.9 1.1 -6.26 0.693 -10.5 0.780 1.34 0.261\n12 C 19800102 -6.05 -10.6 1.3 -6.26 0.693 -10.5 0.780 1.34 0.261\n13 C 19800103 -6.5 -9.6 1.5 -6.26 0.693 -10.5 0.780 1.34 0.261\n14 C 19800104 -5.2 -11.6 1.7 -6.26 0.693 -10.5 0.780 1.34 0.261\n15 C 19800105 -7.06 -10 1.1 -6.26 0.693 -10.5 0.780 1.34 0.261\n" }, { "answer_id": 74518966, "author": "Sotos", "author_id": 5635580, "author_profile": "https://Stackoverflow.com/users/5635580", "pm_score": 2, "selected": false, "text": "aggregate() aggregate(.~DCol, df[-1], FUN = function(x) c(avg = mean(x), sd = sd(x)))\n\n DCol V1.avg V1.sd V2.avg V2.sd V3.avg V3.sd\n1 19800101 -6.7933333 0.2900575 -11.1800000 0.3704052 1.10000000 0.00000000\n2 19800102 -6.0833333 0.4010403 -11.1000000 0.5000000 1.30000000 0.00000000\n3 19800103 -5.7166667 0.9928914 -10.0666667 0.7234178 1.60000000 0.17320508\n4 19800104 -5.4333333 0.9712535 -10.3333333 1.4189198 1.66666667 0.05773503\n5 19800105 -6.3533333 1.0072405 -10.2333333 0.7767453 0.76666667 0.28867513\n" }, { "answer_id": 74519252, "author": "Andy Baxter", "author_id": 10744082, "author_profile": "https://Stackoverflow.com/users/10744082", "pm_score": 2, "selected": true, "text": "library(tidyverse)\n\n\ndf %>% \n group_by(DCol) %>%\n summarise(across(c(V1, V2, V3), list(mean = mean, sd = sd), .names = \"{col}_{fn}\"))\n#> # A tibble: 5 × 7\n#> DCol V1_mean V1_sd V2_mean V2_sd V3_mean V3_sd\n#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 19800101 -6.79 0.290 -11.2 0.370 1.1 0 \n#> 2 19800102 -6.08 0.401 -11.1 0.5 1.3 0 \n#> 3 19800103 -5.72 0.993 -10.1 0.723 1.6 0.173 \n#> 4 19800104 -5.43 0.971 -10.3 1.42 1.67 0.0577\n#> 5 19800105 -6.35 1.01 -10.2 0.777 0.767 0.289\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17438953/" ]
74,518,632
<p>I have a wide data frame similar to document term matrix:</p> <pre><code>df_names_tkns &lt;- tibble::tribble( ~name, ~aaa, ~ddd, ~downing, ~eee, ~london, ~street, ~bbb, ~broadway, ~ccc, ~new, ~york, &quot;AAA LONDON DOWNING STREET DDD EEE&quot;, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, NA, NA, NA, &quot;AAA NEW YORK BROADWAY BBB CCC&quot;, 1L, NA, NA, NA, NA, NA, 1L, 1L, 1L, 1L, 1L ) </code></pre> <p>I would like to replace bulk in all columns where x &gt; 0 the value into the name of the column. What would be the correct syntax? I have tried the following two approaches, with if and with case_when.</p> <pre class="lang-r prettyprint-override"><code> df_names_tkns2 &lt;- df_names_tkns |&gt; mutate(across(2:ncol(df_names_tkns), function (x) if (x &gt; 0) cur_column(x) else x)) </code></pre> <p>The error quote:</p> <pre><code>Caused by error in `across()`: ! Problem while computing column `aaa`. Caused by error in `if (x &gt; 0) ...`: ! the condition has length &gt; 1 </code></pre> <p>Or I tried</p> <pre><code>df_names_tkns2 &lt;- df_names_tkns |&gt; mutate( across( 2:ncol(df_names_tkns), ~ case_when(.x &gt; 1 ~ cur_column(.x)) ) ) ) </code></pre> <p>Error quote:</p> <pre><code>Caused by error in `across()`: ! Problem while computing column `aaa`. Caused by error in `cur_column()`: ! unused argument (aaa) </code></pre> <p>Apparently I am not using the right syntax for writing the function. What would be the correct way?</p>
[ { "answer_id": 74518753, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "df %>% \n as_tibble() %>% \n type.convert(as.is = TRUE) %>% \n dplyr::group_by(DCol) %>%\n summarise(across(c(V1, V2, V3), list(mean = mean, sd = sd), .names = \"{col}_{fn}\"))\n\n DCol V1_mean V1_sd V2_mean V2_sd V3_mean V3_sd\n <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n1 19800101 -6.79 0.290 -11.2 0.370 1.1 0 \n2 19800102 -6.08 0.401 -11.1 0.5 1.3 0 \n3 19800103 -5.72 0.993 -10.1 0.723 1.6 0.173 \n4 19800104 -5.43 0.971 -10.3 1.42 1.67 0.0577\n5 19800105 -6.35 1.01 -10.2 0.777 0.767 0.289\n as_tibble type.convert(as.is=TRUE) library(dplyr)\nlibrary(tibble)\n\ndf %>% \n as_tibble() %>% \n type.convert(as.is = TRUE) %>% \n group_by(M) %>%\n mutate(across(c(V1, V2, V3), list(mean = mean, sd = sd), .names = \"{col}_{fn}\"))\n M DCol V1 V2 V3 V1_mean V1_sd V2_mean V2_sd V3_mean V3_sd\n <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n 1 A 19800101 -6.8 -11.0 1.1 -6.21 0.625 -10.6 0.617 1.28 0.466\n 2 A 19800102 -6.5 -11.1 1.3 -6.21 0.625 -10.6 0.617 1.28 0.466\n 3 A 19800103 -6.05 -10.9 1.8 -6.21 0.625 -10.6 0.617 1.28 0.466\n 4 A 19800104 -6.5 -10.6 1.6 -6.21 0.625 -10.6 0.617 1.28 0.466\n 5 A 19800105 -5.2 -9.6 0.6 -6.21 0.625 -10.6 0.617 1.28 0.466\n 6 B 19800101 -7.08 -11.6 1.1 -5.76 1.17 -10.6 1.25 1.24 0.422\n 7 B 19800102 -5.7 -11.6 1.3 -5.76 1.17 -10.6 1.25 1.24 0.422\n 8 B 19800103 -4.6 -9.7 1.5 -5.76 1.17 -10.6 1.25 1.24 0.422\n 9 B 19800104 -4.6 -8.8 1.7 -5.76 1.17 -10.6 1.25 1.24 0.422\n10 B 19800105 -6.8 -11.1 0.6 -5.76 1.17 -10.6 1.25 1.24 0.422\n11 C 19800101 -6.5 -10.9 1.1 -6.26 0.693 -10.5 0.780 1.34 0.261\n12 C 19800102 -6.05 -10.6 1.3 -6.26 0.693 -10.5 0.780 1.34 0.261\n13 C 19800103 -6.5 -9.6 1.5 -6.26 0.693 -10.5 0.780 1.34 0.261\n14 C 19800104 -5.2 -11.6 1.7 -6.26 0.693 -10.5 0.780 1.34 0.261\n15 C 19800105 -7.06 -10 1.1 -6.26 0.693 -10.5 0.780 1.34 0.261\n" }, { "answer_id": 74518966, "author": "Sotos", "author_id": 5635580, "author_profile": "https://Stackoverflow.com/users/5635580", "pm_score": 2, "selected": false, "text": "aggregate() aggregate(.~DCol, df[-1], FUN = function(x) c(avg = mean(x), sd = sd(x)))\n\n DCol V1.avg V1.sd V2.avg V2.sd V3.avg V3.sd\n1 19800101 -6.7933333 0.2900575 -11.1800000 0.3704052 1.10000000 0.00000000\n2 19800102 -6.0833333 0.4010403 -11.1000000 0.5000000 1.30000000 0.00000000\n3 19800103 -5.7166667 0.9928914 -10.0666667 0.7234178 1.60000000 0.17320508\n4 19800104 -5.4333333 0.9712535 -10.3333333 1.4189198 1.66666667 0.05773503\n5 19800105 -6.3533333 1.0072405 -10.2333333 0.7767453 0.76666667 0.28867513\n" }, { "answer_id": 74519252, "author": "Andy Baxter", "author_id": 10744082, "author_profile": "https://Stackoverflow.com/users/10744082", "pm_score": 2, "selected": true, "text": "library(tidyverse)\n\n\ndf %>% \n group_by(DCol) %>%\n summarise(across(c(V1, V2, V3), list(mean = mean, sd = sd), .names = \"{col}_{fn}\"))\n#> # A tibble: 5 × 7\n#> DCol V1_mean V1_sd V2_mean V2_sd V3_mean V3_sd\n#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 19800101 -6.79 0.290 -11.2 0.370 1.1 0 \n#> 2 19800102 -6.08 0.401 -11.1 0.5 1.3 0 \n#> 3 19800103 -5.72 0.993 -10.1 0.723 1.6 0.173 \n#> 4 19800104 -5.43 0.971 -10.3 1.42 1.67 0.0577\n#> 5 19800105 -6.35 1.01 -10.2 0.777 0.767 0.289\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480717/" ]
74,518,649
<p>I want to get the Maximum date from all the tables in my database. I am using user table ALL_TABLES to get the table_name and column_name but I'm not bale to extract the max date of all the tables present in a database.</p> <pre><code>SELECT MAX(dt_load) FROM (SELECT table_name, column_name FROM all_tables WHERE column_name = 'DT_LOAD'); </code></pre> <p>I know that I need to use Dynamic SQL but I'm not able to get that</p>
[ { "answer_id": 74518723, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 0, "selected": false, "text": "SQL> create table test as select 1 id, date '2022-11-21' dt_load from dual;\n\nTable created.\n\nSQL> create table test_2 as select 1 id, date '2022-08-15' dt_load from dual;\n\nTable created.\n SQL> declare\n 2 l_max_date date;\n 3 l_max_overall date := date '0001-01-01';\n 4 begin\n 5 for cur_R in (select table_name\n 6 from user_tab_columns\n 7 where column_name = 'DT_LOAD'\n 8 )\n 9 loop\n 10 execute immediate 'select max(dt_load) from ' || cur_r.table_name into l_max_date;\n 11 dbms_output.put_line(cur_r.table_name ||': '|| to_char(l_max_date, 'dd.mm.yyyy'));\n 12 l_max_overall := greatest(l_max_overall, l_max_date);\n 13 end loop;\n 14 dbms_output.put_line('Overall MAX date: ' || to_char(l_max_overall, 'dd.mm.yyyy'));\n 15 end;\n 16 /\nTEST: 21.11.2022\nTEST_2: 15.08.2022\nOverall MAX date: 21.11.2022\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74518769, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT 'SELECT MAX(max_dt) FROM (' AS query FROM DUAL\nUNION ALL\nSELECT CASE WHEN ROWNUM > 1 THEN ' UNION ALL ' END\n || 'SELECT MAX(dt_load) AS max_dt FROM \"' || owner || '\".\"' || table_name || '\"'\nFROM all_tab_columns\nWHERE column_name = 'DT_LOAD'\nUNION ALL\nSELECT ')' FROM DUAL;\n LISTAGG DECLARE\n v_sql CLOB;\n v_max_date DATE;\nBEGIN\n FOR query IN (\n SELECT 'SELECT MAX(max_dt) FROM (' AS query FROM DUAL\n UNION ALL\n SELECT CASE WHEN ROWNUM > 1 THEN ' UNION ALL ' END\n || 'SELECT MAX(dt_load) AS max_dt FROM \"' || owner || '\".\"' || table_name || '\"'\n FROM all_tab_columns\n WHERE column_name = 'DT_LOAD'\n UNION ALL\n SELECT ')' FROM DUAL\n )\n LOOP\n v_sql := v_sql || query.query;\n END LOOP;\n\n EXECUTE IMMEDIATE v_sql INTO v_max_date;\n DBMS_OUTPUT.PUT_LINE(v_max_date);\nEND;\n/\n CREATE TABLE table1 (dt_load) AS\nSELECT SYSDATE FROM DUAL;\n\nCREATE TABLE table2 (id, dt_load) AS\nSELECT LEVEL, TRUNC(SYSDATE) - LEVEL FROM DUAL CONNECT BY LEVEL <= 5;\n 2022-11-21 12:24:54\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7863786/" ]
74,518,668
<p><strong>Task:</strong> I have to check if there are any two values consecutively same in an array. If it does. I have to take that repeated value into a different place to not have 2 identical values next to each other.</p> <p><strong>Problem:</strong> It returns there are no identical values, when definitely there are more than one. I know that this is happening because the &quot;if&quot; compares the first two elements and as they are not the same returns and stop the loop. But what I need is to complete the whole loop and if there are consecutive repeated values enter into the next loop.</p> <p>I've tried to figure it out solution and genuinely understand it for a long time, and I couldn't.</p> <p><strong>What I've tried:</strong> (I am working with a Stack, I will not post the methods of it because I know they are working fine for other exercises)</p> <pre><code> function noIdenticalConsecutives(arr) { let stack = new Stack(); let repeat = []; if (arr.length === 0) return &quot;No values to iterate&quot;; for (let i = 0; i &lt; arr.length - 1; i++) { const curr = arr[i]; const next = arr[i + 1]; if (curr !== next) return &quot;There are no identical consecutive values&quot;; } for (let i = 0; i &lt; arr.length; i++) { if(arr[i] === arr[i+1]){ repeat.push(arr[i]) }else{ stack.push(arr[i]) } } for (let i = 0; i &lt; repeat.length; i++) { const element = repeat[i]; stack.push(element); } return stack; } noIdenticalConsecutives([14, 4, 10, 7, 3, 1, 1, 5, 7, 7]);//There are no identical values </code></pre>
[ { "answer_id": 74518844, "author": "Wang Zerui", "author_id": 16232205, "author_profile": "https://Stackoverflow.com/users/16232205", "pm_score": 0, "selected": false, "text": "function noIdenticalConsecutives(arr) {\n let stack = new Stack();\n let repeat = [];\n let hasRepeat = false;\n\n if (arr.length === 0) return \"No values to iterate\";\n\n for (let i = 0; i < arr.length - 1; i++) {\n const curr = arr[i];\n const next = arr[i + 1];\n\n if (curr === next) hasRepeat = true;\n \n }\n if (!hasRepeat) return \"There are no identical consecutive values\";\n}\n" }, { "answer_id": 74518882, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "const stackAndRepeat = arr.reduce((accumulator, next) => {\n accumulator.stack[accumulator.stack.length - 1] === next ? accumulator.repeat.push(next) : accumulator.stack.push(next);\n\n return accumulator;\n}, { stack: [], repeat: [] });\n" }, { "answer_id": 74518901, "author": "Sahil Verma", "author_id": 10043200, "author_profile": "https://Stackoverflow.com/users/10043200", "pm_score": 1, "selected": true, "text": "let isIdentical = false;\nfor (let i = 0; i < arr.length - 1; i++) {\nconst curr = arr[i];\nconst next = arr[i + 1];\n\nif (curr == next) { isIdentical = true; return; }\n}\nif(!isIdentical){ return \"There are no identical consecutive values\";}\n" }, { "answer_id": 74519005, "author": "Titan XP", "author_id": 19262395, "author_profile": "https://Stackoverflow.com/users/19262395", "pm_score": 1, "selected": false, "text": "function noIdenticalConsecutives(arr) {\n let stack = [];\n let repeat = [];\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i + 1] !== arr [i]) {\n stack.push(arr[i]);\n } else {\n repeat.push(arr[i]);\n };\n };\n return stack.concat(repeat);\n};\n\nconsole.log(noIdenticalConsecutives([14, 4, 10, 7, 3, 1, 1, 5, 7, 7]));\n// [14, 4, 10, 7, 3, 1, 5, 7, 1, 7]\n" }, { "answer_id": 74522270, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 0, "selected": false, "text": "[4, 4, 4, 1, 2, 8, 8] const noConsecutives = array => {\n let repeats = array.reduce((rep, now, idx, arr) => { \n // If the previous number equals the current number...\n if (arr[idx-1] === now) {\n // remove the current number...\n let match = arr.splice(idx, 1);\n // and add it to the accumulator array\n rep.push(match[0]);\n }\n // Always remember to return accumulator \n return rep;\n }, []);\n // If repeats array is empty...\n if (repeats.length < 1) {\n // return message and end function\n return \"There are no consecutive numbers\";\n }\n // If repeats array is greater or equal to the input array...\n if (repeats.length >= array.length) {\n // return input array\n return \"Too many consecutive numbers\";\n }\n // Merge the input array with repeats array\n let result = [...array, ...repeats]\n // While there is any consecutive numbers in result array...\n while (result.some((num, idx, arr) => arr[idx-1] === num && idx !== 0)) {\n // recursively call noConsecutives() passing result array\n result = noConsecutives(result);\n }\n return result;\n}\n\nconsole.log(JSON.stringify(noConsecutives([0, 1, 5, 1, 5, 5, 5, 6, 0, 9, 2, 0, 0, 7])));\nconsole.log(noConsecutives([4, 4, 4, 4]));\nconsole.log(noConsecutives([1, 2, 3, 4, 1, 2, 3, 4]));" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19129662/" ]
74,518,680
<p>This is related to STM32 pre-HAL &quot;Standard Peripheral Library&quot;...</p> <p>Why use tmpreg in the following code (taken from ADC functions)?</p> <p>`</p> <pre><code>/* Get the old register value */ tmpreg = ADCx-&gt;CR1; /* Clear the Analog watchdog channel select bits */ tmpreg &amp;= CR1_AWDCH_RESET; /* Set the Analog watchdog channel */ tmpreg |= ADC_Channel; /* Store the new register value */ ADCx-&gt;CR1 = tmpreg; </code></pre> <p>`</p> <p>Why not just do this? What are the benefits / drawbacks of each?</p> <pre><code>/* Clear the Analog watchdog channel select bits */ ADCx-&gt;CR1 &amp;= CR1_AWDCH_RESET; /* Set the Analog watchdog channel */ ADCx-&gt;CR1 |= ADC_Channel; </code></pre> <p>Thanks.</p> <p>Using SPL as a reference for developing own drivers.</p>
[ { "answer_id": 74534220, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 3, "selected": true, "text": "volatile tmpreg" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562604/" ]
74,518,693
<p>i need to give two class Name when i give</p> <pre><code> &lt;p className={Styles.headerbtn, Styles.headerbtnchat} disableElevation &gt; &lt;img src=&quot;/assets/images/Chat_Bubble.png&quot; alt=&quot;&quot; /&gt; &lt;span className={Styles.headerbtntxt}&gt;Chat us&lt;/span&gt; &lt;/p&gt; </code></pre> <p>like this it shows some error.</p> <p>Im trying to multiple classname</p>
[ { "answer_id": 74518726, "author": "Evgeny", "author_id": 7309962, "author_profile": "https://Stackoverflow.com/users/7309962", "pm_score": 1, "selected": false, "text": "className className={`${Styles.headerbtn} ${Styles.headerbtnchat}`} className={`another_class ${Styles.headerbtn} ${Styles.headerbtnchat}`}" }, { "answer_id": 74518740, "author": "theemee", "author_id": 14299113, "author_profile": "https://Stackoverflow.com/users/14299113", "pm_score": 0, "selected": false, "text": "className={`${Styles.headerbtn} ${Styles.headerbtnchat}`}\n" }, { "answer_id": 74518773, "author": "Priyen Mehta", "author_id": 19431815, "author_profile": "https://Stackoverflow.com/users/19431815", "pm_score": 1, "selected": false, "text": " <p\n className={classNames(classes.headerbtn, classes.headerbtnchat)}\n disableElevation\n >\n <img src=\"/assets/images/Chat_Bubble.png\" alt=\"\" />\n <span className={Styles.headerbtntxt}>Chat us</span>\n </p>\n" }, { "answer_id": 74518797, "author": "Noman Zahid", "author_id": 14922464, "author_profile": "https://Stackoverflow.com/users/14922464", "pm_score": 1, "selected": false, "text": " <p className={Styles.headerbtn + ' ' + Styles.headerbtnchat}\n disableElevation>\n <img src=\"/assets/images/Chat_Bubble.png\" alt=\"\" />\n <span className={Styles.headerbtntxt}>Chat us</span>\n </p>\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20376356/" ]
74,518,702
<p>I need to access an ID to an adam file setup like this:</p> <p><a href="https://i.stack.imgur.com/19noz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/19noz.png" alt="2sxc adam" /></a></p> <p>MyDocument is the field name, where users can load an image or whatever. In a list style view, users will click a link that activates a detail view for that image.</p> <p>The link will be something like mysite.com/mytab/detailsforfile/fileId</p> <p>The details view will parse the fileId and load the image.</p> <p>So, two questions:</p> <ol> <li>How can I access an ID for that adam file that later allows me to load that file based on that id?</li> <li>How can I access the URL of the file based on the ID created?</li> </ol> <p>Is the native DNN file: 123 the only way? Or does 2sxc or adam have some specific ids?</p> <p>Edit: A practical example would probably help:</p> <p>This list view will have:</p> <pre><code>@foreach(var car in eCars) { &lt;div&gt; &lt;strong&gt;@car.Name&lt;/strong&gt; &lt;img class=&quot;img-fluid&quot; src=&quot;@car.carImageOne&quot;&gt; &lt;a href=&quot;@(&quot;/whatever/&quot; + IDFORTHISIMAGE)&quot;&gt;See full image...&lt;/a&gt; &lt;img class=&quot;img-fluid&quot; src=&quot;@car.carImageTwo&quot;&gt; &lt;a href=&quot;@(&quot;/whatever/&quot; + IDFORTHISIMAGE)&quot;&gt;See full image...&lt;/a&gt; &lt;/div&gt; } </code></pre> <p>And the details view:</p> <pre><code>@{ var qsImageId = Request.QueryString[&quot;whatever&quot;]; //cast and double check the qs int var imageURL = ??; // How do I get the file url based on the id? } &lt;div&gt; //embed nice frame, ads, whatever &lt;img class=&quot;img-fluid&quot; src=&quot;@imageURL&quot;&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74537670, "author": "iJungleBoy", "author_id": 5044294, "author_profile": "https://Stackoverflow.com/users/5044294", "pm_score": 1, "selected": false, "text": "convertLinks: false" }, { "answer_id": 74594173, "author": "João Gomes", "author_id": 8507593, "author_profile": "https://Stackoverflow.com/users/8507593", "pm_score": 0, "selected": false, "text": "var getFile = AsAdam(Entity, \"field\").Files as System.Collections.Generic.IEnumerable<dynamic>;\nget fileId = getFile.First().FileId;\n var myFile = FileManager.Instance.GetFile(FileId);\nvar myurl = FileManager.Instance.GetUrl(myFile);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507593/" ]
74,518,738
<p>I have some example data that shows some data related to docs (<code>docs.id</code>) and the people which it refers to (<code>details.id</code>) :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const docs = [ { id: "89", state: "accepted", details: [ { id: 20656, type: "Claimant", name: "First Name Last Name", first_name: "First Name", last_name: "Last Name", type_label: "claimant" } ] }, { id: "45", state: "accepted", details: [ { id: 20656, type: "Claimant", name: "First Name Last Name", first_name: "First Name", last_name: "Last Name", type_label: "claimant" }, { id: 20657, type: "Fellow", name: "Fellow First Name Fellow Last Name", first_name: "Fellow First Name", last_name: "Fellow Last Name", type_label: "fellow" } ] }, { id: "47", state: "rejected", details: [ { id: 20656, type: "Claimant", name: "First Name Last Name", first_name: "First Name", last_name: "Last Name", type_label: "claimant" } ] } ] const groups = docs.reduce((groups, item) =&gt; { const group = groups[item.details] || []; group.push(item); groups[item.details] = group; return groups; }, {}); console.log("groups: ", groups);</code></pre> </div> </div> </p> <p>I'm trying to manipulate this array so that I could group per person (<code>details.id</code>) all her related docs (<code>docs.id</code>) so that I can later on use the results in react app but it's not working like that.</p> <p><em>EDIT (adding expected result):</em></p> <pre><code> const new = [ { id: 20656, type: &quot;Claimant&quot;, name: &quot;First Name Last Name&quot;, docs: [89,45,47] }, { id: 20656, type: &quot;Fellow&quot;, name: &quot;Fellow First Name Fellow Last Name&quot;, docs: [47] } ] </code></pre>
[ { "answer_id": 74537670, "author": "iJungleBoy", "author_id": 5044294, "author_profile": "https://Stackoverflow.com/users/5044294", "pm_score": 1, "selected": false, "text": "convertLinks: false" }, { "answer_id": 74594173, "author": "João Gomes", "author_id": 8507593, "author_profile": "https://Stackoverflow.com/users/8507593", "pm_score": 0, "selected": false, "text": "var getFile = AsAdam(Entity, \"field\").Files as System.Collections.Generic.IEnumerable<dynamic>;\nget fileId = getFile.First().FileId;\n var myFile = FileManager.Instance.GetFile(FileId);\nvar myurl = FileManager.Instance.GetUrl(myFile);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11886740/" ]
74,518,778
<p>I'm unable to get current user inside serializer. I have passed context but still i get error like</p> <pre><code>&quot;user&quot;: [ &quot;This field is required.&quot; ] </code></pre> <p>#Serializer.py</p> <pre><code>class AddressSerializer(ModelSerializer): class Meta: model = Address fields = &quot;__all__&quot; def create(self, validated_data): request = self.context[&quot;request&quot;] validated_data[&quot;user&quot;] = request.user return super().create(validated_data) </code></pre> <p>#Views.py</p> <pre><code>class AddAddress(APIView): permission_classes = [IsAuthenticated] def post(self, request): print(request.user) serializer = AddressSerializer(data=request.data, context={&quot;request&quot;:request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, 200) return Response(serializer.errors) </code></pre> <p>#Models.py</p> <pre><code>class Address(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) full_name = models.CharField(max_length=35) email = models.EmailField(max_length=100) phone = models.BigIntegerField() address_line_1 = models.TextField(max_length=500) address_line_2 = models.TextField(max_length=500) zip_code = models.IntegerField() city = models.CharField(max_length=20) state = models.CharField(max_length=15) country = models.CharField(max_length=15) class Meta: verbose_name_plural = &quot;Address&quot; def __str__(self): return self.full_name </code></pre> <p>I exactly don't know the problem behind this</p>
[ { "answer_id": 74537670, "author": "iJungleBoy", "author_id": 5044294, "author_profile": "https://Stackoverflow.com/users/5044294", "pm_score": 1, "selected": false, "text": "convertLinks: false" }, { "answer_id": 74594173, "author": "João Gomes", "author_id": 8507593, "author_profile": "https://Stackoverflow.com/users/8507593", "pm_score": 0, "selected": false, "text": "var getFile = AsAdam(Entity, \"field\").Files as System.Collections.Generic.IEnumerable<dynamic>;\nget fileId = getFile.First().FileId;\n var myFile = FileManager.Instance.GetFile(FileId);\nvar myurl = FileManager.Instance.GetUrl(myFile);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16853253/" ]
74,518,826
<pre><code>DATA = data.frame(STUDENT = c(1,1,1,1,1,2,2,2,2,3,3,3), YEAR = c(2000,2000,2001,2001,2002,2000,2001,2001,2002,2000,2001,2001), SEMESTER = c(1,2,1,2,1,2,1,2,1,1,2,1), SCORE = c(7,4,5,6,8,9,1,1,1,2,3,4), WANT= c(NA, NA, 1, NA, 1, NA, 0, NA, 2, NA, 1, NA), WANT2=c(NA, NA, 1, NA, 2, NA, -8, NA, 0, NA, 1, NA)) </code></pre> <p>I have 'DATA' and wish to create the 'WANT' variable which does this:</p> <pre><code>if SCORE from SEMESTER = 1 and YEAR = N &gt; SCORE from SEMESTER = 2 and YEAR = N-1, 1 if SCORE from SEMESTER = 1 and YEAR = N &lt; SCORE from SEMESTER = 2 and YEAR = N-1, 2 if SCORE from SEMESTER = 1 and YEAR = N = SCORE from SEMESTER = 2 and YEAR = N-1, 0 </code></pre>
[ { "answer_id": 74519180, "author": "Andy Baxter", "author_id": 10744082, "author_profile": "https://Stackoverflow.com/users/10744082", "pm_score": 2, "selected": false, "text": "library(tidyverse)\n\nDATA = data.frame(STUDENT = c(1,1,1,1,1,2,2,2,2,3,3,3),\n YEAR = c(2000,2000,2001,2001,2002,2000,2001,2001,2002,2000,2001,2001),\n SEMESTER = c(1,2,1,2,1,2,1,2,1,1,2,1),\n SCORE = c(7,4,5,6,8,9,1,1,1,2,3,4),\n WANT= c(NA, NA, 1, NA, 1, NA, 0, NA, 2, NA, 1, NA))\n\nDATA |> \n # These lines fill in 'missing' semesters\n complete(STUDENT, YEAR, SEMESTER) |> \n arrange(STUDENT, YEAR, SEMESTER) |> \n group_by(STUDENT) |> \n # These lines check 'last score' for each student\n mutate(WANT = case_when(\n SEMESTER == 2 ~ NA,\n SCORE > lag(SCORE) ~ 1,\n SCORE < lag(SCORE) ~ 2,\n SCORE == lag(SCORE) ~ 0\n )\n) |> \n # These lines re-shorten code to only those containing scores\n filter(!is.na(SCORE))\n#> # A tibble: 12 × 5\n#> # Groups: STUDENT [3]\n#> STUDENT YEAR SEMESTER SCORE WANT\n#> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 2000 1 7 NA\n#> 2 1 2000 2 4 NA\n#> 3 1 2001 1 5 1\n#> 4 1 2001 2 6 NA\n#> 5 1 2002 1 8 1\n#> 6 2 2000 2 9 NA\n#> 7 2 2001 1 1 2\n#> 8 2 2001 2 1 NA\n#> 9 2 2002 1 1 0\n#> 10 3 2000 1 2 NA\n#> 11 3 2001 1 4 NA\n#> 12 3 2001 2 3 NA\n" }, { "answer_id": 74519191, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": false, "text": "dplyr case_when DATA %>%\n group_by(STUDENT) %>%\n arrange(YEAR, SEMESTER) %>%\n mutate(WANT = case_when(SEMESTER == 1 & lag(SEMESTER) == 2 & YEAR == lag(YEAR) + 1 & SCORE > lag(SCORE) ~ 1,\n SEMESTER == 1 & lag(SEMESTER) == 2 & YEAR == lag(YEAR) + 1 & SCORE < lag(SCORE) ~ 2,\n SEMESTER == 1 & lag(SEMESTER) == 2 & YEAR == lag(YEAR) + 1 & SCORE == lag(SCORE) ~ 0)) %>%\n arrange(STUDENT)\n STUDENT YEAR SEMESTER SCORE WANT\n <dbl> <dbl> <dbl> <dbl> <dbl>\n 1 1 2000 1 7 NA\n 2 1 2000 2 4 NA\n 3 1 2001 1 5 1\n 4 1 2001 2 6 NA\n 5 1 2002 1 8 1\n 6 2 2000 2 9 NA\n 7 2 2001 1 1 2\n 8 2 2001 2 1 NA\n 9 2 2002 1 1 0\n10 3 2000 1 2 NA\n11 3 2001 1 4 NA\n12 3 2001 2 3 NA\n" }, { "answer_id": 74519423, "author": "Stefano Barbi", "author_id": 3207509, "author_profile": "https://Stackoverflow.com/users/3207509", "pm_score": 0, "selected": false, "text": "pivot_wider DATA |>\n select(STUDENT, YEAR, SEMESTER, SCORE) |>\n pivot_wider(names_from = SEMESTER, values_from = SCORE) |>\n complete(YEAR) |>\n arrange(YEAR) |>\n group_by(STUDENT) |>\n mutate(CHANGE = case_when(`1` > lag(`2`,1) ~ 1,\n `1` < lag(`2`,1) ~ 2,\n `1` == lag(`2`,1) ~ 0,\n TRUE ~ NA_real_)) |>\n ungroup() |>\n arrange(STUDENT, YEAR)\n\n\n##> + # A tibble: 8 × 5\n##> YEAR STUDENT `1` `2` CHANGE\n##> <dbl> <dbl> <dbl> <dbl> <dbl>\n##> 1 2000 1 7 4 NA\n##> 2 2001 1 5 6 1\n##> 3 2002 1 8 NA 1\n##> 4 2000 2 NA 9 NA\n##> 5 2001 2 1 1 2\n##> 6 2002 2 1 NA 0\n##> 7 2000 3 2 NA NA\n##> 8 2001 3 4 3 NA\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619171/" ]
74,518,836
<p><img src="https://i.imgur.com/LYOTjcv.jpg" alt="Text" /></p> <p>I am using Blazor.</p> <p>I am trying to get a specific result from dbset.</p> <p>I have two conditions, salary is 620 and deduction is for p2.</p> <p>The difficult thing is range, btw 600~700 for salary. Then how I move to specific column to get the result for p2.</p> <p>var result = await _db.TaxTable.......blah...blah...</p> <p>In this case, I have to find the result <b>70</b></p> <p>I have tried some code..but I failed everytime.</p> <p>Could you share the exact knowledge?</p> <p>Thank you in adv.</p>
[ { "answer_id": 74520145, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 2, "selected": true, "text": "using var dbContext = _factory.CreateDbContext();\ndbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;\n\nvar value = await dbContext.Set<TRecord>()\n .SingleOrDefault(item => item.start <= this.salary && item.end >= this.salary)?.p2 ?? 0;\n @page \"/\"\n\n<PageTitle>Index</PageTitle>\n\n<input class=\"form-control\" @bind-value=this.salary />\n\n<div class=\"text-end m-2\">\n <button class=\"btn btn-primary\" @onclick=Calc>Calculate</button>\n <button class=\"btn btn-secondary\" @onclick=Calc2>Calculate 2</button>\n</div>\n\n<div class=\"bg-dark text-white m-2 p-2\">\n P2 = @P2\n</div>\n\n@code {\n private int salary;\n private int P2;\n\n private void Calc()\n {\n var record = deductions.SingleOrDefault(item => item.start <= this.salary && item.end >= this.salary);\n P2 = record?.p2 ?? 0;\n }\n\n private void Calc2()\n {\n P2 = deductions.SingleOrDefault(item => item.start <= this.salary && item.end >= this.salary)?.p2 ?? 0;\n }\n\n\n private List<Deduction> deductions = new List<Deduction>\n {\n new Deduction(1,0,199,10,20,30), \n new Deduction(2,200,299,20,30,40),\n new Deduction(3,300,399,30,40,50),\n new Deduction(4,400,499,40,50,60),\n };\n\n public record Deduction(int Id, int start, int end, int p1, int p2, int p3 );\n}\n" }, { "answer_id": 74522928, "author": "Brian Parker", "author_id": 1492496, "author_profile": "https://Stackoverflow.com/users/1492496", "pm_score": 2, "selected": false, "text": "double GetDeduction(double salary, string discount)\n{\n var row = someData.SingleOrDefault(a => salary >= a.start && salary < a.end);\n\n if(row == null) throw new SomeRowNotFoundException();\n\n return discount switch \n {\n \"p1\" => row.p1,\n \"p2\" => row.p2,\n \"p3\" => row.p3,\n _ => throw new SomeDiscountNotValidException();\n }\n}\n someData.SingleOrDefault(a => salary > a.start && salary <= a.end)" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2136407/" ]
74,518,856
<p>I currently learn C, in the kr book there is one paragraph that confuses me:</p> <p><em>&quot;Q Rather more surprising, at least at first sight, is the fact that a reference to a[i] can also be written as <code>*(a+i)</code>. In evaluating <code>a[i]</code>, C converts it to <code>*(a+i)</code> immediately; the two forms are equivalent. Applying the operator <code>&amp;</code> to both parts of this equivalence, it follows that <code>&amp;a[i]</code> and <code>a+i</code> are also identical: <code>a+i</code> is the address of the <code>i</code>-th element beyond <code>a</code>. As the other side of this coin, if <code>pa</code> is a pointer, expressions may use it with a subscript; <code>pa[i]</code> is identical to <code>*(pa+i)</code>. In short, an array-and-index expression is equivalent to one written as a pointer and offset.&quot;</em></p> <p>Taken literally it means that <code>&amp;a[i]</code> is equal to <code>&amp;(*(a+i))</code>, and also <code>&amp;(*(a+i))=a+i</code>. But <code>*x</code> is the VALUE of <code>x</code> and can, for example, be negative, so <code>&amp;</code> should not apply to it. I understand that <code>a+i</code> is <code>a[i]</code> but it was explained in the book right before the paragraph I cited so I don't get what is this paragraph for or what's even written in it.</p> <p>While I am at it, am I right in thinking that for say 3 adjacent objects of some type(whether they officially make up an array or not) if the pointer x of the same type points to the first of them the address it contains is the address of the first byte of first object and <code>x+1</code> is not <code>x+1</code> in bytes, but <code>x+1*sizeof(the type in question)</code>?</p>
[ { "answer_id": 74519292, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 0, "selected": false, "text": "*x x *x x x int y y int y; y y = y+1 y y y+1 y y = y y y = y+1 sizeof & ++ -- . y = y+1 y y y *x x *x *x = *x+1 *x *x *x &*x & &*x *x *x & x+1 x+1 x+1*sizeof(the type in question) x x+1 sizeof *x x char (char *) x (char *) x + sizeof *x *x x+1 (char *) x + sizeof *x char * (char *) (x+1) == (char *) x + sizeof *x" }, { "answer_id": 74519350, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "&* * variable &*variable variable &*(a+i) a+i a[i] *(a+i) *((a)+(i)) a[i & mask] *(a + i & mask) *((a) + (i & mask)) x" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562428/" ]
74,518,889
<p>I already have a list adapter that works properly. But I want to divide the object in the list into sections according to the date they were created. Something like this:</p> <p><a href="https://i.stack.imgur.com/8IBZx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8IBZx.png" alt="enter image description here" /></a></p> <p>I found something called &quot;sectioned recycler view&quot; but couldn't find any documentation on that. I read all the related questions, but they all are either outdated or use a third-party library. What's the native way of implementing this feature?</p>
[ { "answer_id": 74522121, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 3, "selected": true, "text": "GONE onBindViewHolder VISIBLE GONE val visible = position == 0 || items[position].date != items[position - 1].date\n Item Header sealed class ListElement {\n data class Header(val date: Date) : ListElement()\n data class Item(val itemData: YourItem) : ListElement()\n} \n Item List<ListElement> Header Item ViewHolder is Header is Item groupBy Map Header, Item, Item... items.map { Item(it) }\n .groupBy { it.itemData.date }\n .entries\n .flatMap { (date, items) -> listOf(Header(date)) + items }\n Header val list = mutableListOf<ListElement>().apply {\n for (item in items) {\n // add a header if the date changed - this handles the first header\n // in an empty list too (where lastOrNull returns null, so the date is null)\n val previousItemDate = (lastOrNull() as? Item)?.itemData?.date\n if (previousItemDate != item.date) add(Header(item.date))\n add(Item(item))\n }\n}\n fold" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12431078/" ]
74,518,892
<p>After login is successful it stays on the login page with the user's info still in inputs, as I want it to redirect to previous location or home.. I don't know if I used useSearchParams the right way and if i should include them in the useEffect. &quot;After login is successful it stays on the login page with the user's info still in inputs, as I want it to redirect to previous location or home.. I don't know if I used useSearchParams the right way and if i should include them in the useEffect&quot; &lt; jut to post the question</p> <p>LoginScreen.js:</p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import { Link } from &quot;react-router-dom&quot;; import { useDispatch, useSelector } from &quot;react-redux&quot;; import { Row, Col, Button, Form } from &quot;react-bootstrap&quot;; //import products from &quot;../../products&quot;; import Message from &quot;../Message&quot;; import Loader from &quot;../Loader&quot;; import { useNavigate, useLocation, useSearchParams } from &quot;react-router-dom&quot;; import { login } from &quot;../../actions/UserActions&quot;; import LoginForm from &quot;../LoginForm&quot;; function LoginScreen() { const [searchParams, setSearchParams] = useSearchParams(); const { search } = useLocation(); const navigate = useNavigate(); const [email, setEmail] = useState(&quot;&quot;); const [password, setPassword] = useState(&quot;&quot;); const dispatch = useDispatch(); const redirect = searchParams.get(search.split(&quot;=&quot;)) || 1; const userLogin = useSelector((state) =&gt; state.userLogin); const { error, loading, userInfo } = userLogin; useEffect(() =&gt; { if (userInfo) { navigate(redirect); //searchParams.delete(&quot;userInfo&quot;); setSearchParams(searchParams); } }, [navigate, userInfo, redirect, searchParams, setSearchParams]); const submitHandler = (e) =&gt; { e.preventDefault(); dispatch(login(email, password)); }; </code></pre> <p>App.js:</p> <pre><code> &lt;Container&gt; &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;HomeScreen /&gt;} /&gt; &lt;Route path=&quot;/login&quot; element={&lt;LoginScreen /&gt;} /&gt; &lt;Route path=&quot;/register&quot; element={&lt;RegisterScreen /&gt;} /&gt; &lt;Route path=&quot;/product/:id&quot; element={&lt;ProductScreen /&gt;} /&gt; &lt;Route path=&quot;/cart&quot;&gt; &lt;Route path=&quot;:productid&quot; element={&lt;CartScreen /&gt;} /&gt; &lt;Route index element={&lt;CartScreen /&gt;} /&gt; &lt;/Route&gt; &lt;/Routes&gt; &lt;/Container&gt; </code></pre> <p>package.json:</p> <pre><code>{ &quot;name&quot;: &quot;efrontend&quot;, &quot;proxy&quot;: &quot;http://127.0.0.1:8000/&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@reduxjs/toolkit&quot;: &quot;^1.9.0&quot;, &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;, &quot;@testing-library/react&quot;: &quot;^13.4.0&quot;, &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;, &quot;axios&quot;: &quot;^1.1.3&quot;, &quot;bootstrap&quot;: &quot;^5.2.2&quot;, &quot;react&quot;: &quot;^18.2.0&quot;, &quot;react-bootstrap&quot;: &quot;^2.6.0&quot;, &quot;react-dom&quot;: &quot;^18.2.0&quot;, &quot;react-redux&quot;: &quot;^8.0.5&quot;, &quot;react-router-bootstrap&quot;: &quot;^0.26.2&quot;, &quot;react-router-dom&quot;: &quot;^6.4.3&quot;, &quot;react-scripts&quot;: &quot;5.0.1&quot;, &quot;redux-devtools-extension&quot;: &quot;^2.13.9&quot;, &quot;redux-thunk&quot;: &quot;^2.4.2&quot;, &quot;web-vitals&quot;: &quot;^2.1.4&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] }, &quot;devDependencies&quot;: { &quot;@types/bootstrap&quot;: &quot;^5.2.6&quot;, &quot;@types/react-bootstrap&quot;: &quot;^0.32.31&quot; } } </code></pre>
[ { "answer_id": 74522121, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 3, "selected": true, "text": "GONE onBindViewHolder VISIBLE GONE val visible = position == 0 || items[position].date != items[position - 1].date\n Item Header sealed class ListElement {\n data class Header(val date: Date) : ListElement()\n data class Item(val itemData: YourItem) : ListElement()\n} \n Item List<ListElement> Header Item ViewHolder is Header is Item groupBy Map Header, Item, Item... items.map { Item(it) }\n .groupBy { it.itemData.date }\n .entries\n .flatMap { (date, items) -> listOf(Header(date)) + items }\n Header val list = mutableListOf<ListElement>().apply {\n for (item in items) {\n // add a header if the date changed - this handles the first header\n // in an empty list too (where lastOrNull returns null, so the date is null)\n val previousItemDate = (lastOrNull() as? Item)?.itemData?.date\n if (previousItemDate != item.date) add(Header(item.date))\n add(Item(item))\n }\n}\n fold" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19778871/" ]
74,518,902
<p>I have created an app for my company. To use the application, you need to log in to the account that We ourselves create for each specific employee, registration of new accounts in the application is not available now and will not be available in the future, since only We can create new accounts for new employees and delete old accounts on our server . Can such an application be published in the App Store, given the new requirements of Apple? Is there any way to avoid this? Maybe if our application is unlisted, then it will be allowed to be published without explicitly registering new accounts?</p> <p>We tried to submit our app for review and provided a demo account, but we were denied publishing due to implicit registration in the app.</p>
[ { "answer_id": 74522121, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 3, "selected": true, "text": "GONE onBindViewHolder VISIBLE GONE val visible = position == 0 || items[position].date != items[position - 1].date\n Item Header sealed class ListElement {\n data class Header(val date: Date) : ListElement()\n data class Item(val itemData: YourItem) : ListElement()\n} \n Item List<ListElement> Header Item ViewHolder is Header is Item groupBy Map Header, Item, Item... items.map { Item(it) }\n .groupBy { it.itemData.date }\n .entries\n .flatMap { (date, items) -> listOf(Header(date)) + items }\n Header val list = mutableListOf<ListElement>().apply {\n for (item in items) {\n // add a header if the date changed - this handles the first header\n // in an empty list too (where lastOrNull returns null, so the date is null)\n val previousItemDate = (lastOrNull() as? Item)?.itemData?.date\n if (previousItemDate != item.date) add(Header(item.date))\n add(Item(item))\n }\n}\n fold" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19061392/" ]
74,518,903
<p>Im supposed to write a method divideByTwo that takes an integer as a parameter and returns the number divided by 2. and i need to try to solve the problem with a single program statement in the method. I don't know how to fix the problem, i've used modulo, while loop, changed the return value but still don't know what i am doing wrong. Any kind of help appreciated!</p> <p>this is what i've done so far:</p> <pre><code>public static int divideByTwo(int a){ int i = 0; while(i &lt; 1){ System.out.print(a/2); i++; } return a; } </code></pre> <p><a href="https://i.stack.imgur.com/1yRuF.png" rel="nofollow noreferrer">expected output</a></p>
[ { "answer_id": 74522121, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 3, "selected": true, "text": "GONE onBindViewHolder VISIBLE GONE val visible = position == 0 || items[position].date != items[position - 1].date\n Item Header sealed class ListElement {\n data class Header(val date: Date) : ListElement()\n data class Item(val itemData: YourItem) : ListElement()\n} \n Item List<ListElement> Header Item ViewHolder is Header is Item groupBy Map Header, Item, Item... items.map { Item(it) }\n .groupBy { it.itemData.date }\n .entries\n .flatMap { (date, items) -> listOf(Header(date)) + items }\n Header val list = mutableListOf<ListElement>().apply {\n for (item in items) {\n // add a header if the date changed - this handles the first header\n // in an empty list too (where lastOrNull returns null, so the date is null)\n val previousItemDate = (lastOrNull() as? Item)?.itemData?.date\n if (previousItemDate != item.date) add(Header(item.date))\n add(Item(item))\n }\n}\n fold" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20035146/" ]
74,518,908
<p>I have the following array of objects</p> <pre><code>var array = [ {first_name: 'Mike', last_name: 'Kelly'}, {first_name: 'Charles', last_name: 'Bronson'}, {first_name: 'Chuck', last_name: 'Norris'}, ]; </code></pre> <p>I wanted to replace underscore with space and capitalize first word of each key as follows</p> <pre><code>var array = [ {&quot;First Name&quot;: 'Mike', &quot;Last Name&quot;: 'Kelly'}, {&quot;First Name&quot;: 'Charles', &quot;Last Name&quot;: 'Bronson'}, {&quot;First Name&quot;: 'Chuck', &quot;Last Name&quot;: 'Norris'}, ]; </code></pre> <p>I managed to remove underscore with the following code from <a href="https://stackoverflow.com/a/44704817/12499550">this</a> but I can't capitalize first letter of each keys.</p> <pre><code>function convert(obj) { const result = {}; Object.keys(obj).forEach(function (key) { result[key.replace(/_/g, ' ')] = obj[key]; }); return result; } var result = array.map(function (o) { return convert(o); }); </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74522121, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 3, "selected": true, "text": "GONE onBindViewHolder VISIBLE GONE val visible = position == 0 || items[position].date != items[position - 1].date\n Item Header sealed class ListElement {\n data class Header(val date: Date) : ListElement()\n data class Item(val itemData: YourItem) : ListElement()\n} \n Item List<ListElement> Header Item ViewHolder is Header is Item groupBy Map Header, Item, Item... items.map { Item(it) }\n .groupBy { it.itemData.date }\n .entries\n .flatMap { (date, items) -> listOf(Header(date)) + items }\n Header val list = mutableListOf<ListElement>().apply {\n for (item in items) {\n // add a header if the date changed - this handles the first header\n // in an empty list too (where lastOrNull returns null, so the date is null)\n val previousItemDate = (lastOrNull() as? Item)?.itemData?.date\n if (previousItemDate != item.date) add(Header(item.date))\n add(Item(item))\n }\n}\n fold" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12499550/" ]
74,518,909
<p>I have a 2d array with shape(3,6), then i want to create a condition to check a value of each array. my data arry is as follows :</p> <blockquote> <p>array([[ 1, 2, 3, 4, 5, 6], 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]])</p> </blockquote> <p>if in an array there are numbers &lt; 10 then the value will be 0</p> <p>the result I expected</p> <blockquote> <p>array([[ 0, 0, 0, 0, 0, 0], 0, 0, 0, 10, 11, 12], [13, 14, 15, 16, 17, 18]])</p> </blockquote> <p>the code i created is like this, but why can't it work as i expected</p> <pre><code>FCDataNew = [] a = [ [1,2,3,4,5,6], [7,8,9,10,11,12], [13,14,15,16,17,18] ] a = np.array(a) c = 0 c = np.array(c) for i in range(len(a)): if a[i].all()&lt;10: FCDataNew.append(c) else: FCDataNew.append(a[i]) FCDataNew = np.array(FCDataNew) FCDataNew </code></pre>
[ { "answer_id": 74518930, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 3, "selected": true, "text": "FCDataNew = np.array([[1,2,3,4,5,6],\n [7,8,9,10,11,12],\n [13,14,15,16,17,18],\n ])\n\nFCDataNew[FCDataNew<10] = 0\n out = np.where(FCDataNew<10, 0, FCDataNew)\n array([[ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 10, 11, 12],\n [13, 14, 15, 16, 17, 18]])\n" }, { "answer_id": 74518971, "author": "uozcan12", "author_id": 5226470, "author_profile": "https://Stackoverflow.com/users/5226470", "pm_score": 0, "selected": false, "text": "arr[arr < 10] = 0" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562723/" ]
74,518,929
<p>Can I simplify this code without foreach?</p> <pre><code>$userQuestIds = [2,4,45,586,16,2,143,234,654,78,56]; $typeQuests = []; foreach ($userQuestIds as $qId) { $typeQuests[] = Quest::where(['id' =&gt; $qId])-&gt;first(); } </code></pre>
[ { "answer_id": 74519012, "author": "Rouhollah Mazarei", "author_id": 5876267, "author_profile": "https://Stackoverflow.com/users/5876267", "pm_score": 1, "selected": false, "text": "whereIn $typeQuests = Quest::whereIn('id', $userQuestIds)->get();\n id" }, { "answer_id": 74519140, "author": "Andriy Lozynskiy", "author_id": 5712529, "author_profile": "https://Stackoverflow.com/users/5712529", "pm_score": 2, "selected": true, "text": "id $typeQuests = Quest::find($userQuestIds);\n" }, { "answer_id": 74521661, "author": "Andrej Petrushevski", "author_id": 11977171, "author_profile": "https://Stackoverflow.com/users/11977171", "pm_score": 0, "selected": false, "text": "whereIn() QueryBuilder $userQuestIds = [2,4,45,586,16,2,143,234,654,78,56];\n$typeQuests = Quest::whereIn('id', $userQuestIds)->get();\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12213220/" ]
74,518,932
<p>Good day, I am doing Web api rest project and want to include product search for products by size and color, but I want to be able search for example: 1 One size</p> <pre><code>[httpGet][Route(&quot;oneSize/{sizeID}&quot;)] </code></pre> <p>2 Two Sizes</p> <pre><code>[httpGet][Route(&quot;TwoSizes/{sizeID1}/{sizeID2}&quot;)] </code></pre> <p>3 One size/ One color</p> <pre><code>[httpGet][Route(&quot;OneSizeOneColor/{sizeID1}/{ColorID}&quot;)] </code></pre> <p>4 Two sizes/ One color</p> <pre><code>[httpGet][Route(&quot;TwoSizeOneColor/{sizeID1}/{sizeID2}/{ColorID}&quot;)] </code></pre> <p>etc. Do I need to create end point for every tipe of search or is there a smarter way of doing it?</p>
[ { "answer_id": 74519606, "author": "theemee", "author_id": 14299113, "author_profile": "https://Stackoverflow.com/users/14299113", "pm_score": 2, "selected": true, "text": "FromQuery [HttpGet]\npublic IActionResult SearchProducts([FromQuery] int[] sizeIds, [FromQuery] int[] colorIds) {\n}\n int string https://localhost:5001/your-endpoint-name?sizeIds=1&sizeIds=2&colorIds=3&colorIds=4 key=value ? & IQuaryable<Product> query = dbContext.Products;\nif (sizeIds.Length > 0) {\n query= query.Where(p => sizeIds.Contains(p.SizeId));\n}\nif (colorIds.Length > 0) {\n query= query.Where(p => colorIds.Contains(p.ColorId));\n}\nList<Product> result = await query.ToListAsync();\n SELECT * FROM Products\nWHERE Products.SizeId IN (1, 2) AND Products.ColorId IN (3, 4);\n" }, { "answer_id": 74520259, "author": "Modestas Vacerskas", "author_id": 17250130, "author_profile": "https://Stackoverflow.com/users/17250130", "pm_score": 0, "selected": false, "text": " public class ProductBase\n{\n public int Id { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n public ICollection<ProductVariant> Variants { get; set; } = new List<ProductVariant>();\n public int BaseImageId { get; set; } = 0;\n public string BaseImagePath { get; set; } = string.Empty;\n\n}\n\n public class ProductVariant\n{\n public int Id { get; set; }\n public int Quantity { get; set; }\n public int ProductBaseId { get; set; }\n public int ProductSizeId { get; set; }\n public ProductSize ProductSize { get; set; }\n public int ProductColorId { get; set; }\n public ProductColor ProductColor { get; set; }\n\n public IEnumerable<ImageVariant> imageVariants { get; set; } = new List<ImageVariant>();\n}\npublic class ProductSize\n{\n public int Id { get; set; }\n public string Size { get; set; }\n}\npublic class ProductColor\n{\n public int Id { get; set; }\n public string Color { get; set; }\n}\n public async Task<IQueryable<Models.ProductBase>> SearchProducts(int[] SizeIds, int[] ColorIds )\n {\n IQueryable<Models.ProductBase> query = _dataContext.ProductBases\n .Include(pb => pb.Variants).ThenInclude(v => v.ProductSize)\n .Include(pb => pb.Variants).ThenInclude(v => v.ProductColor)\n .Include(pb => pb.Variants).ThenInclude(v => v.imageVariants);\n \n if(SizeIds.Length > 0)\n {\n query = query.Where(pb => SizeIds.Contains(pb.Variants.Any(pb.Variants.doesnotWork));\n }\n if(ColorIds.Length > 0)\n {\n query = query.Where(pb => ColorIds.Contains(pb.Variants.Contains(pb.Variants.doesNotWork)));\n }\n\n List<ProductBase> result = await query.ToListAsync(); \n }\n" }, { "answer_id": 74520430, "author": "Modestas Vacerskas", "author_id": 17250130, "author_profile": "https://Stackoverflow.com/users/17250130", "pm_score": 0, "selected": false, "text": " public async Task<IEnumerable<Models.ProductBase>> SearchProducts(int[] SizeIds, int[] ColorIds )\n {\n IQueryable<Models.ProductBase> query = _dataContext.ProductBases\n .Include(pb => pb.Variants).ThenInclude(v => v.ProductSize)\n .Include(pb => pb.Variants).ThenInclude(v => v.ProductColor)\n .Include(pb => pb.Variants).ThenInclude(v => v.imageVariants);\n \n if(SizeIds.Length > 0)\n {\n query = query.Where(pb => pb.Variants.ToList().Any(v => SizeIds.Contains(v.ProductSizeId)));\n }\n if(ColorIds.Length > 0)\n {\n query = query.Where(pb => pb.Variants.ToList().Any(v => ColorIds.Contains(v.ProductColorId)));\n }\n\n List<Models.ProductBase> result = await query.ToListAsync();\n\n return result;\n }\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17250130/" ]
74,518,937
<p>As we all know, we can easy to see the line of an output statement in the browser, just like follow picture</p> <p><a href="https://i.stack.imgur.com/L8dBk.png" rel="nofollow noreferrer">enter image description here</a></p> <p>but in the nodejs env, how do I know what line is 'output statement' in.</p> <hr /> <p>I have this need because I want to know better during development where the information is coming from when the program fails. Of course, I could have each output statement carry a unique character, like <code>console.log('1', '...')</code>, <code>console.log('2', '...')</code> but that feels silly and unhackable to me.</p> <p>I'll show you a simple piece of code as an illustration</p> <pre class="lang-js prettyprint-override"><code>try { throw new Error('something error') } catch (error) { console.log(error.stack) } </code></pre> <p>Run the above code I can see the output:</p> <pre><code>Error: something error at file:///c:/Users/Linhieng/Desktop/tmp/a.js:2:9 at ModuleJob.run (node:internal/modules/esm/module_job:198:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:385:24) at async loadESM (node:internal/process/esm_loader:88:5) at async handleMainPromise (node:internal/modules/run_main:61:12) </code></pre> <p>the above output tell us what line is the error in, but I want to know the line of <code>console.log</code>.</p>
[ { "answer_id": 74519057, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "console.log(error, LINE_NUMBER);\n" }, { "answer_id": 74519062, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 3, "selected": true, "text": "console.log const realLog = console.log;\nconsole.log = (...msgs) => {\n try {\n throw new Error(\"something error\");\n } catch (error) {\n const lines = error.stack.split(/(?:\\r\\n|\\r|\\n)+/);\n msgs.push(`[${lines[2].trim()}]`);\n }\n realLog(...msgs);\n};\n function example() {\n console.log(\"Hi there\");\n}\n\nexample();\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15527429/" ]
74,518,944
<p>I read multiple related threads about how to solve the same problem, but I couldn't apply the solutions to my code.</p> <p>Also, the code is supposed receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data.</p> <p>Any suggestions?</p> <pre><code> def check_alpha(m_string): list_wanted = ['!', '?', '.', ',', ' '] for letter in m_string: if not (letter in list_wanted or letter.isalpha()): return False return True and any(letter.isalpha() for letter in m_string) while True: string = input(&quot;Enter the text to be encrypted: &quot;) if check_alpha(string): break else: print(&quot;Please enter a valid text: &quot;) continue while True: # Validating input key key = input(&quot;Enter the key: &quot;) try: key = int(key) except ValueError: print(&quot;Please enter a valid key: &quot;) continue break def caesarcipher(string, key): # Caesar Cipher encrypted_string = [] new_key = key % 26 for letter in string: encrypted_string.append(getnewletter(letter, new_key)) return ''.join(encrypted_string) def getnewletter(letter, key): new_letter = ord(letter) + key return chr(new_letter) if new_letter &lt;= 122 else chr(96 + new_letter % 122) with open('Caesar.txt', 'a') as the_file: # Writing to a text file the_file.write(caesarcipher(string, key)) print(caesarcipher(string, key)) print('Your text has been encrypted via Caesar-Cipher, the result is in Caesar.txt') </code></pre>
[ { "answer_id": 74519057, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "console.log(error, LINE_NUMBER);\n" }, { "answer_id": 74519062, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 3, "selected": true, "text": "console.log const realLog = console.log;\nconsole.log = (...msgs) => {\n try {\n throw new Error(\"something error\");\n } catch (error) {\n const lines = error.stack.split(/(?:\\r\\n|\\r|\\n)+/);\n msgs.push(`[${lines[2].trim()}]`);\n }\n realLog(...msgs);\n};\n function example() {\n console.log(\"Hi there\");\n}\n\nexample();\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20111366/" ]
74,518,951
<p>I'm wanting to set a combined maximum length of 1400 for three input fields in angular, so if say that for the first field the user enters 400 characters, in the second and third fields the maxlength becomes 1000.</p> <p>I have found one answer at StackOverflow but that is for angularjs and not working even if I follow so please give me angular 9 solution trying to solve this issue for 4days now</p> <p>progress so far...</p> <p>TS file</p> <pre><code>getMaxLength(val): void{     this.remaining = this.MAX_LENGTH - (     this.summary.nativeElement.value.length +     this.insights.nativeElement.value.length +     this.recommendations.nativeElement.value.length     );     this.summaryLimit = this.MAX_LENGTH - (this.summary.nativeElement.value.length)     this.insightLimit = this.MAX_LENGTH - (this.insights.nativeElement.value.length)     this.recommLimit = this.MAX_LENGTH - (this.recommendations.nativeElement.value.length)   } </code></pre> <p>html file</p> <pre><code>&lt;form [formGroup]=&quot;wrapReportForm&quot; class=&quot;wrap_form&quot;&gt; &lt;div class=&quot;wrap_input&quot;&gt; &lt;span&gt;{{remaining}}&lt;/span&gt; &lt;label class=&quot;label-required&quot; for=&quot;summary&quot; &gt;Summary &lt;/label &gt; &lt;textarea formControlName=&quot;summary&quot; #summary type=&quot;text&quot; maxlength=&quot;{{summaryLimit}}&quot; (ngChange)=&quot;getMaxLength($event)&quot; name=&quot;summary&quot; placeholder=&quot;Enter some input&quot; wrap=&quot;soft&quot; &gt;&lt;/textarea&gt; &lt;!-- (keydown)=&quot;getMaxLength($event, summary.value?.lead)&quot; --&gt; &lt;!-- &lt;span&gt;{{ summary.value?.length || 0 }}/{{maxLength1}}&lt;/span&gt; --&gt; &lt;/div&gt; &lt;div class=&quot;wrap_input&quot;&gt; &lt;label class=&quot;label-required&quot;&gt;Insights &lt;/label&gt; &lt;textarea formControlName=&quot;insights&quot; type=&quot;text&quot; name=&quot;insights&quot; #insights maxlength=&quot;{{insightLimit}}&quot; (ngModelChange)=&quot;getMaxLength($event)&quot; placeholder=&quot;Enter some input&quot; &gt;&lt;/textarea&gt; &lt;!-- &lt;span&gt;{{ insights.value?.length || 0 }}/{{maxLength2}}&lt;/span&gt; --&gt; &lt;/div&gt; &lt;div class=&quot;wrap_input&quot;&gt; &lt;label class=&quot;label-required&quot;&gt;Recommendations &lt;/label&gt; &lt;textarea formControlName=&quot;recommendations&quot; type=&quot;text&quot; name=&quot;recommendations&quot; #recommendations maxlength=&quot;{{recommLimit}}&quot; (ngModelChange)=&quot;getMaxLength($event)&quot; placeholder=&quot;Enter some input&quot; &gt;&lt;/textarea&gt; &lt;!-- (keydown)=&quot;getMaxLength($event, recommendations.value?.length)&quot; --&gt; &lt;!-- &lt;span&gt;{{ recommendations.value?.length || 0 }}/{{maxLength3}}&lt;/span&gt; --&gt; &lt;/div&gt; &lt;div class=&quot;wrapReport_buttons&quot;&gt; &lt;button class=&quot;margin-right-sm outline&quot; mat-dialog-close &gt;Cancel&lt;/button&gt; &lt;button class=&quot;fill&quot; (click)=&quot;generateWrapReport(true)&quot; mat-dialog-close&gt;Send Request&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p><a href="https://i.stack.imgur.com/pAnLo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pAnLo.png" alt="" /></a></p>
[ { "answer_id": 74519057, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "console.log(error, LINE_NUMBER);\n" }, { "answer_id": 74519062, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 3, "selected": true, "text": "console.log const realLog = console.log;\nconsole.log = (...msgs) => {\n try {\n throw new Error(\"something error\");\n } catch (error) {\n const lines = error.stack.split(/(?:\\r\\n|\\r|\\n)+/);\n msgs.push(`[${lines[2].trim()}]`);\n }\n realLog(...msgs);\n};\n function example() {\n console.log(\"Hi there\");\n}\n\nexample();\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16469291/" ]
74,518,961
<p>I have this table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>employee number</th> <th>job</th> <th>year</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>paramedic</td> <td>2022</td> </tr> <tr> <td>111</td> <td>doctor</td> <td>2021</td> </tr> <tr> <td>111</td> <td>student</td> <td>2020</td> </tr> <tr> <td>222</td> <td>waiter</td> <td>2022</td> </tr> <tr> <td>222</td> <td>student</td> <td>2021</td> </tr> <tr> <td>333</td> <td>nurse</td> <td>2022</td> </tr> </tbody> </table> </div> <p>I want to add one more column that will show what will be the next job of the same employee. This is will be the result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>employee number</th> <th>job</th> <th>year</th> <th>next job</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>paramedic</td> <td>2022</td> <td>last job</td> </tr> <tr> <td>111</td> <td>doctor</td> <td>2021</td> <td>paramedic</td> </tr> <tr> <td>111</td> <td>student</td> <td>2020</td> <td>doctor</td> </tr> <tr> <td>222</td> <td>waiter</td> <td>2022</td> <td>last job</td> </tr> <tr> <td>222</td> <td>student</td> <td>2021</td> <td>waiter</td> </tr> <tr> <td>333</td> <td>nurse</td> <td>2022</td> <td>last job</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74519057, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 0, "selected": false, "text": "console.log(error, LINE_NUMBER);\n" }, { "answer_id": 74519062, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 3, "selected": true, "text": "console.log const realLog = console.log;\nconsole.log = (...msgs) => {\n try {\n throw new Error(\"something error\");\n } catch (error) {\n const lines = error.stack.split(/(?:\\r\\n|\\r|\\n)+/);\n msgs.push(`[${lines[2].trim()}]`);\n }\n realLog(...msgs);\n};\n function example() {\n console.log(\"Hi there\");\n}\n\nexample();\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74518961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13942179/" ]
74,519,025
<p>I'd like to create a class with can use any Vector.</p> <p>Possible types could be std::vector, boost::vector, etl::vector.</p> <p>All used vector types must implement std::vector member functions. I'd like to create a concept which validates that the used vector type implements all std::vector member functions</p> <p>So far I have come up with</p> <pre><code>#include &lt;concepts&gt; #include &lt;vector&gt; template &lt; typename T , typename Element_T&gt; concept IVector_T = requires(T vec, Element_T elem) { {vec.push_back(elem) } -&gt; std::same_as&lt;void&gt;; ///&lt; Add an element to the vector {vec.back()} -&gt;std::convertible_to&lt;Element_T&gt;; }; template&lt;typename Element_T, IVector_T Vector_T&gt; class TestVector { public: void push_back(const Element_T&amp; elem) { myVec.push_back(elem); } Element_T&amp; back() { //return ref to last element return myVec.back(); } private: Vector_T&lt;Element_T&gt; myVec; }; </code></pre> <p>However I'm getting a compiler error</p> <pre><code>&lt;source&gt;(27): error C2059: syntax error: '&lt;' &lt;source&gt;(28): note: see reference to class template instantiation 'TestVector&lt;Element_T,Vector_T&gt;' being compiled &lt;source&gt;(27): error C2238: unexpected token(s) preceding ';' &lt;source&gt;(19): error C3861: 'myVec': identifier not found &lt;source&gt;(19): error C2065: 'myVec': undeclared identifier </code></pre> <p>I'm using latest MSVC17 on Win 10, however this should also run an Linux and Mac</p> <p>I have a godbolt link for you to easily reproduce this issue <a href="https://godbolt.org/z/54zac583j" rel="nofollow noreferrer">https://godbolt.org/z/54zac583j</a></p> <p>Thx for your help guys :)</p> <p>Edit: As noted in the comments pop_into() is not std. =&gt; replaced it with back().</p> <p>To clearify: Some vectors like boost::vector and std::vector need 1 template argument (i.e. std::vector) Other vector types like etl::vector may need more template arguments. etl::vector for example is a preallocated vector therefore we need a max vector size (i.e. etl::vector&lt;int, 100&gt;)</p>
[ { "answer_id": 74519196, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "template<typename Element_T,\n template <typename Elem> typename Vector_T>\nrequires IVector_T<Vector_T<Element_T>, Element_T>\nclass TestVector\n{\n...\n Vector_T TestVector IVector_T template <IVector_T Vector_T>" }, { "answer_id": 74519206, "author": "bitmask", "author_id": 430766, "author_profile": "https://Stackoverflow.com/users/430766", "pm_score": 2, "selected": false, "text": "template<typename Element_T, template <typename> typename Vector_T>\nrequires(IVector_T<Vector_T<Element_T>, Element_T>)\nclass TestVector { // ...\n" }, { "answer_id": 74519305, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 3, "selected": true, "text": "Vector_T template<typename Element_T, IVector_T<Element_T> Vector_T>\nclass TestVector\n{\n...\nprivate:\n Vector_T myVec;\n};\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11729602/" ]
74,519,028
<p><strong>DATA IN DATABASE</strong></p> <pre><code>&quot;data&quot;: [ { &quot;recruiter&quot;: &quot;Venkatesh&quot;, &quot;Total&quot;: [ { &quot;_id&quot;: &quot;6368de60a13476be793928bb&quot;, &quot;Status&quot;: &quot;Client Submitted&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot; }, { &quot;_id&quot;: &quot;636b71192fdb6190cd3ac4ab&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot;, &quot;Status&quot;: &quot;Hired&quot; }, { &quot;_id&quot;: &quot;636b941b2fdb6190cd3acd15&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot;, &quot;Status&quot;: &quot;Interview Scheduled&quot; }, { &quot;_id&quot;: &quot;636cd69d2fdb6190cd3b1be2&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot;, &quot;Status&quot;: &quot;Client Submitted&quot; }, { &quot;_id&quot;: &quot;6372301975e1e77a9c3b5896&quot;, &quot;Status&quot;: &quot;Client Submitted&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot; }, { &quot;_id&quot;: &quot;637761ed655965f094779322&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot;, &quot;Status&quot;: &quot;Hired&quot; }, { &quot;_id&quot;: &quot;637b04f5655965f094779d40&quot;, &quot;created_by&quot;: &quot;Venkatesh&quot;, &quot;Status&quot;: &quot;Hired&quot; } ] }, { &quot;recruiter&quot;: &quot;Sudhir&quot;, &quot;Total&quot;: [ { &quot;_id&quot;: &quot;636b73f42fdb6190cd3ac765&quot;, &quot;created_by&quot;: &quot;Sudhir&quot;, &quot;Status&quot;: &quot;Client Submitted&quot; }, { &quot;_id&quot;: &quot;6371efd059a6b9f34f910527&quot;, &quot;created_by&quot;: &quot;Sudhir&quot;, &quot;Status&quot;: &quot;Hired&quot; }, { &quot;_id&quot;: &quot;63724e7c75e1e77a9c3b5cb7&quot;, &quot;created_by&quot;: &quot;Sudhir&quot;, &quot;Status&quot;: &quot;Client Submitted&quot; }, { &quot;_id&quot;: &quot;6373210c3182820f833b41a4&quot;, &quot;created_by&quot;: &quot;Sudhir&quot;, &quot;Status&quot;: &quot;Interview Scheduled&quot; }, { &quot;_id&quot;: &quot;637332423182820f833b493b&quot;, &quot;created_by&quot;: &quot;Sudhir&quot;, &quot;Status&quot;: &quot;Client Submitted&quot; } ] }, </code></pre> <p><strong>RESPONSE I WANT</strong></p> <pre><code>[ { created_by: 'Venkatesh', Hired: 7, interviewscheduled: 7, clientsubmitted: 7 }, { created_by: 'Sudhir', Hired: 5, interviewscheduled: 5, clientsubmitted: 5 }, ] </code></pre> <p><strong>CODE</strong></p> <pre><code> for(let i=0;i&lt;=fil.length-1;i++){ let x={hired:[],is:[],cs:[]} for(let j=0;j&lt;=fil[i].Total.length-1;j++){ if(fil[i].Total[j].Status=&quot;hired&quot;){ // h.push({hired:fil[i].Total[j].Status}) x.hired.push(&quot;hired&quot;) } if(fil[i].Total[j].Status=&quot;Interview Scheduled&quot;){ // is.push({interviewscheduled:fil[i].Total[j].Status}) x.is.push(&quot;is&quot;) } if(fil[i].Total[j].Status=&quot;Client Submitted&quot;){ // cs.push({cs:fil[i].Total[j].Status}) x.cs.push(&quot;cs&quot;) } } fil_arr.push({created_by:fil[i].recruiter,Hired:x.hired.length,interviewscheduled:x.is.length,clientsubmitted:x.cs.length}) } </code></pre> <p>I want to show the total number of interviewscheduled, clientsubmitted,hired for status key based on recruiter.Iam unable to find the correct output for this.I tried using for loop but it is not giving proper output.please do help me regarding this.Thank you in advance.</p>
[ { "answer_id": 74519196, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "template<typename Element_T,\n template <typename Elem> typename Vector_T>\nrequires IVector_T<Vector_T<Element_T>, Element_T>\nclass TestVector\n{\n...\n Vector_T TestVector IVector_T template <IVector_T Vector_T>" }, { "answer_id": 74519206, "author": "bitmask", "author_id": 430766, "author_profile": "https://Stackoverflow.com/users/430766", "pm_score": 2, "selected": false, "text": "template<typename Element_T, template <typename> typename Vector_T>\nrequires(IVector_T<Vector_T<Element_T>, Element_T>)\nclass TestVector { // ...\n" }, { "answer_id": 74519305, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 3, "selected": true, "text": "Vector_T template<typename Element_T, IVector_T<Element_T> Vector_T>\nclass TestVector\n{\n...\nprivate:\n Vector_T myVec;\n};\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562714/" ]
74,519,043
<p>How to extract re-captcha token from blockchain in jmeter</p> <p>I want a token id from blockchain and implement in another graphql Request as variable</p>
[ { "answer_id": 74519196, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "template<typename Element_T,\n template <typename Elem> typename Vector_T>\nrequires IVector_T<Vector_T<Element_T>, Element_T>\nclass TestVector\n{\n...\n Vector_T TestVector IVector_T template <IVector_T Vector_T>" }, { "answer_id": 74519206, "author": "bitmask", "author_id": 430766, "author_profile": "https://Stackoverflow.com/users/430766", "pm_score": 2, "selected": false, "text": "template<typename Element_T, template <typename> typename Vector_T>\nrequires(IVector_T<Vector_T<Element_T>, Element_T>)\nclass TestVector { // ...\n" }, { "answer_id": 74519305, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 3, "selected": true, "text": "Vector_T template<typename Element_T, IVector_T<Element_T> Vector_T>\nclass TestVector\n{\n...\nprivate:\n Vector_T myVec;\n};\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562878/" ]
74,519,046
<p>A business feature that came out is to export invoice PDF files with arabic text. Stack we're using is: Spring boot 2.7.5</p> <p>We're generating our PDFs using jasperreport:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;net.sf.jasperreports&lt;/groupId&gt; &lt;artifactId&gt;jasperreports&lt;/artifactId&gt; &lt;version&gt;${jasperreports.version}&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>The code is pretty simple:</p> <pre><code>Map&lt;String, Object&gt; jasperParameters = new HashMap&lt;&gt;(); // Handling language ResourceBundle bundle = ResourceBundle.getBundle( &quot;localization/i18n&quot;, new Locale(&quot;ar&quot;, &quot;MA&quot;)); jasperParameters.put(JRParameter.REPORT_RESOURCE_BUNDLE, bundle); jasperParameters.put(&quot;currency&quot;, &quot;MAD&quot;); jasperParameters.put(&quot;orderNumber&quot;, orderEntity.getReference()); jasperParameters.put(&quot;orderDate&quot;, orderEntity.getCreatedDate().toString()); jasperParameters.put(&quot;clientName&quot;, orderEntity.getClient().getName()); jasperParameters.put(&quot;clientPhoneNumber&quot;, orderEntity.getClient().getPhoneNumber()); InputStream template = getClass().getResourceAsStream(&quot;/templates/order.jrxml&quot;); List&lt;OrderItemEntity&gt; orderItemEntities = orderItemDaoService.findAll(OrderItemSpecification.withOrderId( orderEntity.getId()), Pageable.unpaged()).getContent(); List&lt;OrderInvoiceItem&gt; orderItems = orderItemEntities.stream().map(orderItemMapper::entityToInvoiceItem) .toList(); try { JasperReport jasperReport = JasperCompileManager.compileReport(template); JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(orderItems); jasperParameters.put(&quot;datasource&quot;, dataSource); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, jasperParameters, new JREmptyDataSource()); byte[] pdf = JasperExportManager.exportReportToPdf(jasperPrint); String base64PDF = Base64.getEncoder().encodeToString(pdf); log.info(&quot;Your pdf file is: {}&quot;, base64PDF); } catch (JRException e) { log.warn( &quot;Couldn't generate invoice based on Jasper report. More information about the error: {}&quot;, e.getMessage()); throw new RuntimeException( &quot;An error occurred when generating invoice with Jasper Report.&quot;, e); } </code></pre> <p>Unfortunately, our labels defined in the bundle are displayed as question marks. Looked for existing answers on the web, all were referring to fonts that should be loaded or installed on the server but nothing seems to work since I installed them on my laptop and nothing changed.</p> <p>We tried to move to Thymeleaf using flying-saucer but this time arabic labels weren't displayed on the final PDF and during processing of the template the String value returned does hold the caracters correctly.</p> <p>Any help will be appreciated.</p>
[ { "answer_id": 74519196, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "template<typename Element_T,\n template <typename Elem> typename Vector_T>\nrequires IVector_T<Vector_T<Element_T>, Element_T>\nclass TestVector\n{\n...\n Vector_T TestVector IVector_T template <IVector_T Vector_T>" }, { "answer_id": 74519206, "author": "bitmask", "author_id": 430766, "author_profile": "https://Stackoverflow.com/users/430766", "pm_score": 2, "selected": false, "text": "template<typename Element_T, template <typename> typename Vector_T>\nrequires(IVector_T<Vector_T<Element_T>, Element_T>)\nclass TestVector { // ...\n" }, { "answer_id": 74519305, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 3, "selected": true, "text": "Vector_T template<typename Element_T, IVector_T<Element_T> Vector_T>\nclass TestVector\n{\n...\nprivate:\n Vector_T myVec;\n};\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682000/" ]
74,519,060
<p>So I have a table with name, quantity and price</p> <pre><code>name quantity price &quot;custom-row&quot; a 12 5 12*5 b 20 3 20*3 c 18 10 18*10 </code></pre> <p>Is it possible to add a &quot;custom&quot; row when using a select query? And I want the values in that row = quantity * price. How can I do that?</p>
[ { "answer_id": 74519196, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "template<typename Element_T,\n template <typename Elem> typename Vector_T>\nrequires IVector_T<Vector_T<Element_T>, Element_T>\nclass TestVector\n{\n...\n Vector_T TestVector IVector_T template <IVector_T Vector_T>" }, { "answer_id": 74519206, "author": "bitmask", "author_id": 430766, "author_profile": "https://Stackoverflow.com/users/430766", "pm_score": 2, "selected": false, "text": "template<typename Element_T, template <typename> typename Vector_T>\nrequires(IVector_T<Vector_T<Element_T>, Element_T>)\nclass TestVector { // ...\n" }, { "answer_id": 74519305, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 3, "selected": true, "text": "Vector_T template<typename Element_T, IVector_T<Element_T> Vector_T>\nclass TestVector\n{\n...\nprivate:\n Vector_T myVec;\n};\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15671786/" ]
74,519,064
<pre><code>data = tibble(x = c(&quot;a&quot;, &quot;b&quot;), y = c(&quot;aa&quot;, &quot;b&quot;), z = c(&quot;a&quot;, &quot;bb&quot;)) data %&gt;% mutate(str_length = across(c(x, y, z), ~ str_count(., &quot;.&quot;))) </code></pre> <p>How do I calculate the difference between str_length for each row?</p> <p>Desired output would be: <code>data$str_diff</code> = c(1, 1).</p>
[ { "answer_id": 74519137, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "data %>% \n mutate(\n str_diff = abs(str_count(x) - str_count(y))\n )\n x y z str_diff\n <chr> <chr> <dbl> <int>\n1 a aa 1 1\n2 b b 2 0\n" }, { "answer_id": 74519364, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 2, "selected": false, "text": "data$str_diff <- apply(sapply(data, nchar), 1, function(row) diff(range(row)))\n *apply data$str_diff <- apply(data, 1, function(row) diff(range(nchar(row))))\n" }, { "answer_id": 74519454, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 3, "selected": true, "text": "tidyverse pmap data %>% \n mutate(str_diff = pmap_int(across(x:z), ~ diff(range(str_length(c(...))))))\n\n# A tibble: 2 × 4\n x y z str_diff\n <chr> <chr> <chr> <int>\n1 a aa a 1\n2 b b bb 1\n" }, { "answer_id": 74519484, "author": "pgitti", "author_id": 16748103, "author_profile": "https://Stackoverflow.com/users/16748103", "pm_score": 1, "selected": false, "text": "data %>% \n rowwise() %>% \n mutate(str_diff = diff(range(map(c(x, y, z), str_count))))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16748103/" ]
74,519,107
<p>So I've actually got two issues with <strong>PostgreSQL</strong>. I actually use <strong>npgsql.NET</strong> to create queries, connections, other with PostgreSQL, however I am new to this database software.</p> <h1>First Issue</h1> <p>I got the error:</p> <pre class="lang-cs prettyprint-override"><code>Npgsql.PostgresException: '42601: syntax error at or near &quot;#&quot; POSITION: 16' </code></pre> <p>after using the script:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE {textBox1.Text} ( user_id serial PRIMARY KEY, username VARCHAR ( 50 ) UNIQUE NOT NULL, password VARCHAR ( 50 ) NOT NULL, email VARCHAR ( 255 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL, last_login TIMESTAMP ); </code></pre> <p>The <code>textbox1.Text</code> included: Pronner#2223.</p> <h1>Second Issue</h1> <p>When creating a table with the name <code>PRONNER</code> for example, it shows up as <code>pronner</code>. What's wrong with the capitalization system? Or can it possibly be because I'm using <code>pgAdmin 4</code> so I just see it as lower case there?</p> <p>I'm quite new to this like I mentioned at the beginning of the issue, and I used to use <code>MySQL</code> so the syntax is a teensy bit different, but the system is very different.</p>
[ { "answer_id": 74519137, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "data %>% \n mutate(\n str_diff = abs(str_count(x) - str_count(y))\n )\n x y z str_diff\n <chr> <chr> <dbl> <int>\n1 a aa 1 1\n2 b b 2 0\n" }, { "answer_id": 74519364, "author": "Robert Hacken", "author_id": 2094893, "author_profile": "https://Stackoverflow.com/users/2094893", "pm_score": 2, "selected": false, "text": "data$str_diff <- apply(sapply(data, nchar), 1, function(row) diff(range(row)))\n *apply data$str_diff <- apply(data, 1, function(row) diff(range(nchar(row))))\n" }, { "answer_id": 74519454, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 3, "selected": true, "text": "tidyverse pmap data %>% \n mutate(str_diff = pmap_int(across(x:z), ~ diff(range(str_length(c(...))))))\n\n# A tibble: 2 × 4\n x y z str_diff\n <chr> <chr> <chr> <int>\n1 a aa a 1\n2 b b bb 1\n" }, { "answer_id": 74519484, "author": "pgitti", "author_id": 16748103, "author_profile": "https://Stackoverflow.com/users/16748103", "pm_score": 1, "selected": false, "text": "data %>% \n rowwise() %>% \n mutate(str_diff = diff(range(map(c(x, y, z), str_count))))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19200377/" ]
74,519,144
<p>I am calling some macros via VBA cod i need some changes in it, i will be thankful if any help could be provided</p> <pre><code>Sub Button1_Click() Call moveFilesFromListPartial Call moveFilesFromListPartial_AA Call moveAllFilesInDateFolderIfNotExist Application.OnTime Now + TimeValue(&quot;00:01:00&quot;), &quot;Button1_Click&quot; End Sub </code></pre> <p>In this current VBA macro all the macros run after one minutes however i request if 3rd macro which is moveAllFilesInDateFolderIfNotExist should run after 5 seconds of first 2 macros. i.e. first 2 macros should be run after 60 seconds and third macro should be run after 65 seconds. this should be the loop every time</p> <p>i will be grateful</p>
[ { "answer_id": 74520927, "author": "Guillaume BEDOYA", "author_id": 20522241, "author_profile": "https://Stackoverflow.com/users/20522241", "pm_score": 1, "selected": false, "text": "Application.Wait Sub Button1_Click()\n\n Call moveFilesFromListPartial\n Call moveFilesFromListPartial_AA\n Application.Wait(Now + TimeValue(\"00:00:05\")) ' 5 seconds to wait\n Call moveAllFilesInDateFolderIfNotExist\n Application.OnTime Now + TimeValue(\"00:01:00\"), \"Button1_Click\"\nEnd Sub\n Sleep Public Declare Sub Sleep Lib \"kernel32\" (ByVal dwmilliseconds As Long)\n Sleep 5000 moveAllFilesInDateFolderIfNotExist" }, { "answer_id": 74528547, "author": "Tim Williams", "author_id": 478884, "author_profile": "https://Stackoverflow.com/users/478884", "pm_score": 1, "selected": true, "text": "Sub Button1_Click()\n Application.OnTime Now + TimeValue(\"00:01:00\"), \"Part1\"\nEnd Sub\n\nSub Part1()\n Call moveFilesFromListPartial\n Call moveFilesFromListPartial_AA\n 'wait 5sec before running the next part \n Application.OnTime Now + TimeValue(\"00:00:05\"), \"Part2\"\nEnd Sub\n\nSub Part2()\n Call moveAllFilesInDateFolderIfNotExist\n Application.OnTime Now + TimeValue(\"00:01:00\"), \"Part1\"\nEnd Sub\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20141828/" ]
74,519,176
<p>How to remove duplicate entries from a large Oracle table (200M rows, 20 columns)?</p> <p>The below query <a href="https://stackoverflow.com/questions/529098/removing-duplicate-rows-from-table-in-oracle">from 2014</a> is slow. It took 2 minutes to delete 1 duplicate entry for one specific combination of columns (i.e. <code>where col1 = 1 and .. col20 = 'Z'</code>).</p> <pre><code>DELETE sch.table1 WHERE rowid NOT IN (SELECT MIN(rowid) FROM sch.table1 GROUP BY col1, col2, col3, col4,.. ., col20) </code></pre> <p>Any way to speed it up, e.g. with indexing?</p>
[ { "answer_id": 74520927, "author": "Guillaume BEDOYA", "author_id": 20522241, "author_profile": "https://Stackoverflow.com/users/20522241", "pm_score": 1, "selected": false, "text": "Application.Wait Sub Button1_Click()\n\n Call moveFilesFromListPartial\n Call moveFilesFromListPartial_AA\n Application.Wait(Now + TimeValue(\"00:00:05\")) ' 5 seconds to wait\n Call moveAllFilesInDateFolderIfNotExist\n Application.OnTime Now + TimeValue(\"00:01:00\"), \"Button1_Click\"\nEnd Sub\n Sleep Public Declare Sub Sleep Lib \"kernel32\" (ByVal dwmilliseconds As Long)\n Sleep 5000 moveAllFilesInDateFolderIfNotExist" }, { "answer_id": 74528547, "author": "Tim Williams", "author_id": 478884, "author_profile": "https://Stackoverflow.com/users/478884", "pm_score": 1, "selected": true, "text": "Sub Button1_Click()\n Application.OnTime Now + TimeValue(\"00:01:00\"), \"Part1\"\nEnd Sub\n\nSub Part1()\n Call moveFilesFromListPartial\n Call moveFilesFromListPartial_AA\n 'wait 5sec before running the next part \n Application.OnTime Now + TimeValue(\"00:00:05\"), \"Part2\"\nEnd Sub\n\nSub Part2()\n Call moveAllFilesInDateFolderIfNotExist\n Application.OnTime Now + TimeValue(\"00:01:00\"), \"Part1\"\nEnd Sub\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19363912/" ]
74,519,188
<p>I've a simple question but I couldn't find a plausible solution.</p> <p>My dataframe looks like this:</p> <pre><code>dput(prec) structure(list(date = structure(c(19091, 19091, 19092, 19092, 19093, 19093, 19094, 19094, 19095, 19095, 19096, 19096, 19097, 19097, 19098, 19098, 19099, 19099, 19100, 19100, 19101, 19101, 19102, 19102, 19103, 19103, 19104, 19104, 19105, 19105, 19106, 19106, 19107, 19107, 19109, 19109, 19110, 19110, 19111, 19111, 19112, 19112, 19113, 19113, 19114, 19114), class = &quot;Date&quot;), target = c(&quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;, &quot;grass&quot;, &quot;tree&quot;), Precip_Tot = c(0, 0, 0, 0, 0.0464, 0.0464, 0.0362, 0.0362, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.131, 0.131, 0, 0, 0, 0, 0, 0, 0.016, 0.016, 0, 0, 0, 0, 0, 0, 0, 0, 0.4506, 0.4506)), row.names = c(NA, 46L), class = &quot;data.frame&quot;) </code></pre> <p>In the column <strong>Precip_Tot</strong> I have duplicated values because I have duplicated <strong>date</strong>.</p> <p>How can I remove/turn into NA the duplicate values of <strong>Precip_Tot</strong> per <strong>date</strong> day? Note: I don't want to remove any row.</p> <p>Any help is much appreciated.</p>
[ { "answer_id": 74519438, "author": "user2974951", "author_id": 2974951, "author_profile": "https://Stackoverflow.com/users/2974951", "pm_score": 3, "selected": true, "text": "prec[duplicated(prec$date),\"Precip_Tot\"]=NA\n\n date target Precip_Tot\n1 2022-04-09 grass 0.0000\n2 2022-04-09 tree NA\n3 2022-04-10 grass 0.0000\n4 2022-04-10 tree NA\n5 2022-04-11 grass 0.0464\n6 2022-04-11 tree NA\n7 2022-04-12 grass 0.0362\n8 2022-04-12 tree NA\n9 2022-04-13 grass 0.0000\n ...\n" }, { "answer_id": 74519503, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 1, "selected": false, "text": "NA library(dplyr)\n\nprec %>%\n group_by(date) %>%\n mutate(Precip_Tot = if_else(row_number() == 1, Precip_Tot, NA_real_)) %>%\n ungroup()\n # A tibble: 46 × 3\n date target Precip_Tot\n <date> <chr> <dbl>\n 1 2022-04-09 grass 0 \n 2 2022-04-09 tree NA \n 3 2022-04-10 grass 0 \n 4 2022-04-10 tree NA \n 5 2022-04-11 grass 0.0464\n 6 2022-04-11 tree NA \n 7 2022-04-12 grass 0.0362\n 8 2022-04-12 tree NA \n 9 2022-04-13 grass 0 \n10 2022-04-13 tree NA \n# … with 36 more rows\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15030195/" ]
74,519,192
<p>How can I evaluate an <code>ifelse()</code> statement using a condition stored in a character vector?</p> <p>For example:</p> <pre><code>a &lt;- 1 b &lt;- 2 condition &lt;- &quot;&gt;&quot; ifelse(a condition b, print(&quot;good&quot;), print(&quot;bad)) </code></pre>
[ { "answer_id": 74519322, "author": "Anoushiravan R", "author_id": 14314520, "author_profile": "https://Stackoverflow.com/users/14314520", "pm_score": 3, "selected": false, "text": "ifelse(eval(parse(text = paste0(a, condition, b))), 'good', 'bad')\n" }, { "answer_id": 74519376, "author": "Andy Baxter", "author_id": 10744082, "author_profile": "https://Stackoverflow.com/users/10744082", "pm_score": 2, "selected": false, "text": "ifelse(do.call(condition, list(a, b)), \"good\", \"bad\")\n >" }, { "answer_id": 74519897, "author": "Ronak Shah", "author_id": 3962914, "author_profile": "https://Stackoverflow.com/users/3962914", "pm_score": 3, "selected": false, "text": "match.fun a <- 1\nb <- 2\ncondition <- \">\"\nif(match.fun(condition)(a, b)) 'good' else 'bad'\n#[1] \"bad\"\n if else ifelse a b ifelse eval(parse(...)) condition match.fun" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19305511/" ]
74,519,210
<p>What is the <code>-o</code> flag in this .NET CLI command: <code>dotnet new webapi -o RESTfulAPIName</code>?</p> <p>My .Net Core SDK version is 6.0.403.</p>
[ { "answer_id": 74519269, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 2, "selected": false, "text": "./<ProjectName>/ dotnet new --help" }, { "answer_id": 74519277, "author": "Mellik", "author_id": 20561885, "author_profile": "https://Stackoverflow.com/users/20561885", "pm_score": 2, "selected": false, "text": "-o [-o|--output <OUTPUT_DIRECTORY>] [--project <PROJECT_PATH>]\n" }, { "answer_id": 74519599, "author": "Amir", "author_id": 3567736, "author_profile": "https://Stackoverflow.com/users/3567736", "pm_score": 1, "selected": false, "text": "-o" }, { "answer_id": 74523938, "author": "Waqar Dongre", "author_id": 6805982, "author_profile": "https://Stackoverflow.com/users/6805982", "pm_score": 0, "selected": false, "text": "dotnet new --help" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805982/" ]
74,519,257
<p>I have a multiindex and I want to perform drop_duplicates on a per level basis, I dont want to look at the entire dataframe but only if there is a duplicate with the same main index</p> <p>Example:</p> <pre><code>entry,subentry,A,B 1 0 1.0 1.0 1 1.0 1.0 2 2.0 2.0 2 0 1.0 1.0 1 2.0 2.0 2 2.0 2.0 </code></pre> <p>should return:</p> <pre><code>entry,subentry,A,B 1 0 1.0 1.0 1 2.0 2.0 2 0 1.0 1.0 1 2.0 2.0 </code></pre>
[ { "answer_id": 74519273, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 3, "selected": true, "text": "MultiIndex.get_level_values Index.duplicated entry boolean indexing df1 = df[df.index.get_level_values('entry').duplicated(keep='last')]\nprint (df1)\n\n A B\nentry subentry \n1 0 1.0 1.0\n 1 1.0 1.0\n2 0 1.0 1.0\n 1 2.0 2.0\n DataFrame.reset_index ~ Series df2 = df[~df.reset_index(level=0).duplicated(keep='last').to_numpy()]\nprint (df2)\n\n A B\nentry subentry \n1 1 1.0 1.0\n 2 2.0 2.0\n2 0 1.0 1.0\n 2 2.0 2.0\n df2 = df[~df.assign(new=df.index.get_level_values('entry')).duplicated(keep='last')]\nprint (df2)\n\n A B\nentry subentry \n1 1 1.0 1.0\n 2 2.0 2.0\n2 0 1.0 1.0\n 2 2.0 2.0\n print (df.reset_index(level=0))\n entry A B\nsubentry \n0 1 1.0 1.0\n1 1 1.0 1.0\n2 1 2.0 2.0\n0 2 1.0 1.0\n1 2 2.0 2.0\n2 2 2.0 2.0\n\nprint (~df.reset_index(level=0).duplicated(keep='last'))\n0 False\n1 True\n2 True\n0 True\n1 False\n2 True\ndtype: bool\n print (df.assign(new=df.index.get_level_values('entry')))\n A B new\nentry subentry \n1 0 1.0 1.0 1\n 1 1.0 1.0 1\n 2 2.0 2.0 1\n2 0 1.0 1.0 2\n 1 2.0 2.0 2\n 2 2.0 2.0 2\n \nprint (~df.assign(new=df.index.get_level_values('entry')).duplicated(keep='last'))\nentry subentry\n1 0 False\n 1 True\n 2 True\n2 0 True\n 1 False\n 2 True\ndtype: bool\n" }, { "answer_id": 74519375, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "drop_duplicates out = df.groupby(level=0, group_keys=False).apply(lambda d: d.drop_duplicates())\n reset_index duplicated out = df[~df.reset_index('entry').duplicated().values]\n A B\nentry subentry \n1 0 1.0 1.0\n 2 2.0 2.0\n2 0 1.0 1.0\n 1 2.0 2.0\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13981994/" ]
74,519,289
<p>I have got a python list</p> <pre><code>Year= [‘1997JAN’, ‘1997FEB’, ‘1997MAR’‘1997APR’………………………’2021SEP’’2021OCT’] </code></pre> <p>I would like to extract only years from the above list but not the months</p> <p>How can I extract only years?</p> <pre><code>Year = [1997,1997,1997,…………………2021,2021] </code></pre>
[ { "answer_id": 74519387, "author": "here_need_help", "author_id": 19383281, "author_profile": "https://Stackoverflow.com/users/19383281", "pm_score": 2, "selected": true, "text": "dates = ['1997JAN', '1997FEB', '1997MAR','1997APR', '2022NOV']\n years = [int(x[:4]) for x in dates]\n" }, { "answer_id": 74519448, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": "re import re\n\nYear= ['1997JAN', '1997FEB', '1997MAR','1997APR','2021SEP','2021OCT']\n\nYears_only=[re.findall(r'\\d+', year)[0] for year in Year]\n\nYears_only\n ['1997', '1997', '1997', '1997', '2021', '2021']\n" }, { "answer_id": 74519466, "author": "Ali", "author_id": 6189090, "author_profile": "https://Stackoverflow.com/users/6189090", "pm_score": 0, "selected": false, "text": "filter str.isdigit input = '1997JAN'\noutput = ''.join(filter(str.isdigit, input))\nprint(output)\n# '1997' (This is still string)\n output = int(''.join(filter(str.isdigit, input)))\nprint(output)\n# 1997\n output = list(map(lambda input: int(''.join(filter(str.isdigit, input))), Year))\nprint(output)\n# [1997,1997,1997,…………………2021,2021]\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17731735/" ]
74,519,306
<p>I have a schema, in which there are many tables and which thus contains many columns. Is there a way I can select specific columns from the scheme?</p>
[ { "answer_id": 74519543, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT column1, column3, column4\nFROM schema_name.table_name\n SELECT t1.column1,\n t1.column3,\n t2.column4,\n t3.column1 AS t3_column1\nFROM schema_name.table1 t1\n CROSS JOIN schema_name.table2 t2\n INNER JOIN schema_name.table3 t3\n ON (t1.columnX = t3.columnY)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7518949/" ]
74,519,334
<p>The program is meant to remove the '-' from an ISBN code inputted, eg. &quot;978-123456-789&quot; is inputted and &quot;978123456789&quot; is outputted. Instead what I'm getting out is &quot;978123456789978123456789&quot; - it's printing it twice. Can someone please explain to me why? Thanks</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;string.h&gt; int main(void) { char ISBN[16], arrayClean[12]; int i,j,k,a; printf(&quot;Enter your ISBN: &quot;); scanf(&quot;%s&quot;,&amp;ISBN); for(i=0; i&lt;=13; i++) { a = ISBN[i] - 48; if(a==-3) { for(j=i;j&lt;=13;j++) { k++; ISBN[j]=ISBN[j+1]; } k=0; i=0; } } for(i=0; i&lt;=11; i++) arrayClean[i]=ISBN[i]; printf(&quot;%s&quot;,arrayClean); return 0; } </code></pre>
[ { "answer_id": 74519543, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT column1, column3, column4\nFROM schema_name.table_name\n SELECT t1.column1,\n t1.column3,\n t2.column4,\n t3.column1 AS t3_column1\nFROM schema_name.table1 t1\n CROSS JOIN schema_name.table2 t2\n INNER JOIN schema_name.table3 t3\n ON (t1.columnX = t3.columnY)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20563109/" ]
74,519,359
<p>I need to find all columns that have 5 or more distinct values. Now my query is like:</p> <pre><code> SELECT TABLE_NAME,COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'MY_SCHEMA' AND TABLE_NAME IN ('TABLE_1', 'TABLE_2', 'TABLE_3') </code></pre> <p>I thought it could be done like simple subquery. Something like:</p> <pre><code>*code above* AND (select count(distinct COLUMN_NAME) FROM TABLE_SCHEMA + TABLE_NAME) &gt; 5 </code></pre> <p>I just recently started to learn SQL and thought this kind of thing is easy, but still I can't figure out right query.</p>
[ { "answer_id": 74519543, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "SELECT column1, column3, column4\nFROM schema_name.table_name\n SELECT t1.column1,\n t1.column3,\n t2.column4,\n t3.column1 AS t3_column1\nFROM schema_name.table1 t1\n CROSS JOIN schema_name.table2 t2\n INNER JOIN schema_name.table3 t3\n ON (t1.columnX = t3.columnY)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12359353/" ]
74,519,373
<p>I try to write mock test using jest and @vue/test-utils, Here is the &quot;<strong>bots.spec.js</strong>&quot; / test file.</p> <pre><code>jest.mock('axios', ()=&gt;({ getBots: () =&gt; { const result = { __esModule: true, data: () =&gt; ({ name: &quot;demo&quot;, _id: &quot;62e8d832afdaad001b65bff5&quot;, }) } return Promise.resolve(result) } })) let getBots; describe('Load bots function', () =&gt; { beforeEach(async () =&gt; { jest.clearAllMocks() getBots = (await import('../../src/services')).default }) it('Should load given bots', async() =&gt;{ const bot_Name = &quot;demo&quot; const bot_id = &quot;62e8d832afdaad001b65bff5&quot; const actual = await getBots(bot_id) expect(actual).toMatch(bot_Name) }) }) </code></pre> <p>Following error occurred</p> <pre><code>TypeError: _axios.default.get is not a function </code></pre> <p><a href="https://i.stack.imgur.com/tr25l.png" rel="nofollow noreferrer">screenshot of the occurred error</a></p>
[ { "answer_id": 74520094, "author": "Tobias Souza", "author_id": 20562925, "author_profile": "https://Stackoverflow.com/users/20562925", "pm_score": 2, "selected": false, "text": "jest.mock('axios', () => ({\n get: jest.fn(),\n}));\n it('Should load given bots', async() =>{\n (mockAxios.get as jest.Mock).mockImplementationOnce(() =>\n Promise.resolve({\n data: {\n name: \"demo\",\n _id: \"62e8d832afdaad001b65bff5\",\n }\n })\n );\n const bot_Name = \"demo\"\n const bot_id = \"62e8d832afdaad001b65bff5\"\n\n const actual = await getBots(bot_id)\n expect(actual).toMatch(bot_Name)\n})\n" }, { "answer_id": 74557550, "author": "Saduni", "author_id": 15383182, "author_profile": "https://Stackoverflow.com/users/15383182", "pm_score": 1, "selected": false, "text": " jest.mock('axios', ()=>({\n get: () => {\n const result = {\n data:{\n name: \"demo\",\n _id: \"62e8d832afdaad001b65bff5\",\n }\n }\n return Promise.resolve(result)\n }\n}))\n\nlet getBots;\ndescribe('Load bots function', () => {\n beforeEach(async () => {\n jest.clearAllMocks()\n getBots = (await (await import('../../src/services')).getBots)\n })\n\n it('Should load given bots', async() =>{\n const expectedResponse = {\n name: \"demo\",\n _id: \"62e8d832afdaad001b65bff5\",\n\n }\n const actual = await getBots()\n\n expect(actual.data).toStrictEqual(expectedResponse)\n })\n})\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15383182/" ]
74,519,394
<p>I am a beginner python user and I am stuck with a time-calculator program I am trying to create as part of an online certification. The program will calculate in an AM/PM format the time it is added from the initial time and the correct weekday. I have been having problems with this part as for reasons unknown to me the functions restart after having found the new weekday, assigning the integer &quot;2&quot; from the variable weekday and then breaking.</p> <p>Here is the code snippet:</p> <pre><code>day_names = [ &quot;monday&quot;, &quot;tuesday&quot;, &quot;wednesday&quot;, &quot;thursday&quot;, &quot;friday&quot;, &quot;saturday&quot;, &quot;sunday&quot;, ] def weekday_calculator( weekday, day_count, new_hour, new_minute,): # this function calculates the right weekday for the new time &gt; print(f&quot;starting weekday:{weekday}&quot;) &gt; weekday = weekday.lower() &gt; starting_day_index = day_names.index(weekday) &gt; print(f&quot;This is the starting day of the week's index: {starting_day_index}&quot;) &gt; print(f&quot;This is the day count {day_count}&quot;) &gt; weekday_calculate = starting_day_index + day_count &gt; if weekday_calculate &lt;= 6: &gt;&gt; new_weekday = day_names[weekday_calculate] # to be fixed &gt;&gt; print(f&quot;This is the new weekday {new_weekday}&quot;) &gt;&gt; result_printer(new_hour, new_minute, new_am_pm, day_count, new_weekday) &gt; elif weekday_calculate &gt; 6: &gt;&gt; print(&quot;let's adjust the weekday&quot;) &gt;&gt; adjust_weekday(define_weekday) weekday_calculator(weekday = &quot;tuesday&quot;, daycount = 1) #this is only the data relevant to this snippet </code></pre> <p>This is the expected output:</p> <pre><code>Let's calculate the weekday starting weekday:tuesday This is the starting day of the week's index: 1 This is the day count 1 This is the new weekday Wednesday (proceeds to the next function) </code></pre> <p>This is what has been happening</p> <pre><code>Let's calculate the weekday starting weekday:tuesday This is the starting day of the week's index: 1 This is the day count 1 This is the new weekday wednesday tuesday starting weekday:2 Traceback (most recent call last) line 52, in weekday_calculator weekday = weekday.lower() AttributeError: 'int' object has no attribute 'lower' # of course that is because you cannot change an integer to lower </code></pre> <p>Does anyone have an idea on how to fix this problem? I have no idea where the value &quot;2&quot; for weekday is coming from, and neither why the function is repeating itself instead of directly jump to the next one once at the end of the if statement. I have tried to change the structure of the function and the variable names so that the program does not make confusion between weekday and new weekday, but to no avail.</p> <p>As you rightly requested, I have edited the post and added the rest of the code:</p> <pre><code>day_names = [ &quot;monday&quot;, &quot;tuesday&quot;, &quot;wednesday&quot;, &quot;thursday&quot;, &quot;friday&quot;, &quot;saturday&quot;, &quot;sunday&quot;, ] timeday_am = [&quot;PM&quot;, &quot;AM&quot;] * 100 timeday_pm = [&quot;AM&quot;, &quot;PM&quot;] * 100 weekday = 0 def result_printer(new_hour, new_minute, new_am_pm, day_count, weekday): new_time = [new_hour, new_minute] for number in new_time: if number &lt; 10: return f&quot;0{number}&quot; if day_count != 0: if day_count == 1: day = &quot;(next day)&quot; else: day = f&quot;({day_count} days later)&quot; print(f&quot;{new_time[0]}:{new_time[1]} {new_am_pm}, {weekday} {day}&quot;) def adjust_weekday( define_weekday, ): # this is to adjust the weekday index if it is more than 6 adjusted_weekday = day_names[define_weekday % len(day_names)] print((adjusted_weekday)) def weekday_calculator( weekday, day_count, new_hour, new_minute, new_am_pm ): # this function calculates the right weekday for the new time print(f&quot;starting weekday:{weekday}&quot;) weekday = weekday.lower() starting_day_index = day_names.index(weekday) print(f&quot;This is the starting day of the week's index: {starting_day_index}&quot;) print(f&quot;This is the day count {day_count}&quot;) weekday_calculate = starting_day_index + day_count if weekday_calculate &lt;= 6: new_weekday = day_names[weekday_calculate] # to be fixed print(f&quot;This is the new weekday {new_weekday}&quot;) result_printer(new_hour, new_minute, new_am_pm, day_count, new_weekday) elif weekday_calculate &gt; 6: print(&quot;let's adjust the weekday&quot;) adjust_weekday(define_weekday) def day_calculator( new_hour, new_minute, new_am_pm, am_pm, weekday, day_count ): # this function calculates the right AM PM of the new hour, and the number of days between times (if applicable) day_count = day_count if new_am_pm == &quot;AM&quot;: new_am_pm = timeday_am[am_pm] print(f&quot;This is the new time of the day list {new_am_pm}&quot;) day_new = timeday_am[:am_pm] print(f&quot;this is the new day {day_new}&quot;) day_count = day_new.count( &quot;AM&quot; ) # this is to count how many days have passed from the starting day print(f&quot;this is the day count {day_count}&quot;) elif new_am_pm == &quot;PM&quot;: new_am_pm_day = timeday_pm[am_pm] print(f&quot;This is the new time of the day {new_am_pm}&quot;) day_new = timeday_pm[:am_pm] print(f&quot;this is how it is calculated {day_new}&quot;) day_count = day_new.count(&quot;AM&quot;) print(f&quot;this is the day count {day_count}&quot;) if weekday is not None: print(weekday) print(&quot;Let's calculate the weekday&quot;) weekday_calculator(weekday, day_count, new_hour, new_minute, new_am_pm) result_printer(new_hour, new_minute, new_am_pm, day_count, weekday) def time_calculator(init_time: str, add_time: str, weekday: str): day_count = 0 new_am_pm = init_time.split(&quot; &quot;)[1] init_hour = int(init_time.split(&quot;:&quot;)[0]) init_minute = init_time.split(&quot;:&quot;)[1] init_minute = int( init_minute.split(&quot; &quot;)[0] ) # this is to avoid to include AM/PM in the string #this results in problem when python cannot convert string to integer because of formatting ex 00: add_hour = int(add_time.split(&quot;:&quot;)[0]) add_minute = int(add_time.split(&quot;:&quot;)[1]) print( f&quot;1. This is the hour to be added: {init_hour} and this is the minute: {init_minute}&quot; ) # @ control string new_minute = init_minute + add_minute new_hour = init_hour + add_hour if new_minute &gt;= 60: new_minute -= 60 new_hour = new_hour + 1 # calculate am or pm am_pm = ( new_hour // 12 ) # this starts the process to calculate the right time of the day and day of the week, floor division rounds the number down print(f&quot;This is {am_pm} am pm coefficent&quot;) # @control string print(type(am_pm)) # adapt new hour to hour format 0-12 if new_hour &gt; 12: new_hour = new_hour - (am_pm * 12) print( f&quot;This is the new hour: {new_hour} and this is the new minute: {new_minute}&quot; ) # @ control string if am_pm &lt; 1: new_am_pm = new_am_pm else: day_calculator(new_hour, new_minute, new_am_pm, am_pm, weekday, day_count) if weekday is not None: weekday_calculator(new_hour, new_minute, new_am_pm, weekday, day_count) result_printer(new_hour, new_minute, new_am_pm, day_count, weekday) time_calculator(&quot;3:10 PM&quot;, &quot;23:20&quot;, &quot;tuesday&quot;) </code></pre>
[ { "answer_id": 74519521, "author": "Claude Shannon", "author_id": 20102259, "author_profile": "https://Stackoverflow.com/users/20102259", "pm_score": 1, "selected": false, "text": "starting weekday:tuesday\nThis is the starting day of the week's index: 1\nThis is the day count 1\nThis is the new weekday wednesday\n weekday, day_count, new_hour, new_minute, new_am_pm weekday_calculator(new_hour=new_hour, new_minute=new_minute, new_am_pm=new_am_pm, weekday=weekday, day_count=day_count)\n weekday_calculator(weekday, day_count, new_hour, new_minute, new_am_pm)" }, { "answer_id": 74519588, "author": "Maen", "author_id": 11104626, "author_profile": "https://Stackoverflow.com/users/11104626", "pm_score": 0, "selected": false, "text": "starting weekday:2" }, { "answer_id": 74519789, "author": "Jeanot Zubler", "author_id": 14906662, "author_profile": "https://Stackoverflow.com/users/14906662", "pm_score": 2, "selected": true, "text": "time_calculator day_calculator(new_hour, new_minute, new_am_pm, am_pm, weekday, day_count) weekday_calculator weekday_calculator weekday, day_count, new_hour, new_minute, new_am_pm new_hour, new_minute, new_am_pm, weekday, day_count" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13310599/" ]
74,519,398
<p>So I have a stack view and the profile image needs to go next to the the username and stay there. How do I do that in this arranged stack view without conflicts because I have tried to anchor it to the top. Like this but no results:</p> <p><a href="https://i.stack.imgur.com/JIwWK.png" rel="nofollow noreferrer">Image of what I am trying to achieve</a></p> <p>But currently it keeps doing this: <a href="https://i.stack.imgur.com/jnRW3.png" rel="nofollow noreferrer">What is currently happening</a></p> <pre><code>override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(profileImageView) contentView.addSubview(profileNameLabel) contentView.addSubview(userHandel) profileImageView.setContentHuggingPriority(.defaultHigh, for: .horizontal) let innerPostStackView = UIStackView(arrangedSubviews: [profileNameLabel, userHandel, postTextLabel]) innerPostStackView.axis = .vertical let postStackView = UIStackView(arrangedSubviews: [profileImageView, innerPostStackView]) postStackView.translatesAutoresizingMaskIntoConstraints = false postStackView.alignment = .center postStackView.spacing = 10 contentView.addSubview(postStackView) NSLayoutConstraint.activate([ postStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10), postStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15), postStackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10), postTextLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -15) ]) </code></pre> <p>This is what I Have tried with the stack views. I cannot get it to work the way I want it to look.</p>
[ { "answer_id": 74519761, "author": "md-rubel", "author_id": 11224645, "author_profile": "https://Stackoverflow.com/users/11224645", "pm_score": -1, "selected": false, "text": "override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n \n contentView.addSubview(profileImageView)\n contentView.addSubview(profileNameLabel)\n contentView.addSubview(userHandel)\n contentView.addSubview(postTextLabel)\n \n // activate autolayout constraints:\n NSLayoutConstraint.activate([\n // profileImageView:\n profileImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),\n profileImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16),\n profileImageView.heightAnchor.constraint(equalToConstant: 52),\n profileImageView.widthAnchor.constraint(equalToConstant: 52),\n \n // profileNameLabel:\n profileNameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),\n profileNameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8),\n profileNameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16),\n \n // userHandel:\n userHandel.topAnchor.constraint(equalTo: profileNameLabel.bottomAnchor, constant: 8),\n userHandel.leftAnchor.constraint(equalTo: profileNameLabel.leftAnchor),\n userHandel.rightAnchor.constraint(equalTo: profileNameLabel.rightAnchor),\n \n // postTextLabel:\n postTextLabel.topAnchor.constraint(equalTo: userHandel.bottomAnchor, constant: 8),\n postTextLabel.leftAnchor.constraint(equalTo: userHandel.leftAnchor),\n postTextLabel.rightAnchor.constraint(equalTo: userHandel.rightAnchor),\n postTextLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16)\n ])\n}\n" }, { "answer_id": 74520537, "author": "Fabio", "author_id": 5575955, "author_profile": "https://Stackoverflow.com/users/5575955", "pm_score": 1, "selected": true, "text": "class MyCell: UITableViewCell {\n\nlet profileNameLabel: UILabel = {\n let label = UILabel()\n label.numberOfLines = 0\n label.textColor = .black\n label.backgroundColor = .clear\n label.font = .systemFont(ofSize: 20, weight: .bold)\n label.text = \"Minions\"\n label.translatesAutoresizingMaskIntoConstraints = false\n return label\n}()\n\nlet userHandel: UILabel = {\n let label = UILabel()\n label.numberOfLines = 0\n label.textColor = .systemBlue\n label.backgroundColor = .clear\n label.font = .systemFont(ofSize: 14, weight: .semibold)\n label.text = \"@Minions\"\n label.translatesAutoresizingMaskIntoConstraints = false\n return label\n}()\n\nlet postTextLabel: UILabel = {\n let label = UILabel()\n label.numberOfLines = 0\n label.textColor = .black\n label.backgroundColor = .clear\n label.text = \"Every Mac comes with a one-year limited warranty(opens in a new window) and up to 90 days of complimentary technical support(opens in a new window). AppleCare+ for Mac extends your coverage from your AppleCare+ purchase date and adds unlimited incidents of accidental damage protection, each subject to a service fee of $99 for screen damage or external enclosure damage, or $299 for other accidental damage, plus applicable tax. In addition, you’ll get 24/7 priority access to Apple experts via chat or phone. For complete details, see the terms(opens in a new window).\"\n return label\n}()\n\nlet costant: CGFloat = 60\n\nlet profileImageView: UIImageView = {\n let iv = UIImageView()\n iv.backgroundColor = .darkGray.withAlphaComponent(0.2)\n iv.contentMode = .scaleAspectFill\n iv.clipsToBounds = true\n iv.translatesAutoresizingMaskIntoConstraints = false\n return iv\n}()\n\nlet containerView: UIView = {\n let v = UIView()\n v.backgroundColor = .clear\n return v\n}()\n\noverride init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n backgroundColor = .white\n let image = UIImage(named: \"minions\")?.withRenderingMode(.alwaysOriginal)\n profileImageView.image = image\n profileImageView.widthAnchor.constraint(equalToConstant: costant).isActive = true // set here profileImageView wudth\n profileImageView.layer.cornerRadius = costant / 2\n \n contentView.backgroundColor = .white\n \n containerView.addSubview(profileNameLabel)\n profileNameLabel.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true\n profileNameLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true\n profileNameLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true\n profileNameLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true\n \n containerView.addSubview(userHandel)\n userHandel.topAnchor.constraint(equalTo: profileNameLabel.bottomAnchor).isActive = true\n userHandel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true\n userHandel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true\n userHandel.heightAnchor.constraint(equalToConstant: 20).isActive = true\n \n let totalUpStack = UIStackView(arrangedSubviews: [profileImageView, containerView])\n totalUpStack.axis = .horizontal\n totalUpStack.spacing = 6\n totalUpStack.distribution = .fill\n totalUpStack.translatesAutoresizingMaskIntoConstraints = false\n totalUpStack.heightAnchor.constraint(equalToConstant: costant).isActive = true\n \n let completeStack = UIStackView(arrangedSubviews: [totalUpStack, postTextLabel])\n completeStack.axis = .vertical\n completeStack.spacing = 6\n completeStack.distribution = .fill\n completeStack.translatesAutoresizingMaskIntoConstraints = false\n \n contentView.addSubview(completeStack)\n completeStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true\n completeStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true\n completeStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true\n completeStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true\n}\n\nrequired init?(coder: NSCoder) {\n fatalError(\"init(coder:) has not been implemented\")\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20143356/" ]
74,519,442
<p>I'm trying to make a table that lists 2 types of files linked together. One type are .mp3, and the other are .txt files. I want these files to be linked together, such that the files that share the same name share one row, when the foreach loop passes through them. This is so that the mp3 files can be played, and the corresponding text file can be opened.</p> <p><strong>App.razor</strong> page has a table that displays all files in a folder, but it doesn't take into account if the files of the 2 types share the same name. Can anybody help with how to make a class that has the files linked together so that they can be called in the table?</p> <p>Here is the code.</p> <pre><code>&lt;table class=&quot;table table-striped mb-0&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (var fileGroup in myFilesGroupedAndSorted) { &lt;Mp3 FileGroup=fileGroup /&gt; } &lt;/tbody&gt; &lt;/table&gt; @code { readonly List&lt;TextFile&gt; textList = new(); private string audioUrl { get; set; } readonly string audioFolderName = &quot;textFiles&quot;; protected override void OnInitialized() { var path = $&quot;{env.WebRootPath}\\{audioFolderName}\\&quot;; //System.IO.Path.ChangeExtension(@&quot;wwwroot\textFiles\&quot;, null); var files = new DirectoryInfo(path).GetFiles(); foreach (var file in files) { textList.Add(new TextFile { Name = file.Name, Url = $&quot;/textFiles/{file.Name}&quot;, Path = file.FullName }); } } IEnumerable&lt;IGrouping&lt;string, TextFile&gt;&gt; myFilesGroupedAndSorted =&gt; textList.GroupBy(file =&gt; GetPathWithoutExtension(file.Path)) .OrderBy(group =&gt; group.Key); private string GetPathWithoutExtension(string path) { return System.IO.Path.ChangeExtension(path, null); } } </code></pre> <p><code>Mp3.razor</code></p> <pre><code>&lt;tr&gt; &lt;td&gt; @FileGroup.Key &lt;/td&gt; &lt;td&gt; @if (Mp3 is not null) { &lt;span @onclick=&quot;() =&gt; PlayAudio(Mp3.Url)&quot; class=&quot;text-primary oi oi-play-circle me-2&quot; aria-hidden=&quot;true&quot; role=&quot;button&quot;&gt; &lt;/span&gt; } @if (Text is not null) { &lt;span @onclick=&quot;() =&gt; openTextFile(Text)&quot;&gt; &lt;button&gt;Open&lt;/button&gt; &lt;/span&gt; } &lt;/td&gt; &lt;/tr&gt; @code { readonly List&lt;TextFile&gt; textList = new(); private string audioUrl { get; set; } [Parameter] public IGrouping&lt;string, TextFile&gt; FileGroup { get; set; } = default!; TextFile? Text =&gt; FileGroup.FirstOrDefault(file =&gt; Path.GetExtension(file.Path).ToLower() == &quot;txt&quot;); TextFile? Mp3 =&gt; FileGroup.FirstOrDefault(file =&gt; Path.GetExtension(file.Path).ToLower() == &quot;mp3&quot;); private void PlayAudio(string url) { audioUrl = url; InvokeAsync(StateHasChanged); } private async Task DeleteAudio(TextFile text) { ... } public void openTextFile(TextFile text) { ... } } </code></pre> <p>The newer version where <code>System.ArgumentNullException: 'Value cannot be null. (Parameter 'source')'</code> happens on startup. If i delete <code>TextFile? Text =&gt; fileGroup.FirstOrDefault(file =&gt; Path.GetExtension(file.Path).ToLower() == &quot;txt&quot;);</code> and <code>TextFile? Mp3 =&gt; fileGroup.FirstOrDefault(file =&gt; Path.GetExtension(file.Path).ToLower() == &quot;mp3&quot;);</code> as well as their mentions in the table, it functions.</p> <pre><code>@using System.Linq @inject IWebHostEnvironment env &lt;table class=&quot;table table-striped mb-0&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (var fileGroup in myFilesGroupedAndSorted) { &lt;tr&gt; &lt;td&gt; @fileGroup.Key &lt;/td&gt; &lt;td&gt; @if (Mp3 is not null) { &lt;span @onclick=&quot;() =&gt; PlayAudio(Mp3.Url)&quot; class=&quot;text-primary oi oi-play-circle me-2&quot; aria-hidden=&quot;true&quot; role=&quot;button&quot;&gt; &lt;/span&gt; } @if (Text is not null) { &lt;span @onclick=&quot;() =&gt; openTextFile(Text)&quot; &gt;&lt;button&gt;Open&lt;/button&gt; &lt;/span&gt; } &lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; @code { List&lt;TextFile&gt; textList = new(); readonly string audioFolderName = &quot;textFiles&quot;; public IGrouping&lt;string, TextFile&gt; fileGroup { get; set; } = default!; TextFile? Text =&gt; fileGroup.FirstOrDefault(file =&gt; Path.GetExtension(file.Path).ToLower() == &quot;txt&quot;); TextFile? Mp3 =&gt; fileGroup.FirstOrDefault(file =&gt; Path.GetExtension(file.Path).ToLower() == &quot;mp3&quot;); protected override void OnInitialized() { var path = $&quot;{env.WebRootPath}\\{audioFolderName}\\&quot;; var files = new DirectoryInfo(path).GetFiles(); foreach (var file in files) { textList.Add(new TextFile { Name = file.Name, Url = $&quot;/textFiles/{file.Name}&quot;, Path = file.FullName }); } } IEnumerable&lt;IGrouping&lt;string, TextFile&gt;&gt; myFilesGroupedAndSorted =&gt; textList.GroupBy(file =&gt; GetPathWithoutExtension(file.Path)) .OrderBy(group =&gt; group.Key); private string GetPathWithoutExtension(string path) { return System.IO.Path.ChangeExtension(path, null); } private string audioUrl { get; set; } private void PlayAudio(string url) { audioUrl = url; InvokeAsync(StateHasChanged); } List&lt;EditTextFiles&gt; items = new(); public void openTextFile(TextFile text){ } } </code></pre>
[ { "answer_id": 74521294, "author": "Brian Parker", "author_id": 1492496, "author_profile": "https://Stackoverflow.com/users/1492496", "pm_score": 2, "selected": true, "text": "Linq GroupBy @foreach(var fileGroup in myFilesGroupedAndSorted)\n{\n <h3>@fileGroup.Key</h3>\n @foreach(var file in fileGroup.OrderBy( file => file.Path))\n {\n <div>@file.Path</div>\n }\n}\n\n@code {\n // without access to your folder I generated random data.\n List<TextFile> myList = new List<TextFile>\n {\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile1.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile2.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile3.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile4.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile5.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile6.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile1.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile2.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile3.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile4.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile5.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile6.mp3\", Url = \"\" },\n };\n\n\n IEnumerable<IGrouping<string, TextFile>> myFilesGroupedAndSorted\n => myList.GroupBy(file => GetPathWithoutExtension(file.Path))\n .OrderBy(group => group.Key);\n\n private string GetPathWithoutExtension(string path)\n {\n return System.IO.Path.ChangeExtension(path, null);\n }\n}\n IGrouping<string, TextFile> Mp3.Razor <tr>\n <td>\n @FileGroup.Key\n </td>\n <td>\n @if (Mp3 is not null)\n {\n <span @onclick=\"() => PlayAudio(Mp3.Url)\"\n class=\"text-primary oi oi-play-circle me-2\" aria-hidden=\"true\" role=\"button\">\n </span>\n <span @onclick=\"() => DeleteAudio(FileGroup.Key)\"\n class=\"text-danger oi oi-trash\" aria-hidden=\"true\" role=\"button\">\n </span>\n }\n @if (Text is not null)\n {\n <span @onclick=\"() => openTextFile(Text)\">\n <button>Open</button>\n </span>\n }\n </td>\n</tr>\n@code {\n [Parameter]\n public IGrouping<string, TextFile> FileGroup { get; set; } = default!;\n\n TextFile? Text => FileGroup.FirstOrDefault(file => Path.GetExtension(file.Path).ToLower() == \"txt\");\n TextFile? Mp3 => FileGroup.FirstOrDefault(file => Path.GetExtension(file.Path).ToLower() == \"mp3\");\n}\n ...\n <tbody>\n @foreach(var fileGroup in myFilesGroupedAndSorted)\n {\n <Mp3 FileGroup=fileGroup /> \n }\n </tbody>\n...\n" }, { "answer_id": 74521367, "author": "Dialecticus", "author_id": 395718, "author_profile": "https://Stackoverflow.com/users/395718", "pm_score": 0, "selected": false, "text": "bool HasMp3 bool HasTxt Where var files = new DirectoryInfo(path).GetFiles();\n\ntextList.AddRange(files\n .GroupBy(c => Path.ChangeExtension(c.Name, null))\n .Select(g => new TextFile() {\n Name = g.Key,\n Url = $\"/textFiles/{g.Key}\",\n HasMp3 = g.Any(c => Path.GetExtension(c) == \".mp3\"),\n HasTxt = g.Any(c => Path.GetExtension(c) == \".txt\"),\n }));\n Url" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20373344/" ]
74,519,459
<p>language: Python 3.7.0 mysql-connector-python==8.0.31</p> <p>I'm working on a website and have just implemented a database. The response I'm getting from the database looks like this:</p> <pre><code>[('indigo', 'admin')] </code></pre> <p>How do I extract the two values from the tuple in a list and convert it to a list only?</p> <p><strong>Expected output:</strong></p> <pre><code>[&quot;indigo&quot;, &quot;admin&quot;] </code></pre> <p>Thanks,</p> <p>indigo</p>
[ { "answer_id": 74521294, "author": "Brian Parker", "author_id": 1492496, "author_profile": "https://Stackoverflow.com/users/1492496", "pm_score": 2, "selected": true, "text": "Linq GroupBy @foreach(var fileGroup in myFilesGroupedAndSorted)\n{\n <h3>@fileGroup.Key</h3>\n @foreach(var file in fileGroup.OrderBy( file => file.Path))\n {\n <div>@file.Path</div>\n }\n}\n\n@code {\n // without access to your folder I generated random data.\n List<TextFile> myList = new List<TextFile>\n {\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile1.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile2.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile3.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile4.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile5.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile6.txt\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile1.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile2.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile3.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile4.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile5.mp3\", Url = \"\" },\n new TextFile { Name = \"\", Path = \"some-path\\\\SomeFile6.mp3\", Url = \"\" },\n };\n\n\n IEnumerable<IGrouping<string, TextFile>> myFilesGroupedAndSorted\n => myList.GroupBy(file => GetPathWithoutExtension(file.Path))\n .OrderBy(group => group.Key);\n\n private string GetPathWithoutExtension(string path)\n {\n return System.IO.Path.ChangeExtension(path, null);\n }\n}\n IGrouping<string, TextFile> Mp3.Razor <tr>\n <td>\n @FileGroup.Key\n </td>\n <td>\n @if (Mp3 is not null)\n {\n <span @onclick=\"() => PlayAudio(Mp3.Url)\"\n class=\"text-primary oi oi-play-circle me-2\" aria-hidden=\"true\" role=\"button\">\n </span>\n <span @onclick=\"() => DeleteAudio(FileGroup.Key)\"\n class=\"text-danger oi oi-trash\" aria-hidden=\"true\" role=\"button\">\n </span>\n }\n @if (Text is not null)\n {\n <span @onclick=\"() => openTextFile(Text)\">\n <button>Open</button>\n </span>\n }\n </td>\n</tr>\n@code {\n [Parameter]\n public IGrouping<string, TextFile> FileGroup { get; set; } = default!;\n\n TextFile? Text => FileGroup.FirstOrDefault(file => Path.GetExtension(file.Path).ToLower() == \"txt\");\n TextFile? Mp3 => FileGroup.FirstOrDefault(file => Path.GetExtension(file.Path).ToLower() == \"mp3\");\n}\n ...\n <tbody>\n @foreach(var fileGroup in myFilesGroupedAndSorted)\n {\n <Mp3 FileGroup=fileGroup /> \n }\n </tbody>\n...\n" }, { "answer_id": 74521367, "author": "Dialecticus", "author_id": 395718, "author_profile": "https://Stackoverflow.com/users/395718", "pm_score": 0, "selected": false, "text": "bool HasMp3 bool HasTxt Where var files = new DirectoryInfo(path).GetFiles();\n\ntextList.AddRange(files\n .GroupBy(c => Path.ChangeExtension(c.Name, null))\n .Select(g => new TextFile() {\n Name = g.Key,\n Url = $\"/textFiles/{g.Key}\",\n HasMp3 = g.Any(c => Path.GetExtension(c) == \".mp3\"),\n HasTxt = g.Any(c => Path.GetExtension(c) == \".txt\"),\n }));\n Url" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12908643/" ]
74,519,478
<p>The number n^k is entered, I need to output the value in a character array-string</p> <p>I have no idea how to write the code</p>
[ { "answer_id": 74519605, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n\nint main(void) {\n int n;\n printf(\"Enter N:\\n\");\n scanf(\"%d\", &n);\n \n int k;\n printf(\"Enter K:\\n\");\n scanf(\"%d\", &k);\n \n int result = pow(n,k);\n char text[100];\n sprintf(text, \"%d\", result);\n \n printf(\"The Answer is %s\\n\", text);\n\n return 0;\n}\n" }, { "answer_id": 74519658, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 1, "selected": true, "text": "pow int main()\n{\n int n, k;\n scanf(\"%d%d\", &n, &k);\n char* s = (char*)malloc(1000000);\n int i, j, len, temp, carry;\n s[0] = '1';\n len = 1;\n for (i = 1; i <= k; i++)\n {\n carry = 0;\n for (j = 0; j < len; j++)\n {\n temp = (s[j] - '0') * n + carry;\n s[j] = temp % 10 + '0';\n carry = temp / 10;\n }\n while (carry > 0)\n {\n s[len] = carry % 10 + '0';\n carry /= 10;\n len++;\n }\n }\n for (i = len - 1; i >= 0; i--)\n printf(\"%c\", s[i]);\n return 0;\n}\n n k str length void pow(int n, int k, char* str, int* length)\n{\n int i, j, carry, temp;\n str[0] = '1';\n *length = 1;\n for (i = 0; i < k; i++)\n {\n carry = 0;\n for (j = 0; j < *length; j++)\n {\n temp = (str[j] - '0') * n + carry;\n str[j] = temp % 10 + '0';\n carry = temp / 10;\n }\n while (carry)\n {\n str[*length] = carry % 10 + '0';\n carry /= 10;\n (*length)++;\n }\n }\n // reverse\n for (i = 0; i < *length / 2; i++)\n {\n temp = str[i];\n str[i] = str[*length - i - 1];\n str[*length - i - 1] = temp;\n }\n str[*length] = '\\0';\n}\nint main()\n{\n int n, k;\n scanf(\"%d %d\", &n, &k);\n char str[100000];\n int length;\n pow(n, k, str, &length);\n printf(\"%s\", str);\n return 0;\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20417945/" ]
74,519,480
<p>I want to sum the Amount in my Bill Table via dates and report as daily sales</p> <p>The table columns are Client Name, Amount, BDate This is what I have tried</p> <pre><code> Dim query = &quot;SELECT SUM(Amount)as sales FROM BillTbl where [BDate] = ? &quot; Dim conkey As New SqlConnection(con) Dim cmd = New SqlCommand(query, conkey) cmd.Parameters.AddWithValue(&quot;@BDate&quot;, Now.ToString(&quot;MM/dd/yyyy&quot;)) conkey.Open() Dim total As Double = Convert.ToDouble(cmd.ExecuteScalar()) check.Text = total.ToString conkey.Close() </code></pre>
[ { "answer_id": 74520187, "author": "SWR", "author_id": 20533163, "author_profile": "https://Stackoverflow.com/users/20533163", "pm_score": 1, "selected": false, "text": "Sales ClientName SELECT [BDate], SUM([Amount]) AS Sales FROM [BillTbl] GROUP BY [BDate]\n BDate SELECT CAST([BDate] AS DATE), SUM([Amount]) AS [Sales] FROM [BillTbl] GROUP BY CAST([BDate] AS DATE)\n SELECT CONVERT(VARCHAR(10), [BDate], 102), SUM([Amount]) AS [Sales] FROM [BillTbl] GROUP BY CONVERT(VARCHAR(10), [BDate], 102)\n" }, { "answer_id": 74522830, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": true, "text": "BDate Date DateTime varchar Dim query = \"SELECT SUM(Amount)as sales FROM BillTbl where [BDate] = cast(current_timestamp as Date)\"\n\nUsing conkey As New SqlConnection(con), _\n cmd As New SqlCommand(query, con)\n\n conkey.Open()\n Dim total As Decimal = Convert.ToDecimal(cmd.ExecuteScalar())\nEnd Using\n Dim query = \"SELECT SUM(Amount)as sales FROM BillTbl where [BDate] = @BDate\"\n\nUsing conkey As New SqlConnection(con), _\n cmd As New SqlCommand(query, con)\n\n ' Always choose an SqlDbType and Length to match the database column\n cmd.Parameters.Add(\"@BDate\", SqlDbType.Date).Value = DateTime.Today\n conkey.Open()\n Dim total As Decimal = Convert.ToDecimal(cmd.ExecuteScalar())\nEnd Using\n AddWithValue() .Close() Using .Close() Using MM/dd/yyyy total" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20554111/" ]
74,519,508
<p>I have a simple database structure:</p> <pre><code>CREATE TABLE dbo.Report ( ID int NOT NULL, Name varchar(50) NOT NULL ) CREATE TABLE dbo.ReportText ( ID int NOT NULL, Content varchar(max) NOT NULL, FK_ReportID int NOT NULL, FK_FontID int NOT NULL ) CREATE TABLE dbo.Font ( ID int NOT NULL, Name varchar(100) NOT NULL, FK_ReportID int NOT NULL ) </code></pre> <p>In plain English:</p> <ul> <li>A <code>Report</code> contains multiple <code>ReportText</code> rows</li> <li>Each <code>ReportText</code> has a <code>Font</code></li> <li>Each <code>Font</code> is restricted to a <code>Report</code> <ul> <li>i.e. The ReportTexts for ReportA cannot use any of the Fonts for ReportB</li> </ul> </li> </ul> <p>I can enforce everything with simple foreign keys, except that last requirement. I can have:</p> <ul> <li>a foreign key from <code>Report.ID</code> to <code>ReportText.FK_ReportID</code></li> <li>a foreign key from <code>Report.ID</code> to <code>Font.FK_ReportID</code></li> </ul> <p>...but I need a third relationship that will prevent a <code>ReportText</code> from selecting a <code>Font</code> for a report ID different from its own <code>FK_ReportID</code>.</p> <p>Is this possible or is there a problem with my schema?</p>
[ { "answer_id": 74520249, "author": "Giovanni Luisotto", "author_id": 9614903, "author_profile": "https://Stackoverflow.com/users/9614903", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION dbo.CheckFontUsage (@ReportID int, @FontID int)\nRETURNS bit\nAS\nBEGIN\n DECLARE @AlreadyUsed bit;\n SELECT @AlreadyUsed = IIF(COUNT(*) > 0,1,0) FROM dbo.ReportText WHERE FK_ReportID <> @ReportID AND FK_FontID = @FontID\n\n RETURN(@AlreadyUsed);\nEND\n\nGO\n\nALTER TABLE dbo.ReportText \nADD CONSTRAINT CK_YourConstrName CHECK (dbo.CheckFontUsage(FK_ReportID,FK_FontID) = 0)\nGO\n" }, { "answer_id": 74520952, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 1, "selected": false, "text": "/* For testing we may want to drop these\nDROP TABLE IF EXISTS ReportText;\nDROP TABLE IF EXISTS FontsReports\nDROP TABLE IF EXISTS Reports;\nDROP TABLE IF EXISTS Fonts;\n*/\n\nCREATE TABLE Reports (ID INT IDENTITY PRIMARY KEY, Name VARCHAR(50) NOT NULL);\nCREATE TABLE Fonts (ID INT PRIMARY KEY IDENTITY, Name NVARCHAR(100))\n\nCREATE TABLE FontsReports (FontID INT NOT NULL FOREIGN KEY REFERENCES Fonts(ID), \n ReportID INT NOT NULL FOREIGN KEY REFERENCES Reports(ID));\nCREATE TABLE ReportText (ID INT IDENTITY, Content NVARCHAR(MAX) NOT NULL, ReportID INT FOREIGN KEY REFERENCES Reports(ID), \n FontID INT FOREIGN KEY REFERENCES Fonts(ID));\nINSERT INTO Reports (Name) VALUES \n('Allow Font one'),('Allow Font two'),('Allow font one and two');\n\nINSERT INTO Fonts (NAME) VALUES \n('Font one'),('Font two'),('Font three');\n\nINSERT INTO FontsReports (FontID, ReportID) VALUES\n(1,1),(1,3),(2,2),(2,3);\n\nALTER TABLE FontsReports ADD PRIMARY KEY(FontID, ReportID)\n\nALTER TABLE FontsReports WITH CHECK ADD CONSTRAINT AllowedFontAndReport \nFOREIGN KEY(FontID) REFERENCES Fonts(ID), \nFOREIGN KEY(ReportID) REFERENCES Reports(ID)\n\nALTER TABLE ReportText WITH CHECK ADD CONSTRAINT AllowedFontReport \nFOREIGN KEY(FontID, ReportID) REFERENCES FontsReports (FontID, ReportID)\n\nINSERT INTO ReportText (Content, ReportID, FontID) VALUES \n('Something that works.', 1, 1)\n\nINSERT INTO ReportText (Content, ReportID, FontID) VALUES \n('Something that fails', 2, 1)\n\n" }, { "answer_id": 74531339, "author": "Dan Guzman", "author_id": 3711162, "author_profile": "https://Stackoverflow.com/users/3711162", "pm_score": 2, "selected": true, "text": "Font ID FK_ReportID ReportText CREATE TABLE dbo.Report\n(\n ID int NOT NULL CONSTRAINT PK_Report PRIMARY KEY,\n Name varchar(50) NOT NULL\n);\n\nCREATE TABLE dbo.Font\n(\n ID int NOT NULL CONSTRAINT PK_Font PRIMARY KEY,\n Name varchar(100) NOT NULL,\n FK_ReportID int NOT NULL\n CONSTRAINT FK_Font_Report FOREIGN KEY REFERENCES dbo.Report(ID),\n CONSTRAINT AK_Font_ID_FK_ReportID UNIQUE(ID, FK_ReportID)\n);\n\nCREATE TABLE dbo.ReportText\n(\n ID int NOT NULL CONSTRAINT PK_ReportText PRIMARY KEY,\n Content varchar(max) NOT NULL,\n FK_ReportID int NOT NULL CONSTRAINT FK_ReportText_Report FOREIGN KEY REFERENCES dbo.Report(ID),\n FK_FontID int NOT NULL,\n CONSTRAINT FK_ReportText_Font FOREIGN KEY (FK_FontID, FK_ReportID) REFERENCES dbo.Font(ID, FK_ReportID),\n);\n\nINSERT INTO dbo.Report VALUES(1,'Report1');\nINSERT INTO dbo.Report VALUES(2,'Report2');\n\nINSERT INTO dbo.Font VALUES(1,'Font1',1);\nINSERT INTO dbo.Font VALUES(2,'Font2',1);\nINSERT INTO dbo.Font VALUES(3,'Font3',2);\n\nINSERT INTO dbo.ReportText VALUES(1,'content1',1,1);\nINSERT INTO dbo.ReportText VALUES(2,'content2',1,1);\nINSERT INTO dbo.ReportText VALUES(3,'content3',1,2);\nINSERT INTO dbo.ReportText VALUES(4,'content1',2,3);\n\n--this fails because font 3 is not valid for report 1\nINSERT INTO dbo.ReportText VALUES(5,'content4',1,3);\n--this fails because font 1 is not valid for report 2\nINSERT INTO dbo.ReportText VALUES(5,'content2',2,1);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5819046/" ]
74,519,530
<p>I am attempting to conditionally render items of an array from <a href="https://jsonplaceholder.typicode.com/users" rel="nofollow noreferrer">json placeholder</a>, by using a ternary operator to establish if an array has any items, then map through it, and return the items. If not, return a message indicating so. I've searched to see if/where my syntax is wrong to no avail.</p> <p>Here's what I have:</p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import { fetchUsers } from &quot;../../lib/functions&quot;; const Users = () =&gt; { const [users, setUsers] = useState([]); useEffect(() =&gt; { fetchUsers().then(res =&gt; setUsers(res.data)) }, []); return ( &lt;div className=&quot;users&quot;&gt; &lt;h1&gt;Users&lt;/h1&gt; {users.length ? users.map((user) =&gt; { (&lt;div key=&quot;id&quot;&gt; &lt;h4&gt;{users.name}&lt;/h4&gt; &lt;h5&gt;{users.email}&lt;/h5&gt; &lt;h6&gt;{users.username}&lt;/h6&gt; &lt;p&gt;{users.address}&lt;/p&gt; &lt;/div&gt;) : ( &lt;div&gt; &lt;p&gt;User not found.&lt;/p&gt; &lt;/div&gt; )})} &lt;/div&gt; ); } export default Users; </code></pre> <p>It's throwing me this error:</p> <p>ERROR in [eslint] src/components/users/Users.js Line 19:23: Parsing error: Missing semicolon. (19:23)</p> <p>webpack compiled with 2 errors</p>
[ { "answer_id": 74520249, "author": "Giovanni Luisotto", "author_id": 9614903, "author_profile": "https://Stackoverflow.com/users/9614903", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION dbo.CheckFontUsage (@ReportID int, @FontID int)\nRETURNS bit\nAS\nBEGIN\n DECLARE @AlreadyUsed bit;\n SELECT @AlreadyUsed = IIF(COUNT(*) > 0,1,0) FROM dbo.ReportText WHERE FK_ReportID <> @ReportID AND FK_FontID = @FontID\n\n RETURN(@AlreadyUsed);\nEND\n\nGO\n\nALTER TABLE dbo.ReportText \nADD CONSTRAINT CK_YourConstrName CHECK (dbo.CheckFontUsage(FK_ReportID,FK_FontID) = 0)\nGO\n" }, { "answer_id": 74520952, "author": "Patrick Hurst", "author_id": 18522514, "author_profile": "https://Stackoverflow.com/users/18522514", "pm_score": 1, "selected": false, "text": "/* For testing we may want to drop these\nDROP TABLE IF EXISTS ReportText;\nDROP TABLE IF EXISTS FontsReports\nDROP TABLE IF EXISTS Reports;\nDROP TABLE IF EXISTS Fonts;\n*/\n\nCREATE TABLE Reports (ID INT IDENTITY PRIMARY KEY, Name VARCHAR(50) NOT NULL);\nCREATE TABLE Fonts (ID INT PRIMARY KEY IDENTITY, Name NVARCHAR(100))\n\nCREATE TABLE FontsReports (FontID INT NOT NULL FOREIGN KEY REFERENCES Fonts(ID), \n ReportID INT NOT NULL FOREIGN KEY REFERENCES Reports(ID));\nCREATE TABLE ReportText (ID INT IDENTITY, Content NVARCHAR(MAX) NOT NULL, ReportID INT FOREIGN KEY REFERENCES Reports(ID), \n FontID INT FOREIGN KEY REFERENCES Fonts(ID));\nINSERT INTO Reports (Name) VALUES \n('Allow Font one'),('Allow Font two'),('Allow font one and two');\n\nINSERT INTO Fonts (NAME) VALUES \n('Font one'),('Font two'),('Font three');\n\nINSERT INTO FontsReports (FontID, ReportID) VALUES\n(1,1),(1,3),(2,2),(2,3);\n\nALTER TABLE FontsReports ADD PRIMARY KEY(FontID, ReportID)\n\nALTER TABLE FontsReports WITH CHECK ADD CONSTRAINT AllowedFontAndReport \nFOREIGN KEY(FontID) REFERENCES Fonts(ID), \nFOREIGN KEY(ReportID) REFERENCES Reports(ID)\n\nALTER TABLE ReportText WITH CHECK ADD CONSTRAINT AllowedFontReport \nFOREIGN KEY(FontID, ReportID) REFERENCES FontsReports (FontID, ReportID)\n\nINSERT INTO ReportText (Content, ReportID, FontID) VALUES \n('Something that works.', 1, 1)\n\nINSERT INTO ReportText (Content, ReportID, FontID) VALUES \n('Something that fails', 2, 1)\n\n" }, { "answer_id": 74531339, "author": "Dan Guzman", "author_id": 3711162, "author_profile": "https://Stackoverflow.com/users/3711162", "pm_score": 2, "selected": true, "text": "Font ID FK_ReportID ReportText CREATE TABLE dbo.Report\n(\n ID int NOT NULL CONSTRAINT PK_Report PRIMARY KEY,\n Name varchar(50) NOT NULL\n);\n\nCREATE TABLE dbo.Font\n(\n ID int NOT NULL CONSTRAINT PK_Font PRIMARY KEY,\n Name varchar(100) NOT NULL,\n FK_ReportID int NOT NULL\n CONSTRAINT FK_Font_Report FOREIGN KEY REFERENCES dbo.Report(ID),\n CONSTRAINT AK_Font_ID_FK_ReportID UNIQUE(ID, FK_ReportID)\n);\n\nCREATE TABLE dbo.ReportText\n(\n ID int NOT NULL CONSTRAINT PK_ReportText PRIMARY KEY,\n Content varchar(max) NOT NULL,\n FK_ReportID int NOT NULL CONSTRAINT FK_ReportText_Report FOREIGN KEY REFERENCES dbo.Report(ID),\n FK_FontID int NOT NULL,\n CONSTRAINT FK_ReportText_Font FOREIGN KEY (FK_FontID, FK_ReportID) REFERENCES dbo.Font(ID, FK_ReportID),\n);\n\nINSERT INTO dbo.Report VALUES(1,'Report1');\nINSERT INTO dbo.Report VALUES(2,'Report2');\n\nINSERT INTO dbo.Font VALUES(1,'Font1',1);\nINSERT INTO dbo.Font VALUES(2,'Font2',1);\nINSERT INTO dbo.Font VALUES(3,'Font3',2);\n\nINSERT INTO dbo.ReportText VALUES(1,'content1',1,1);\nINSERT INTO dbo.ReportText VALUES(2,'content2',1,1);\nINSERT INTO dbo.ReportText VALUES(3,'content3',1,2);\nINSERT INTO dbo.ReportText VALUES(4,'content1',2,3);\n\n--this fails because font 3 is not valid for report 1\nINSERT INTO dbo.ReportText VALUES(5,'content4',1,3);\n--this fails because font 1 is not valid for report 2\nINSERT INTO dbo.ReportText VALUES(5,'content2',2,1);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19433155/" ]
74,519,531
<p>So, im trying to make a script that takes code from a pastebin post and runs it. But, for some reason it doesnt run the code. I dont know why. Could someone explain why this wont work so i can fix the issue?</p> <p>I tried: (dont mind the imports im gonna use those for later)</p> <pre><code>import os from json import loads, dumps from base64 import b64decode from urllib.request import Request, urlopen from subprocess import Popen, PIPE def get_code(): test = 'None' try: test = urlopen(Request('https://pastebin.com/raw/4dnZntN3')).read().decode() except: pass return test test = get_code() def main(): test main() </code></pre> <p>The output is empty, and no errors.</p>
[ { "answer_id": 74519614, "author": "vineet singh", "author_id": 12623612, "author_profile": "https://Stackoverflow.com/users/12623612", "pm_score": 0, "selected": false, "text": "def main():\n exec(test)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20463334/" ]
74,519,555
<p>I am trying to convert python dataframe into column headers. I am using transpose function but results are not as expected. Which function can be used to accomplish the results as given below?</p> <p>data is:</p> <pre><code>Year 2020 Month SEPTEMBER Filed Date 29-11-2020 Year 2022 Month JULY Filed Date 20-08-2022 Year 2022 Month APRIL Filed Date 20-05-2022 Year 2017 Month AUGUST Filed Date 21-09-2017 Year 2018 Month JULY Filed Date 03-02-2019 Year 2021 Month MAY Filed Date 22-06-2021 Year 2017 Month DECEMBER Filed Date 19-01-2018 Year 2018 Month MAY Filed Date 03-02-2019 Year 2019 Month MARCH Filed Date 28-09-2019 </code></pre> <p>and convert it into:</p> <pre><code>Year Month Filed Date 2020 September 29-11-2020 2022 July 20-08-2022 </code></pre>
[ { "answer_id": 74519904, "author": "Sam Wittwicky", "author_id": 20546479, "author_profile": "https://Stackoverflow.com/users/20546479", "pm_score": 0, "selected": false, "text": "Year 2020\nMonth SEPTEMBER\nFiled Date 29-11-2020\nYear 2022\nMonth JULY\nFiled Date 20-08-2022\nYear 2022\nMonth APRIL\nFiled Date 20-05-2022\nYear 2017\nMonth AUGUST\nFiled Date 21-09-2017\nYear 2018\nMonth JULY\nFiled Date 03-02-2019\nYear 2021\nMonth MAY\nFiled Date 22-06-2021\nYear 2017\nMonth DECEMBER\nFiled Date 19-01-2018\nYear 2018\nMonth MAY\nFiled Date 03-02-2019\nYear 2019\nMonth MARCH\nFiled Date 28-09-2019\n df=pd.DataFrame()\nfor i in range(0,len(df1),3):\n df= df.append(df1.pivot(columns='A', values='B', index=None).bfill(axis = 0).iloc[i])\ndf.reset_index(drop=True, inplace=True)\nprint(df)\n A Filed Date Month Year\n0 29-11-2020 SEPTEMBER 2020\n1 20-08-2022 JULY 2022\n2 20-05-2022 APRIL 2022\n3 21-09-2017 AUGUST 2017\n4 03-02-2019 JULY 2018\n" }, { "answer_id": 74520576, "author": "SomeDude", "author_id": 1410303, "author_profile": "https://Stackoverflow.com/users/1410303", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame(\n [df1.iloc[i:i+3][1].tolist() for i in range(0, len(df1), 3)],\n columns=df1.iloc[0:3][0].tolist(),\n)\n Year Month Filed\n0 2020 SEPTEMBER Date 29-11-2020\n1 2022 JULY Date 20-08-2022\n2 2022 APRIL Date 20-05-2022\n3 2017 AUGUST Date 21-09-2017\n4 2018 JULY Date 03-02-2019\n5 2021 MAY Date 22-06-2021\n6 2017 DECEMBER Date 19-01-2018\n7 2018 MAY Date 03-02-2019\n8 2019 MARCH Date 28-09-2019\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20546479/" ]
74,519,566
<p>I have a player where you move with WASD. Currently, moving forwards and backwards has the same speed, but walking backwards and sideways should be slower.</p> <pre><code>float x = Input.GetAxis(&quot;Horizontal&quot;); float z = Input.GetAxis(&quot;Vertical&quot;); Vector3 move = transform.right * x + transform.forward * z; if (move.magnitude &gt; 1) move /= move.magnitude; controller.Move(move * speed * Time.deltaTime); if (Input.GetKey(KeyCode.LeftShift)) { speed = sprintSpeed; } else { speed = walkSpeed; } </code></pre> <p>The only solution I have would be to add if statements for W, A, S and D keys and reduce their speeds individually based on the users key input, but I'm not sure if that's a bad way to implement it.</p>
[ { "answer_id": 74519904, "author": "Sam Wittwicky", "author_id": 20546479, "author_profile": "https://Stackoverflow.com/users/20546479", "pm_score": 0, "selected": false, "text": "Year 2020\nMonth SEPTEMBER\nFiled Date 29-11-2020\nYear 2022\nMonth JULY\nFiled Date 20-08-2022\nYear 2022\nMonth APRIL\nFiled Date 20-05-2022\nYear 2017\nMonth AUGUST\nFiled Date 21-09-2017\nYear 2018\nMonth JULY\nFiled Date 03-02-2019\nYear 2021\nMonth MAY\nFiled Date 22-06-2021\nYear 2017\nMonth DECEMBER\nFiled Date 19-01-2018\nYear 2018\nMonth MAY\nFiled Date 03-02-2019\nYear 2019\nMonth MARCH\nFiled Date 28-09-2019\n df=pd.DataFrame()\nfor i in range(0,len(df1),3):\n df= df.append(df1.pivot(columns='A', values='B', index=None).bfill(axis = 0).iloc[i])\ndf.reset_index(drop=True, inplace=True)\nprint(df)\n A Filed Date Month Year\n0 29-11-2020 SEPTEMBER 2020\n1 20-08-2022 JULY 2022\n2 20-05-2022 APRIL 2022\n3 21-09-2017 AUGUST 2017\n4 03-02-2019 JULY 2018\n" }, { "answer_id": 74520576, "author": "SomeDude", "author_id": 1410303, "author_profile": "https://Stackoverflow.com/users/1410303", "pm_score": 1, "selected": false, "text": "df = pd.DataFrame(\n [df1.iloc[i:i+3][1].tolist() for i in range(0, len(df1), 3)],\n columns=df1.iloc[0:3][0].tolist(),\n)\n Year Month Filed\n0 2020 SEPTEMBER Date 29-11-2020\n1 2022 JULY Date 20-08-2022\n2 2022 APRIL Date 20-05-2022\n3 2017 AUGUST Date 21-09-2017\n4 2018 JULY Date 03-02-2019\n5 2021 MAY Date 22-06-2021\n6 2017 DECEMBER Date 19-01-2018\n7 2018 MAY Date 03-02-2019\n8 2019 MARCH Date 28-09-2019\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20413330/" ]
74,519,689
<p>I need custom response to all my controllers, how to make this real?</p> <p>I have format like this: <strong>Success response</strong></p> <pre><code>{ status: string, code: number, message: string data: object | array | any, request: { url: string, method: string } } </code></pre> <p><strong>Exception response</strong></p> <pre><code>{ status: string, code: number, message: string error: object | array | any, request: { url: string, method: string } } </code></pre> <p>How can I implement it in Nestjs?</p>
[ { "answer_id": 74519746, "author": "fonzane", "author_id": 8863088, "author_profile": "https://Stackoverflow.com/users/8863088", "pm_score": 1, "selected": false, "text": "@Get('path')\nasync getResponse() {\n if(success) {\n return {\n status: string,\n code: number,\n message: string\n data: object | array | any,\n request: {\n url: string,\n method: string\n }\n } else if (error) {\n return {\n status: string,\n code: number,\n message: string\n error: object | array | any,\n request: {\n url: string,\n method: string\n }\n }\n }\n export interface SuccessResponse = {\n status: string,\n code: number,\n message: string\n data: object | array | any,\n request: {\n url: string,\n method: string\n }\n}\n\nexport type ErrorResponse = {\n status: string,\n code: number,\n message: string\n error: object | array | any,\n request: {\n url: string,\n method: string\n }\n}\n @Get('path')\nasync getResponse(): SuccessResponse | ErrorResponse { ... }\n" }, { "answer_id": 74521904, "author": "Jay McDoniel", "author_id": 9576186, "author_profile": "https://Stackoverflow.com/users/9576186", "pm_score": 0, "selected": false, "text": "ArgumentHost ExecutionContext request response" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7666874/" ]
74,519,728
<p>I'm a true beginner with Terraform, and here is my problem:</p> <ul> <li>I need to create multiple objects using the same resource of this type:</li> </ul> <pre><code>resource &quot;jamf_smartComputerGroup&quot; &quot;test_smart_1&quot; { name = &quot;Test Smart 1&quot; criteria { priority = 0 name = &quot;UDID&quot; search_type = &quot;is&quot; search_value = &quot;FAKE-UDID-THAT-ALSO-DOES-NOT-EXIST&quot; } criteria { priority = 1 name = &quot;UDID&quot; search_type = &quot;is not&quot; search_value = &quot;FAKE-UDID-THAT-DOES-NOT-EXIST-LIKE-REALLY&quot; } } </code></pre> <ul> <li>IMPORTANT: this resource can have zero or more criterias!</li> <li>I have created the <code>variables.tf</code> and <code>terraform.vartf</code> files as follow:</li> </ul> <p><strong><code>variables.tf</code></strong></p> <pre><code>variable &quot;jamf_smartComputerGroup_list&quot; { type = list(object({ SMCG_NAME = string SMCG_CRITERIA = list(object({ SMCG_CRITERIA_PRIORITY = number SMCG_CRITERIA_NAME = string SMCG_CRITERIA_TYPE = string SMCG_CRITERIA_VALUE = string })) })) } </code></pre> <p><strong><code>terraform.vartf</code></strong></p> <pre><code>jamf_smartComputerGroup_list = [ { SMCG_NAME = &quot;smcg_1&quot; SMCG_CRITERIA = [] # THIS OBJECT HAS ZERO CRITERIA }, { SMCG_NAME = &quot;smcg_2&quot; SMCG_CRITERIA = [ # THIS OBJECT HAS ONE CRITERIA { SMCG_CRITERIA_PRIORITY = 0 SMCG_CRITERIA_NAME = &quot;crit&quot; SMCG_CRITERIA_TYPE = &quot;is not&quot; SMCG_CRITERIA_VALUE = &quot;false&quot; } ] }, { SMCG_NAME = &quot;smcg_3&quot; SMCG_CRITERIA = [ # THIS OBJECT HAS TWO CRITERIAS { SMCG_CRITERIA_PRIORITY = 0 SMCG_CRITERIA_NAME = &quot;crit 1&quot; SMCG_CRITERIA_TYPE = &quot;contains&quot; SMCG_CRITERIA_VALUE = &quot;foo&quot; }, { SMCG_CRITERIA_PRIORITY = 1 SMCG_CRITERIA_NAME = &quot;crit 2&quot; SMCG_CRITERIA_TYPE = &quot;exact match&quot; SMCG_CRITERIA_VALUE = &quot;bar&quot; } ] } ] </code></pre> <p>In the <strong><code>main.tf</code></strong> file I was able to loop through the objects, without criterias, using this:</p> <pre><code>resource &quot;jamf_smartComputerGroup&quot; &quot;default&quot; { for_each = { for idx, val in var.jamf_smartComputerGroup_list : idx =&gt; val } name = each.value.SMCG_NAME } </code></pre> <p>But and I can't find the appropriate way to determine if one or more criterias are present; and if there is one more criterias, how to loop through them. A far as I understand, I can't use two <code>for_each</code> verbs at the same time, and I can't use <code>count</code> with <code>for_each</code>.</p> <p>Any examples will be appreciated :-) !</p> <p>Regards, Emmanuel Canault</p>
[ { "answer_id": 74519746, "author": "fonzane", "author_id": 8863088, "author_profile": "https://Stackoverflow.com/users/8863088", "pm_score": 1, "selected": false, "text": "@Get('path')\nasync getResponse() {\n if(success) {\n return {\n status: string,\n code: number,\n message: string\n data: object | array | any,\n request: {\n url: string,\n method: string\n }\n } else if (error) {\n return {\n status: string,\n code: number,\n message: string\n error: object | array | any,\n request: {\n url: string,\n method: string\n }\n }\n }\n export interface SuccessResponse = {\n status: string,\n code: number,\n message: string\n data: object | array | any,\n request: {\n url: string,\n method: string\n }\n}\n\nexport type ErrorResponse = {\n status: string,\n code: number,\n message: string\n error: object | array | any,\n request: {\n url: string,\n method: string\n }\n}\n @Get('path')\nasync getResponse(): SuccessResponse | ErrorResponse { ... }\n" }, { "answer_id": 74521904, "author": "Jay McDoniel", "author_id": 9576186, "author_profile": "https://Stackoverflow.com/users/9576186", "pm_score": 0, "selected": false, "text": "ArgumentHost ExecutionContext request response" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20563161/" ]
74,519,729
<p>I'm making archives to .exe using <code>pyinstaller</code>, but I have a big problem, every time I create a file, its size multiplies, it seems that it is multiplying the libraries, does anyone know how to solve it?</p> <pre><code>1° file size: 7mb 2° file size: 52mb 3° file size: 104mb 4° file size: 207mb 5° file size: 414mb 6° file size: 828mb 7° file size: 1.656mb 8° file size: 3.312mb </code></pre> <p>I tried to rename the files, deleted <code>%tmp%</code> files</p>
[ { "answer_id": 74519746, "author": "fonzane", "author_id": 8863088, "author_profile": "https://Stackoverflow.com/users/8863088", "pm_score": 1, "selected": false, "text": "@Get('path')\nasync getResponse() {\n if(success) {\n return {\n status: string,\n code: number,\n message: string\n data: object | array | any,\n request: {\n url: string,\n method: string\n }\n } else if (error) {\n return {\n status: string,\n code: number,\n message: string\n error: object | array | any,\n request: {\n url: string,\n method: string\n }\n }\n }\n export interface SuccessResponse = {\n status: string,\n code: number,\n message: string\n data: object | array | any,\n request: {\n url: string,\n method: string\n }\n}\n\nexport type ErrorResponse = {\n status: string,\n code: number,\n message: string\n error: object | array | any,\n request: {\n url: string,\n method: string\n }\n}\n @Get('path')\nasync getResponse(): SuccessResponse | ErrorResponse { ... }\n" }, { "answer_id": 74521904, "author": "Jay McDoniel", "author_id": 9576186, "author_profile": "https://Stackoverflow.com/users/9576186", "pm_score": 0, "selected": false, "text": "ArgumentHost ExecutionContext request response" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20563396/" ]
74,519,754
<p>I'm doing CRUD operations with Laravel and I added a new input to my 'create' form, &quot;nickname&quot; but I'm getting this error: SQLSTATE[HY000]: General error: 1364 Field 'nickname' doesn't have a default value</p> <pre><code>INSERT INTO `students` ( `name`, `email`, `phone`, `password`, `updated_at`, `created_at` ) VALUES ( test, test@gmail.com, 99999999, testpassword, 2022 -11 -21 13: 20: 47, 2022 -11 -21 13: 20: 47 ) </code></pre> <p>This is my Model file:</p> <pre><code>&lt;?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Student extends Model { use HasFactory; protected $fillable = ['name','nickname','email','phone','password']; } </code></pre> <p>This is my Controller file:</p> <pre><code>use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { /** * Display a listing of the resource. * // * @return \Illuminate\Http\Response */ public function index() { $student = Student::all(); return view('index', compact('student')); } /** * Show the form for creating a new resource. * // * @return \Illuminate\Http\Response */ public function create() { return view('create'); } /** * Store a newly created resource in storage. * // * @param \Illuminate\Http\Request $request // * @return \Illuminate\Http\Response */ public function store(Request $request) { $storeData = $request-&gt;validate([ 'name' =&gt; 'required|max:255', 'name' =&gt; 'required|max:255', 'email' =&gt; 'required|max:255', 'phone' =&gt; 'required|numeric', 'password' =&gt; 'required|max:255', ]); $student = Student::create($storeData); return redirect('/students')-&gt;with('completed', 'Student has been saved!'); } /** * Display the specified resource. * // * @param int $id // * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * // * @param int $id // * @return \Illuminate\Http\Response */ public function edit($id) { $student = Student::findOrFail($id); return view('edit', compact('student')); } /** * Update the specified resource in storage. * // * @param \Illuminate\Http\Request $request // * @param int $id // * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $updateData = $request-&gt;validate([ 'name' =&gt; 'required|max:255', 'nickname' =&gt; 'required|max:255', 'email' =&gt; 'required|max:255', 'phone' =&gt; 'required|numeric', 'password' =&gt; 'required|max:255', ]); Student::whereId($id)-&gt;update($updateData); return redirect('/students')-&gt;with('completed', 'Student has been updated'); } /** * Remove the specified resource from storage. * // * @param int $id // * @return \Illuminate\Http\Response */ public function destroy($id) { $student = Student::findOrFail($id); $student-&gt;delete(); return redirect('/students')-&gt;with('completed', 'Student has been deleted'); } } </code></pre> <p>When I remove the required option in nickname it works but I have to do this.</p>
[ { "answer_id": 74519792, "author": "Evans Benedict", "author_id": 20560614, "author_profile": "https://Stackoverflow.com/users/20560614", "pm_score": 1, "selected": false, "text": "nickname nickname nickname nickname INSERT INTO\n `students` (\n `name`,\n `nickname`,\n `email`,\n `phone`,\n `password`,\n `updated_at`,\n `created_at`\n )\nVALUES\n (\n test,\n nickname\n test@gmail.com,\n 99999999,\n testpassword,\n 2022 -11 -21 13: 20: 47,\n 2022 -11 -21 13: 20: 47\n )\n" }, { "answer_id": 74519905, "author": "ilgar", "author_id": 16568985, "author_profile": "https://Stackoverflow.com/users/16568985", "pm_score": 0, "selected": false, "text": " public function store(Request $request)\n{\n $storeData = $request->validate([\n 'name' => 'required|max:255',\n 'name' => 'required|max:255',\n 'email' => 'required|max:255',\n 'phone' => 'required|numeric',\n 'password' => 'required|max:255',\n ]);\n public function store(Request $request)\n{\n $storeData = $request->validate([\n 'name' => 'required|max:255',\n '**nickname**' => 'required|max:255',\n 'email' => 'required|max:255',\n 'phone' => 'required|numeric',\n 'password' => 'required|max:255',\n ]);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16568985/" ]
74,519,774
<p>I have a ReactiveForm in Angular with validators. I'm trying to hand over the input data the user made to my <em>component.ts</em> and save it in a variable.</p> <p>In my html file:</p> <pre><code>&lt;form [formGroup]=&quot;loginForm&quot; (ngSubmit)=&quot;submitLogin(emailLogin, passwordLogin)&quot;&gt; </code></pre> <p>and in my component.ts:</p> <pre><code>emailLogin: string = &quot;&quot;; passwordLogin: string = &quot;&quot;; submitLogin( emailLogin: string, passwordLogin: string) { this.emailLogin = emailLogin; this.passwordLogin = passwordLogin; console.log(this.passwordLogin); console.log(this.emailLogin); } </code></pre> <p>Everything I get in the console is a empty string and I don't know why</p> <p>I'm very thankful for any help!</p> <p>Full html-form:</p> <pre><code>&lt;form [formGroup]=&quot;loginForm&quot; (ngSubmit)=&quot;submitLogin(emailLogin, passwordLogin)&quot;&gt; &lt;!-- Email input --&gt; &lt;div class=&quot;form-outline mb-4&quot;&gt; &lt;label class=&quot;form-label&quot; for=&quot;emailLogin&quot;&gt;Email-Adresse&lt;/label&gt; &lt;input formControlName=&quot;emailLogin&quot; type=&quot;email&quot; id=&quot;emailLogin&quot; class=&quot;form-control form-control-lg&quot;/&gt; &lt;ng-container *ngIf=&quot;loginForm.controls['emailLogin'].dirty || loginForm.controls['emailLogin'].touched&quot;&gt; &lt;p class=&quot;error&quot; *ngIf=&quot;loginForm.controls['emailLogin'].errors?.['required']&quot;&gt; Dieses Feld darf nicht leer sein&lt;/p&gt; &lt;p class=&quot;error&quot; *ngIf=&quot;loginForm.controls['emailLogin'].errors?.['email']&quot;&gt; Es muss eine E-Mail eingegeben werden&lt;/p&gt; &lt;/ng-container&gt; &lt;/div&gt; &lt;!-- Passwort input --&gt; &lt;div class=&quot;form-outline mb-4&quot;&gt; &lt;label class=&quot;form-label&quot; for=&quot;passwordLogin&quot;&gt;Passwort&lt;/label&gt; &lt;input formControlName=&quot;passwordLogin&quot; type=&quot;password&quot; id=&quot;passwordLogin&quot; class=&quot;form-control form-control-lg&quot;/&gt; &lt;ng-container *ngIf=&quot;loginForm.controls['passwordLogin'].dirty || loginForm.controls['passwordLogin'].touched&quot;&gt; &lt;p class=&quot;error&quot; *ngIf=&quot;loginForm.controls['passwordLogin'].errors?.['required']&quot;&gt; Dieses Feld darf nicht leer sein&lt;/p&gt; &lt;p class=&quot;error&quot; *ngIf=&quot;loginForm.controls['passwordLogin'].errors?.['minlength']&quot;&gt; Das Passwort muss mindestens 8 Zeichen lang sein&lt;/p&gt; &lt;/ng-container&gt; &lt;/div&gt; &lt;!-- Submit button --&gt; &lt;button [disabled]=&quot;!(loginForm.valid &amp;&amp; (loginForm.dirty || loginForm.touched))&quot; type=&quot;submit&quot; class=&quot;btn btn-secondary btn-block mb-4 w-100&quot;&gt;Einloggen &lt;/button&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 74519792, "author": "Evans Benedict", "author_id": 20560614, "author_profile": "https://Stackoverflow.com/users/20560614", "pm_score": 1, "selected": false, "text": "nickname nickname nickname nickname INSERT INTO\n `students` (\n `name`,\n `nickname`,\n `email`,\n `phone`,\n `password`,\n `updated_at`,\n `created_at`\n )\nVALUES\n (\n test,\n nickname\n test@gmail.com,\n 99999999,\n testpassword,\n 2022 -11 -21 13: 20: 47,\n 2022 -11 -21 13: 20: 47\n )\n" }, { "answer_id": 74519905, "author": "ilgar", "author_id": 16568985, "author_profile": "https://Stackoverflow.com/users/16568985", "pm_score": 0, "selected": false, "text": " public function store(Request $request)\n{\n $storeData = $request->validate([\n 'name' => 'required|max:255',\n 'name' => 'required|max:255',\n 'email' => 'required|max:255',\n 'phone' => 'required|numeric',\n 'password' => 'required|max:255',\n ]);\n public function store(Request $request)\n{\n $storeData = $request->validate([\n 'name' => 'required|max:255',\n '**nickname**' => 'required|max:255',\n 'email' => 'required|max:255',\n 'phone' => 'required|numeric',\n 'password' => 'required|max:255',\n ]);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20553481/" ]
74,519,777
<p>Given a file tree with much dept like this:</p> <pre><code>├── movepy.py # the file I want use to move all other files └── testfodlerComp ├── asdas │   └── erwer.txt ├── asdasdas │   └── sdffg.txt └── asdasdasdasd ├── hoihoi.txt ├── hoihej.txt └── asd ├── dfsdf.txt └── dsfsdfsd.txt </code></pre> <p><strong>How can I then move all items recursively into the current working directory:</strong></p> <pre><code>├── movepy.py │── erwer.txt │── sdffg.txt ├── hoihoi.txt ├── hoihej.txt ├── dfsdf.txt └── dsfsdfsd.txt </code></pre> <p><em>The file tree in this question is an example, in reality I want to move a tree that has many nested sub folders with many nested files.</em></p>
[ { "answer_id": 74519792, "author": "Evans Benedict", "author_id": 20560614, "author_profile": "https://Stackoverflow.com/users/20560614", "pm_score": 1, "selected": false, "text": "nickname nickname nickname nickname INSERT INTO\n `students` (\n `name`,\n `nickname`,\n `email`,\n `phone`,\n `password`,\n `updated_at`,\n `created_at`\n )\nVALUES\n (\n test,\n nickname\n test@gmail.com,\n 99999999,\n testpassword,\n 2022 -11 -21 13: 20: 47,\n 2022 -11 -21 13: 20: 47\n )\n" }, { "answer_id": 74519905, "author": "ilgar", "author_id": 16568985, "author_profile": "https://Stackoverflow.com/users/16568985", "pm_score": 0, "selected": false, "text": " public function store(Request $request)\n{\n $storeData = $request->validate([\n 'name' => 'required|max:255',\n 'name' => 'required|max:255',\n 'email' => 'required|max:255',\n 'phone' => 'required|numeric',\n 'password' => 'required|max:255',\n ]);\n public function store(Request $request)\n{\n $storeData = $request->validate([\n 'name' => 'required|max:255',\n '**nickname**' => 'required|max:255',\n 'email' => 'required|max:255',\n 'phone' => 'required|numeric',\n 'password' => 'required|max:255',\n ]);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5558126/" ]
74,519,810
<p>I am trying to find out if a txt file with 'newfile' name exists in a specified directory or not, if not create a new txt file</p> <pre><code>import os.path if (os.path.exists(&quot;newfile.txt&quot;) == False): open(&quot;count.txt&quot;, &quot;w&quot;) </code></pre> <p>but it does not work since I cannot access the current or specified director with this code.</p>
[ { "answer_id": 74519868, "author": "Evans Benedict", "author_id": 20560614, "author_profile": "https://Stackoverflow.com/users/20560614", "pm_score": 0, "selected": false, "text": "import os.path\n\nfile = 'yourpath\\file_to_check.txt' # 예제 Textfile\n\nif os.path.isfile(file):\n print(\"Yes. it is a file\")\nelif os.path.isdir(file):\n print(\"Yes. it is a directory\")\nelif os.path.exists(file):\n print(\"Something exist\")\nelse :\n print(\"Nothing\")\n from pathlib import Path\n\nmy_file = Path(\"your_path\\file_to_check.txt\") # This way only works in windows os\nif my_file.is_file():\n print(\"Yes it is a file\") \n" }, { "answer_id": 74519990, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 0, "selected": false, "text": "glob import glob\n\nfile_path = glob.glob('../your/file_directory/*')\nif \"count.txt\" not in file_path:\n with open('../your/file_directory/count.txt', 'w') as f:\n f.write('Create new text file')\n\n" }, { "answer_id": 74519992, "author": "Wang Zerui", "author_id": 16232205, "author_profile": "https://Stackoverflow.com/users/16232205", "pm_score": 1, "selected": false, "text": "import inspect\nimport os\n\nmodule_path = inspect.getfile(inspect.currentframe())\nmodule_dir = os.path.realpath(os.path.dirname(module_path))\nos.chdir(module_dir) # set working directory to where file is\n\nif not os.path.exists(\"C:\\\\absolute\\\\directory\\\\newfile.txt\"):\n open(\"count.txt\", \"w\")\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562785/" ]
74,519,816
<p>I've an icon and on click of that icon I need to navigate to a different component. That component is neither parent nor child of the component from where the icon was originally clicked.</p> <pre><code>&lt;i class=&quot;fa fa-times&quot; (click)=&quot;iconClicked()&quot;&gt;&lt;/i&gt; </code></pre> <pre><code>constructor(private _router: Router) { } iconClicked() { this._router.navigateByUrl('/products/entity/record-page'); } </code></pre> <p>My requirement is to pass json data to that component. Let the json data be like this:</p> <pre><code>{ name: &quot;tanzeel&quot;, country: &quot;india&quot;, hobbies: [&quot;football&quot;,&quot;cricket&quot;,&quot;basketball&quot;] } </code></pre> <p>However in real scenario the json is going to be huge. How do I pass this json along with <code>this._router.navigateByUrl.....</code> to that component. Please help.</p>
[ { "answer_id": 74519868, "author": "Evans Benedict", "author_id": 20560614, "author_profile": "https://Stackoverflow.com/users/20560614", "pm_score": 0, "selected": false, "text": "import os.path\n\nfile = 'yourpath\\file_to_check.txt' # 예제 Textfile\n\nif os.path.isfile(file):\n print(\"Yes. it is a file\")\nelif os.path.isdir(file):\n print(\"Yes. it is a directory\")\nelif os.path.exists(file):\n print(\"Something exist\")\nelse :\n print(\"Nothing\")\n from pathlib import Path\n\nmy_file = Path(\"your_path\\file_to_check.txt\") # This way only works in windows os\nif my_file.is_file():\n print(\"Yes it is a file\") \n" }, { "answer_id": 74519990, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 0, "selected": false, "text": "glob import glob\n\nfile_path = glob.glob('../your/file_directory/*')\nif \"count.txt\" not in file_path:\n with open('../your/file_directory/count.txt', 'w') as f:\n f.write('Create new text file')\n\n" }, { "answer_id": 74519992, "author": "Wang Zerui", "author_id": 16232205, "author_profile": "https://Stackoverflow.com/users/16232205", "pm_score": 1, "selected": false, "text": "import inspect\nimport os\n\nmodule_path = inspect.getfile(inspect.currentframe())\nmodule_dir = os.path.realpath(os.path.dirname(module_path))\nos.chdir(module_dir) # set working directory to where file is\n\nif not os.path.exists(\"C:\\\\absolute\\\\directory\\\\newfile.txt\"):\n open(\"count.txt\", \"w\")\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11163977/" ]
74,519,832
<p>I have created a private repo on github, I want to clone this (empty) repo to my local computer to push changes to.</p> <p>I'm using MacOS Ventura 13.0.</p> <p>I have created a keypair and I have uploaded the public key to <code>Settings &gt; SSH and GPG keys</code>. <a href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent" rel="nofollow noreferrer">I have added this key to the ssh-agent</a>. When I <a href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/testing-your-ssh-connection" rel="nofollow noreferrer">test my SSH connection</a> to GitHub, everything works as expected (I get the preferred output like my username and stuff).</p> <p>When I try to clone the private repo, I get the following output:</p> <pre><code>user@my-mac &lt;folder&gt; % git clone git@github.com:&lt;username&gt;/&lt;repo&gt;.git Cloning into '&lt;folder&gt;'... git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. </code></pre> <p>What could possibly be wrong? Should I add the SSH key to a specific repo (in deploy keys)?</p>
[ { "answer_id": 74520780, "author": "Lazy Badger", "author_id": 960558, "author_profile": "https://Stackoverflow.com/users/960558", "pm_score": -1, "selected": false, "text": "/etc/ssh/sshd_config" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12496104/" ]
74,519,837
<p>I'm trying to see if the same &quot;ID&quot; its repeated but with a different &quot;DATE&quot; value.</p> <p>I was thinking using a numpy.where, so I created the column &quot;Count&quot; to use something like this:</p> <pre><code>df['FULFILL?'] = np.where((df['Count']&gt;1) &amp; (df['DATE']), 'YES', 'NO') </code></pre> <p>But then I got stuck because I was not sure how to end the second condition. Here's an example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Count</th> <th>DATE</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>3</td> <td>01/01/2020</td> </tr> <tr> <td>222</td> <td>2</td> <td>02/12/2020</td> </tr> <tr> <td>111</td> <td>3</td> <td>01/01/2020</td> </tr> <tr> <td>222</td> <td>2</td> <td>02/12/2020</td> </tr> <tr> <td>111</td> <td>3</td> <td>02/10/2020</td> </tr> <tr> <td>333</td> <td>2</td> <td>01/25/2020</td> </tr> <tr> <td>333</td> <td>2</td> <td>05/02/2020</td> </tr> <tr> <td>444</td> <td>1</td> <td>01/01/2020</td> </tr> </tbody> </table> </div> <p>I'm looking an output like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Count</th> <th>DATE</th> <th>FULFILL?</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>3</td> <td>01/01/2020</td> <td>YES</td> </tr> <tr> <td>222</td> <td>2</td> <td>02/12/2020</td> <td>NO</td> </tr> <tr> <td>111</td> <td>3</td> <td>01/01/2020</td> <td>YES</td> </tr> <tr> <td>222</td> <td>2</td> <td>02/12/2020</td> <td>NO</td> </tr> <tr> <td>111</td> <td>3</td> <td>02/10/2020</td> <td>YES</td> </tr> <tr> <td>333</td> <td>2</td> <td>01/25/2020</td> <td>YES</td> </tr> <tr> <td>333</td> <td>2</td> <td>05/02/2020</td> <td>YES</td> </tr> <tr> <td>444</td> <td>1</td> <td>01/01/2020</td> <td>NO</td> </tr> </tbody> </table> </div> <p>Sorry if my english it's not very good :)</p>
[ { "answer_id": 74520780, "author": "Lazy Badger", "author_id": 960558, "author_profile": "https://Stackoverflow.com/users/960558", "pm_score": -1, "selected": false, "text": "/etc/ssh/sshd_config" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211618/" ]
74,519,922
<p>I want to fetch data from the Database and want to show all the records of some columns by using listView.builder in flutter code .How I can do this ??</p> <pre><code> </code></pre> <p>I want to fetch data from the Database and want to show all the records of some columns by using listView.builder in flutter code .How I can do this ??</p> <pre><code>static Future&lt;List&gt; getData() async { final db = await SQLHelper.db(); var data= (await db.rawQuery('select column1,column2,column3,column4 From table')); return data.toList(); } import 'package:flutter/material.dart'; import 'package:test_02/dbHelper.dart'; class showOutlets extends StatefulWidget { @override State&lt;showOutlets&gt; createState() =&gt; showOutletsState(); } class showOutletsState extends State&lt;showOutlets&gt; { num age = -1; String birthDate = &quot;&quot;; var data ; List&lt;dynamic&gt; list = [SQLHelper.getOutletsData()]; bool _isLoading = false; void _showFullRecord() async { data = await SQLHelper.getOutletsData( ); setState(() { data =data; _isLoading = false; }); } static var boldStyle= const TextStyle( fontWeight: FontWeight.bold, ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('User Data' ), ), body: _isLoading? const Center( child: CircularProgressIndicator(), ) : ListView.builder( itemCount: list.length, itemBuilder: (context, index ) =&gt; Card( color: Colors.orangeAccent, // color: Colors.orange[200], margin: const EdgeInsets.all(15), child: Column( children: [ const Text(&quot;USER INFORMATION &quot;, style: TextStyle( fontSize: 20.0, ),), // Text('NAME:${data}'), // how can I show the data on the screen ], ), ) ) ); } </code></pre> <pre><code> </code></pre>
[ { "answer_id": 74520780, "author": "Lazy Badger", "author_id": 960558, "author_profile": "https://Stackoverflow.com/users/960558", "pm_score": -1, "selected": false, "text": "/etc/ssh/sshd_config" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531148/" ]
74,519,930
<p>I'm trying to create the following Class:</p> <pre><code>public decimal base { get; set; } </code></pre> <p>and I get the error mentioned. Any solution please? Thank you.</p> <p>I'm trying to create the following Class and I get the error mentioned. Any solution please? Thank you</p>
[ { "answer_id": 74520269, "author": "theemee", "author_id": 14299113, "author_profile": "https://Stackoverflow.com/users/14299113", "pm_score": 0, "selected": false, "text": "base public decimal Base { get; set; }\n" }, { "answer_id": 74574444, "author": "Kroepniek", "author_id": 19699903, "author_profile": "https://Stackoverflow.com/users/19699903", "pm_score": 2, "selected": false, "text": "[JsonProperty(\"base\")]\npublic decimal Base { get; set; }\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4160061/" ]
74,519,934
<p>im new to flutter and i got a problem on my app,</p> <p>firstly i was creating a button on my &quot;ReminderPage&quot; to navigate to a different page &quot;AddReminder&quot;. it works before, so i try to add BottomNavigator in my &quot;MainPage&quot;, but when i add a bottom navigatation from &quot;HomePage&quot; to &quot;ReminderPage&quot; all of the sudden the button didnt work, i also have an icon to change the theme, but the button didnt work and the background all of the sudden become blue, i dont know how this error happen so i need help from all of you guys, thank you</p> <p>here is my &quot;ReminderPage&quot; code</p> <pre><code>import 'package:date_picker_timeline/date_picker_timeline.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:medreminder/Reminder/services/notification_services.dart'; import 'package:medreminder/Reminder/services/theme_services.dart'; import 'package:intl/intl.dart'; import 'package:medreminder/Reminder/ui/theme.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; import 'package:medreminder/Reminder/ui/widgets/button.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; class ReminderHomePage extends StatefulWidget { const ReminderHomePage({super.key}); @override State&lt;ReminderHomePage&gt; createState() =&gt; _ReminderHomePageState(); } class _ReminderHomePageState extends State&lt;ReminderHomePage&gt; { DateTime _selectedDate = DateTime.now(); var notifyHelper; @override void initState() { // TODO: implement initState super.initState(); notifyHelper=NotifyHelper(); notifyHelper.initializeNotification(); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, appBar: _appBar(), backgroundColor: context.theme.backgroundColor, body: Column( children: [ _addTaskBar(), _addDateBar(), ], ), ); } _addDateBar(){ return Container( margin: const EdgeInsets.only(top: 20, left: 20), child: DatePicker( DateTime.now(), height: 100, width: 80, initialSelectedDate: DateTime.now(), selectionColor: Color(0xFFAAB6FB), selectedTextColor: Colors.white, dateTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 20, fontWeight: FontWeight.w600, color:Colors.grey ), ), dayTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color:Colors.grey ), ), monthTextStyle: GoogleFonts.lato( textStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, color:Colors.grey ), ), onDateChange: (date){ _selectedDate=date; }, ), ); } _addTaskBar(){ return Container( margin: const EdgeInsets.only(left: 20, right: 20, top: 5), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: const EdgeInsets.symmetric(horizontal: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(DateFormat.yMMMMd().format(DateTime.now()), style: subHeadingStyle, ), Text(&quot;Today&quot;, style: headingStyle, ) ], ), ), MyButton(label: &quot;Add Reminder&quot;, onTap: ()=&gt;Get.to(AddReminderPage())) ], ), ); } _appBar(){ return AppBar( elevation: 0, backgroundColor: context.theme.backgroundColor, leading: GestureDetector( onTap: (){ ThemeService().switchTheme(); notifyHelper.displayNotification( title:&quot;Theme Changed!&quot;, body: Get.isDarkMode?&quot;Activated Light Theme!&quot;:&quot;Activated Dark Theme!&quot; ); notifyHelper.scheduledNotification(); }, child: Icon(Get.isDarkMode ?Icons.wb_sunny_outlined:Icons.nightlight_round, size: 20, color:Get.isDarkMode ? Colors.white:Colors.black ), ), actions: [ CircleAvatar( backgroundImage: AssetImage( &quot;images/profile.png&quot; ), ), // Icon(Icons.person, // size: 20,), SizedBox(width: 20,), ], ); } } </code></pre> <p>here is my BottomNavigator code</p> <pre><code>import 'package:flutter/material.dart'; import 'package:medreminder/Reminder/ui/home_reminder.dart'; import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart'; import 'package:medreminder/home_page.dart'; import 'package:medreminder/profile_page.dart'; import 'package:medreminder/settings_page.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:medreminder/Reminder/ui/theme.dart'; void main() =&gt; runApp(MaterialApp(home: MainPage())); class MainPage extends StatefulWidget { const MainPage({super.key}); @override State&lt;MainPage&gt; createState() =&gt; _MainPageState(); } class _MainPageState extends State&lt;MainPage&gt; { List &lt;Widget&gt; pages = [ HomePage(), SettingPage(), ProfilePage() ]; int currentIndex = 0; void onTap(int index){ setState(() { currentIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: Container( width: MediaQuery.of(context).size.width, //height: MediaQuery.of(context).size.height * 0.4, child: pages[currentIndex] ), bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.shifting, onTap: onTap, currentIndex: currentIndex, selectedItemColor: bluishClr, unselectedItemColor: Colors.black, showUnselectedLabels: false, showSelectedLabels: false, items: [ BottomNavigationBarItem(label: &quot;Home&quot;, icon: Icon(Icons.home)), BottomNavigationBarItem(label: &quot;Settings&quot;, icon: Icon(Icons.settings)), BottomNavigationBarItem(label: &quot;Profile&quot;, icon: Icon(Icons.account_circle)), ], ), ); } } </code></pre> <p>and lastly here is my HomePage code</p> <pre><code>import 'package:flutter/material.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:get/get_navigation/get_navigation.dart'; import 'Reminder/ui/home_reminder.dart'; import 'Reminder/ui/widgets/button.dart'; void main() { // debugPaintSizeEnabled = true; runApp(const HomePage()); } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return GetMaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Medicine Reminder App'), ), body: Column(children: [ Stack( children: [ Image.asset( 'images/MenuImg.jpg', width: 600, height: 200, fit: BoxFit.cover, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.black)), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) =&gt; const ReminderHomePage()), ); }, child: Text(&quot;Button1&quot;), ), TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.black)), onPressed: () {}, child: Text(&quot;Button2&quot;), ), TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.black)), onPressed: () {}, child: Text(&quot;Button3&quot;), ), ], ) ]), ), ); } } </code></pre> <p>i really need a help, so every help would mean so much to me, thankyou guys</p> <p>here is my app working perfectly when i run only the ReminderPage <a href="https://i.stack.imgur.com/JqcZp.png" rel="nofollow noreferrer">https://i.stack.imgur.com/JqcZp.png</a></p> <p>and here's how it look if i run it with BottomNavigationBar (the add reminder button and moon icon cant be clicked) <a href="https://i.stack.imgur.com/9hVr8.png" rel="nofollow noreferrer">https://i.stack.imgur.com/9hVr8.png</a></p>
[ { "answer_id": 74520269, "author": "theemee", "author_id": 14299113, "author_profile": "https://Stackoverflow.com/users/14299113", "pm_score": 0, "selected": false, "text": "base public decimal Base { get; set; }\n" }, { "answer_id": 74574444, "author": "Kroepniek", "author_id": 19699903, "author_profile": "https://Stackoverflow.com/users/19699903", "pm_score": 2, "selected": false, "text": "[JsonProperty(\"base\")]\npublic decimal Base { get; set; }\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229067/" ]
74,519,937
<p>I have an existing dataframe with two columns as follows:</p> <pre><code> reason market_state 0 NaN UNSCHEDULED_AUCTION 1 NaN None 2 NaN CLOSED 3 NaN CONTINUOUS_TRADING 4 NaN None 5 NaN UNSCHEDULED_AUCTION 6 NaN UNSCHEDULED_AUCTION 7 F None 8 NaN CONTINUOUS_TRADING 9 SL None 10 NaN HALTED 11 NaN None 12 NaN None 13 L None </code></pre> <p>I am trying to apply the following 3 mappings to the above dataframe:</p> <pre><code>market_info_df['market_state'] = market_info_df['reason'].map({'F': OPENING_AUCTION}) market_info_df['market_state'] = market_info_df['reason'].map({'SL': CLOSING_AUCTION}) market_info_df['market_state'] = market_info_df['reason'].map({'L': CLOSED}) </code></pre> <p>But when I run the above 3 lines, it seems to overwrite the existing mappings:</p> <pre><code> market_state reason 0 NaN NaN 1 NaN NaN 2 NaN NaN 3 NaN NaN 4 NaN NaN 5 NaN NaN 6 NaN NaN 7 NaN F 8 NaN NaN 9 NaN SL 10 NaN NaN 11 NaN NaN 12 NaN NaN 13 CLOSED L </code></pre> <p>(And it seems to have swapped the columns? - though this doesn't matter)</p> <p>Each of the lines seems to overwrite the dataframe. Is there a way simply to update the dataframe, i.e. so it just updates the three mappings, like this:</p> <pre><code> reason market_state 0 NaN UNSCHEDULED_AUCTION 1 NaN None 2 NaN CLOSED 3 NaN CONTINUOUS_TRADING 4 NaN None 5 NaN UNSCHEDULED_AUCTION 6 NaN UNSCHEDULED_AUCTION 7 F OPENING_AUCTION 8 NaN CONTINUOUS_TRADING 9 SL CLOSING_AUCTION 10 NaN HALTED 11 NaN None 12 NaN None 13 L CLOSED </code></pre>
[ { "answer_id": 74519968, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "Series.fillna market_state d = {'F': 'OPENING_AUCTION','SL': 'CLOSING_AUCTION', 'L': 'CLOSED'}\nmarket_info_df['market_state'] = (market_info_df['reason'].map(d)\n .fillna(market_info_df['market_state']))\nprint (market_info_df)\n reason market_state\n0 NaN UNSCHEDULED_AUCTION\n1 NaN None\n2 NaN CLOSED\n3 NaN CONTINUOUS_TRADING\n4 NaN None\n5 NaN UNSCHEDULED_AUCTION\n6 NaN UNSCHEDULED_AUCTION\n7 F OPENING_AUCTION\n8 NaN CONTINUOUS_TRADING\n9 SL CLOSING_AUCTION\n10 NaN HALTED\n11 NaN None\n12 NaN None\n13 L CLOSED\n" }, { "answer_id": 74519987, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "fillna market_info_df['market_state'] = (\n market_info_df['reason']\n .map({'F': 'OPENING_AUCTION', # only ONE dictionary\n 'SL': 'CLOSING_AUCTION',\n 'L': 'CLOSED'})\n .fillna(market_info_df['market_state'])\n)\n df.loc[df['market_state'].isna(), 'market_state'] = (\n market_info_df['reason']\n .map({'F': 'OPENING_AUCTION', # only ONE dictionary\n 'SL': 'CLOSING_AUCTION',\n 'L': 'CLOSED'})\n)\n reason market_state\n0 NaN UNSCHEDULED_AUCTION\n1 NaN None\n2 NaN CLOSED\n3 NaN CONTINUOUS_TRADING\n4 NaN None\n5 NaN UNSCHEDULED_AUCTION\n6 NaN UNSCHEDULED_AUCTION\n7 F OPENING_AUCTION\n8 NaN CONTINUOUS_TRADING\n9 SL CLOSING_AUCTION\n10 NaN HALTED\n11 NaN None\n12 NaN None\n13 L CLOSED\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19667022/" ]
74,519,945
<p>I'm trying to get the record count from multiple tables, like this.</p> <pre><code>Select count(*) From ( Select Hist.Common_Name, Veg.ID, EDSH.ID From Hist_Event_View as Hist Inner Join Vegtables as Veg ON Hist.Common_Name = Veg.ID INNER JOIN Final as Final ON Hist.Common_Name = Final.ID) as Sub </code></pre> <p>The problem is that ID is being used multiple times, so SQL Server can't resolve which ID is coming from which table in the outer query, I think. How can I handle this issue? Thanks.</p>
[ { "answer_id": 74519968, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 2, "selected": false, "text": "Series.fillna market_state d = {'F': 'OPENING_AUCTION','SL': 'CLOSING_AUCTION', 'L': 'CLOSED'}\nmarket_info_df['market_state'] = (market_info_df['reason'].map(d)\n .fillna(market_info_df['market_state']))\nprint (market_info_df)\n reason market_state\n0 NaN UNSCHEDULED_AUCTION\n1 NaN None\n2 NaN CLOSED\n3 NaN CONTINUOUS_TRADING\n4 NaN None\n5 NaN UNSCHEDULED_AUCTION\n6 NaN UNSCHEDULED_AUCTION\n7 F OPENING_AUCTION\n8 NaN CONTINUOUS_TRADING\n9 SL CLOSING_AUCTION\n10 NaN HALTED\n11 NaN None\n12 NaN None\n13 L CLOSED\n" }, { "answer_id": 74519987, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "fillna market_info_df['market_state'] = (\n market_info_df['reason']\n .map({'F': 'OPENING_AUCTION', # only ONE dictionary\n 'SL': 'CLOSING_AUCTION',\n 'L': 'CLOSED'})\n .fillna(market_info_df['market_state'])\n)\n df.loc[df['market_state'].isna(), 'market_state'] = (\n market_info_df['reason']\n .map({'F': 'OPENING_AUCTION', # only ONE dictionary\n 'SL': 'CLOSING_AUCTION',\n 'L': 'CLOSED'})\n)\n reason market_state\n0 NaN UNSCHEDULED_AUCTION\n1 NaN None\n2 NaN CLOSED\n3 NaN CONTINUOUS_TRADING\n4 NaN None\n5 NaN UNSCHEDULED_AUCTION\n6 NaN UNSCHEDULED_AUCTION\n7 F OPENING_AUCTION\n8 NaN CONTINUOUS_TRADING\n9 SL CLOSING_AUCTION\n10 NaN HALTED\n11 NaN None\n12 NaN None\n13 L CLOSED\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5212614/" ]
74,519,954
<p>I have a <code>TabPane</code> declared like this :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.scene.control.TabPane?&gt; &lt;TabPane fx:id=&quot;rootNode&quot; maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; prefHeight=&quot;400.0&quot; prefWidth=&quot;600.0&quot; stylesheets=&quot;@dark_theme.css&quot; tabClosingPolicy=&quot;UNAVAILABLE&quot; xmlns=&quot;http://javafx.com/javafx/19&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; fx:controller=&quot;controllers.AppController&quot; /&gt; </code></pre> <p>And I want to add tabs from my controller. So I do :</p> <pre><code> jsonConfig.getAvailableChannelIds().forEach( chId -&gt; { try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(&quot;tab_item.fxml&quot;)); Tab item = fxmlLoader.load(); item.setText(String.format(&quot;%d&quot;, chId)); rootNode.getTabs().add(item); }catch (Exception e) { e.printStackTrace(); } }); </code></pre> <p>&quot;tab_item.fxml&quot; looks as follows :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.scene.control.Tab?&gt; &lt;?import javafx.scene.layout.VBox?&gt; &lt;Tab xmlns:fx=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt; &lt;VBox&gt; &lt;fx:include source=&quot;test.fxml&quot;/&gt; &lt;/VBox&gt; &lt;/Tab&gt; </code></pre> <p>And finally &quot;test.fxml&quot; :</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?import javafx.scene.layout.AnchorPane?&gt; &lt;AnchorPane maxHeight=&quot;-Infinity&quot; maxWidth=&quot;-Infinity&quot; minHeight=&quot;-Infinity&quot; minWidth=&quot;-Infinity&quot; prefHeight=&quot;400.0&quot; prefWidth=&quot;600.0&quot; style=&quot;-fx-background-color: red;&quot; xmlns=&quot;http://javafx.com/javafx/19&quot; xmlns:fx=&quot;http://javafx.com/fxml/1&quot; /&gt; </code></pre> <p>And here is what I have :</p> <p><a href="https://i.stack.imgur.com/H3dZe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H3dZe.jpg" alt="enter image description here" /></a></p> <p>What am I missing to fill the <code>Tab</code> content with the red square ?</p>
[ { "answer_id": 74520221, "author": "Dmitry", "author_id": 2769062, "author_profile": "https://Stackoverflow.com/users/2769062", "pm_score": -1, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.control.Tab?>\n\n<?import javafx.scene.layout.AnchorPane?>\n<Tab xmlns:fx=\"http://www.w3.org/1999/XSL/Transform\">\n <content>\n <AnchorPane>\n <fx:include source=\"test.fxml\" AnchorPane.topAnchor=\"0\" AnchorPane.rightAnchor=\"0\" AnchorPane.leftAnchor=\"0\" AnchorPane.bottomAnchor=\"0\"/>\n </AnchorPane>\n </content>\n</Tab>\n \n" }, { "answer_id": 74548477, "author": "James_D", "author_id": 2189127, "author_profile": "https://Stackoverflow.com/users/2189127", "pm_score": 2, "selected": true, "text": "VBox <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.layout.AnchorPane?>\n\n<AnchorPane maxHeight=\"-Infinity\" maxWidth=\"-Infinity\" \n minHeight=\"-Infinity\" minWidth=\"-Infinity\" \n prefHeight=\"400.0\" prefWidth=\"600.0\" \n style=\"-fx-background-color: red;\"\n xmlns=\"http://javafx.com/javafx/19\" \n xmlns:fx=\"http://javafx.com/fxml/1\" />\n -Infinity Region.USE_PREF_SIZE VBox VBox <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.layout.AnchorPane?>\n\n<AnchorPane style=\"-fx-background-color: red;\"\n xmlns:fx=\"http://javafx.com/fxml\" />\n VBox VBox <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.control.Tab?>\n\n<?import javafx.scene.layout.VBox?>\n<Tab xmlns:fx=\"http://javafx.com/fxml/\">\n <VBox fillWidth=\"true\">\n <fx:include source=\"test.fxml\" VBox.vgrow=\"ALWAYS\" />\n </VBox>\n</Tab>\n test.fxml VBox Tab VBox test.fxml VBox <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.control.Tab?>\n\n<Tab xmlns:fx=\"http://javafx.com/fxml/\">\n <fx:include source=\"test.fxml\" />\n</Tab>\n HelloApplication.java package org.jamesd.examples.tab;\n\nimport javafx.application.Application;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.Scene;\nimport javafx.stage.Stage;\n\nimport java.io.IOException;\n\npublic class HelloApplication extends Application {\n @Override\n public void start(Stage stage) throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource(\"hello-view.fxml\"));\n Scene scene = new Scene(fxmlLoader.load(), 320, 240);\n stage.setTitle(\"Hello!\");\n stage.setScene(scene);\n stage.show();\n }\n\n public static void main(String[] args) {\n launch();\n }\n}\n hello-view.fxml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.control.TabPane?>\n\n<TabPane fx:id=\"rootNode\"\n tabClosingPolicy=\"UNAVAILABLE\"\n xmlns:fx=\"http://javafx.com/fxml/\"\n fx:controller=\"org.jamesd.examples.tab.AppController\" />\n AppController.java package org.jamesd.examples.tab;\n\nimport javafx.fxml.FXML;\nimport javafx.fxml.FXMLLoader;\nimport javafx.scene.control.Tab;\nimport javafx.scene.control.TabPane;\n\npublic class AppController {\n\n @FXML\n private TabPane rootNode ;\n\n public void initialize() {\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(\"tab_item.fxml\"));\n Tab item = fxmlLoader.load();\n item.setText(String.format(\"%d\", 42));\n rootNode.getTabs().add(item);\n }catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n tab-item.fxml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.control.Tab?>\n\n<Tab xmlns:fx=\"http://javafx.com/fxml/\">\n <fx:include source=\"test.fxml\" />\n</Tab>\n test.fxml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<?import javafx.scene.layout.AnchorPane?>\n\n<AnchorPane style=\"-fx-background-color: red;\"/>\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2769062/" ]
74,519,974
<p><strong>Problem</strong>:</p> <p>I want to calculate at several times the adjacency matrix <code>A_ij</code> given the adjacency list <code>E_ij</code>, where <code>E_ij[t,i] = j</code> gives the edge from <code>i</code> to <code>j</code> at time <code>t</code>.</p> <p>I can do it with the following code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np nTimes = 100 nParticles = 10 A_ij = np.full((nTimes, nParticles, nParticles), False) E_ij = np.random.randint(0, 9, (100, 10)) for t in range(nTimes): for i in range(nParticles): A_ij[t, i, E_ij[t,i]] = True </code></pre> <p><strong>Question:</strong></p> <p>How can I do it in a vectorized way, either with fancy indexing or using numpy functions such as <code>np.take_along_axis</code>?</p> <hr /> <p><strong>What I tried:</strong></p> <p>I expected this to work:</p> <pre class="lang-py prettyprint-override"><code>A_ij[:,np.arange(nParticles)[None,:,None], E_ij[:,None,np.arange(nParticles)]] = True </code></pre> <p>But it does not.</p> <hr /> <p>Related to: <a href="https://stackoverflow.com/q/43571393/12131616">Trying to convert adjacency list to adjacency matrix in Python</a></p>
[ { "answer_id": 74520182, "author": "Chrysophylaxs", "author_id": 9499196, "author_profile": "https://Stackoverflow.com/users/9499196", "pm_score": 3, "selected": true, "text": "import numpy as np\n\nnTimes = 100\nnParticles = 10\nA_ij = np.full((nTimes, nParticles, nParticles), False)\nE_ij = np.random.randint(0, 9, (100, 10))\n\nnp.put_along_axis(A_ij, E_ij[..., None], True, axis=2)\n" }, { "answer_id": 74520328, "author": "Puco4", "author_id": 12131616, "author_profile": "https://Stackoverflow.com/users/12131616", "pm_score": 1, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n\nnTimes = 1000000\nnParticles = 10\nA_ij1 = np.full((nTimes, nParticles, nParticles), False)\nA_ij2 = np.full((nTimes, nParticles, nParticles), False)\nA_ij3 = np.full((nTimes, nParticles, nParticles), False)\nA_ij4 = np.full((nTimes, nParticles, nParticles), False)\n\n\nE_ij = np.random.randint(0, 9, (nTimes, 10))\n\nstart_time = time.time()\nfor t in range(nTimes):\n for i in range(nParticles):\n A_ij1[t, i, E_ij[t,i]] = True\nprint(\"Loop: %s s\" % (time.time() - start_time))\n\n \nstart_time = time.time()\nA_ij2[np.arange(nTimes)[:,None],np.arange(nParticles)[None,:], E_ij[np.arange(nTimes)[:,None],np.arange(nParticles)[None,:]]] = True\nprint(\"Fancy indexing: %s s\" % (time.time() - start_time))\n\nstart_time = time.time()\nnp.put_along_axis(A_ij3, E_ij[..., None], True, axis=2)\nprint(\"Put along axis: %s s\" % (time.time() - start_time))\n\nstart_time = time.time()\ni, j = np.mgrid[:nTimes, :nParticles]\nA_ij4[i, j, E_ij] = True\nprint(\"mgrid: %s s\" % (time.time() - start_time))\n\n\nprint(np.allclose(A_ij1, A_ij2))\nprint(np.allclose(A_ij1, A_ij3))\nprint(np.allclose(A_ij1, A_ij4))\n Loop: 2.5006823539733887 s\nFancy indexing: 0.11996173858642578 s\nPut along axis: 0.0814671516418457 s\nmgrid: 0.19223332405090332 s\nTrue\nTrue\nTrue\n" }, { "answer_id": 74520448, "author": "Mercury", "author_id": 10229754, "author_profile": "https://Stackoverflow.com/users/10229754", "pm_score": 1, "selected": false, "text": "i, j = np.mgrid[:nTimes, :nParticles]\nA_ij[i, j, E_ij] = True\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74519974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12131616/" ]