qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,256,120 | <p>With the following UMD export:</p>
<pre><code>(function(factory) {
module.exports = factory();
} (function() {
function test() {
this.param = 'This is a test';
this.init = function() {
console.log(this.param)
}
this.init();
}
return test;
}));
</code></pre>
<p>I tried to import the <code>test</code> function, and to initialize an instance</p>
<pre><code>import {test} from 'path/to/test'
const myTest = new test();
</code></pre>
<p>Result:</p>
<blockquote>
<p>test is not a constructor</p>
</blockquote>
| [
{
"answer_id": 74256170,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "import test from 'path/to/test'\n"
},
{
"answer_id": 74256171,
"author": "Franco Agustín Torres",
"au... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,256,127 | <p>I'm working with HighCharts and trying to update the chart series.
So far, everything works fine when I use;</p>
<pre><code>chart.series[0].setData([Date.UTC(2022, 9, 29,14,54,52), 34.74],[Date.UTC(2022, 9, 29,15,24,52), 35.6]);
</code></pre>
<p>However, the real data comes as a string such as;</p>
<pre><code>data = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]';
</code></pre>
<p>Since the setData() method requires an <strong>Array of DateTime x and y values</strong>, I have to convert the above string to an array, which might be simple but I can't really get it working...
I tried two ways:</p>
<ol>
<li><p>using Array.from()</p>
<p>v2 = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]';
line = v2.split('^');
data = Array.from(line);</p>
</li>
<li><p>using push()</p>
<p>v2 = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]';
line = v2.split('^');
data = []
data.push(line)</p>
</li>
</ol>
<p>but neither ways worked for me...</p>
<p>Can please someone point me to the right way of getting the array from the string?</p>
<p>Thanks
Gus</p>
| [
{
"answer_id": 74256170,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "import test from 'path/to/test'\n"
},
{
"answer_id": 74256171,
"author": "Franco Agustín Torres",
"au... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3103946/"
] |
74,256,129 | <p>How can I add this arrayOfObjects to the data that is coming from the api response ?</p>
<p>I tried this pattern but didn't work for me</p>
<pre><code> const url = "https://jsonplaceholder.typicode.com/users";
useEffect(() => {
const arrayOfObjects = [
{num:1},
{num:2},
{num:3},
{num:4},
{num:5},
{num:6},
{num:7},
{num:8},
{num:9},
{num:10},
];
axios(url).then((res) => {
const newData = res.data.map((item) => (item.arrayOfObjects.map(innerItem => innerItem) = num));
console.log(newData);
});
}, []);
</code></pre>
<p>for example the result should look like this in the response data although "https://jsonplaceholder.typicode.com/users" has 10 objects</p>
<pre><code>[
{
name: "Leanne Graham"
num: 1
etc.
},
{
name: "Ervin Howell"
num: 2
etc.
},
{ name: "Clementine Bauch"
num: 3
etc.
}
etc.
]
</code></pre>
| [
{
"answer_id": 74256263,
"author": "Neil Girardi",
"author_id": 1500241,
"author_profile": "https://Stackoverflow.com/users/1500241",
"pm_score": 1,
"selected": false,
"text": "arrayOfObjects"
},
{
"answer_id": 74256313,
"author": "binginsin",
"author_id": 6226712,
"a... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18836219/"
] |
74,256,130 | <p>I need to pass arrays of variables to a subroutine that should change their values according to an external file. The problem is that this should be as generic as possible so if the file has n values I should be able to pass n generic integers.</p>
<p>Here is an example of my code:</p>
<pre><code>program dummy
use checkpt
implicit none
integer :: i1=0, i2=0, k=1, n, cpt
integer*8 :: lastTime
call load_checkpoint(ints=[k,i1,i2])
--some code happening--
end program dummy
</code></pre>
<p>And the subroutine called is the following:</p>
<pre><code>subroutine load_checkpoint(ints)
implicit none
integer, intent(inout) :: ints(:)
integer :: stat
open(8989, file='temp.txt', status='old', action='READ', iostat=stat)
if (stat .eq. 0) then
read (8989,*,iostat=stat) ints
end if
close(8989)
end subroutine load_checkpoint
</code></pre>
<p>What I get is <code>Error: Non-variable expression in variable definition context (actual argument to INTENT = OUT/INOUT) at (1)</code> and I can't understand why. I also tried with non initialized variables but I get the same error. Can anybody help me, please?</p>
| [
{
"answer_id": 74256263,
"author": "Neil Girardi",
"author_id": 1500241,
"author_profile": "https://Stackoverflow.com/users/1500241",
"pm_score": 1,
"selected": false,
"text": "arrayOfObjects"
},
{
"answer_id": 74256313,
"author": "binginsin",
"author_id": 6226712,
"a... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373901/"
] |
74,256,153 | <p>I need to extract an attribute's value from any given tag. For instance, if we have an <code><a></code>, and it contains an <code>href</code>, I would like to extract the value and store it in a variable. After doing some researching/investigation, I found that most people are acquiring attribute values using the following methods:</p>
<p><strong>METHOD # 1: INVOKE METHOD</strong></p>
<pre class="lang-js prettyprint-override"><code>cy.get('a').invoke('attr', 'href').should('eq', 'https://docs.cypress.io')
</code></pre>
<p><strong>METHOD # 2: PROP METHOD</strong></p>
<pre class="lang-js prettyprint-override"><code>cy.get('input').invoke('prop', 'href').then(href => {console.log(`href ${href}`)})
</code></pre>
<p>Method # 1 above performs a test .. although finds the value, it runs it through a <code>.should()</code> but that is not what I want. I want to literally extract the value and store it in a variable for later use. I have no intention to perform an assertion.</p>
<p>Method # 2 does not even work for me.. in the example, <code>href</code> is simply coming back as "undefined"</p>
<p>In a nutshell, I simply want the value of a given attribute to store, display and possibly perform some string manipulation on it. I do not wish to perform any checks/tests. Just merely acquire the value and store it in a variable.</p>
| [
{
"answer_id": 74257255,
"author": "agoff",
"author_id": 11625850,
"author_profile": "https://Stackoverflow.com/users/11625850",
"pm_score": 0,
"selected": false,
"text": "cy.get('input')\n .invoke('attr', 'href')\n .then((href) => {\n // href is the value of the element's href attr... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6287717/"
] |
74,256,154 | <p>I have an input field that asks the user for a number then generates a multiplication from 1 - 12 against the number.</p>
<pre><code><input type="text" id="integer" value="100" />
</code></pre>
<p>if the number entered in the input field is less than 1 and greater than 100, it will alert the user to enter a number between 1 and 100</p>
<pre><code>if (integer < 1 || integer > 100) {
alert(
"Please enter a valid input \nEnter any number between 1 and 100"
);}
</code></pre>
<p>After the alert, the input field should clear.</p>
<pre><code>let integer = document.getElementById("integer").value
</code></pre>
<p>i have tried setting the input value to ""</p>
<pre><code>if (integer < 1 || integer > 100) {
alert(
"Please enter a valid input \nEnter any number between 1 and 100"
);
integer = "";}
</code></pre>
<p>but the input isn't clearing.</p>
| [
{
"answer_id": 74256163,
"author": "mikael khalil",
"author_id": 20374041,
"author_profile": "https://Stackoverflow.com/users/20374041",
"pm_score": -1,
"selected": false,
"text": "<input type=\"text\" id=\"integer\" min=\"1\" max= \"100\" value=\"100\" />"
},
{
"answer_id": 7425... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17093903/"
] |
74,256,156 | <p>I try to use <code>netcat</code> as a quick-and-dirty socket server to receive requests with four words: <code>m base exponent modulus</code>, for example <code>m 119911077684 3 25</code>. I get back the result of the calculation.</p>
<p>This works OK until I send a request with a length of more than 4KB length.</p>
<p>My "server" script:</p>
<pre><code>#!/bin/bash
eol=$'[^\n]*' # needed for bash regex
coproc nc -k -I 1 -l localhost 3000
while read -r input; do
if [[ "$input" =~ ^m\ [0-9]+\ [0-9]+\ [0-9]+${eol} ]]; # m base exponent modulo
then # modpow
base=$(echo $input | awk {'print $2'})
exp=$(echo $input | awk {'print $3'})
mod=$(echo $input | awk {'print $4'})
modPowResult=$(echo "(${base}^${exp})%${mod}" | bc | awk {'print $NF"."'})
echo "Received modPow request for $input. Result: $modPowResult" 1>&2
echo $modPowResult
else
echo $input | wc -c # if pattern does not match, echo byte length of request
fi
done <&"${COPROC[0]}" >&"${COPROC[1]}"
kill "$COPROC_PID"
</code></pre>
<p>I start the script and send with another netcat instance the request:</p>
<pre><code>$ echo "m 123456789 3 45" | nc -N localhost 3000
24.
</code></pre>
<p>This is correct. But when my request is much larger (see below, it is very long, ca. 10KB), I only get <code>4096</code> as reponse, because obviously my request gets cut off after 4KB and the pattern does not match anymore.</p>
<p><strong>How can I increase the buffer size to 10KB?</strong></p>
<p>I am using <code>nc</code> from the netcat-openbsd package, version 1-206-1ubuntu1 on <a href="https://manpages.ubuntu.com/manpages/xenial/man1/nc_openbsd.1.html" rel="nofollow noreferrer">Linux Mint 20.3</a></p>
<hr />
<p>The long request that I send:</p>
<p><code>echo "m 119911077684388654464905913640776437154226670795608893126674401497793499190599280364130861725657104256566310462928507333209140730941832679850546964169574064502302506332980156346356353770204888295893093063184171997362057589517916010232980225391190320750952316465242324362891959100433858192271524147327414193082762890942035801958435316746500255772469345443216706039859433187598295446068294406788893004692563776136880999772523175303498038904595251052460892879542020390119365589551790081268294658670278839814000163620963699270901605327269182105315861334765282825877117237939020225059516048118822507748006320140239127478171838351066517019561839074929762330738028988275952662573265475737958301112851610595197531548497931446195952199321225970603280237392220002522234886604777354155305811126368542319814508734009724324574699762651933585658723268760338177467622997981508947488138668393644460194683162338182424638860784463205640320448417099383855382072818522929202040238994871533168133096831111510329881339134763052538793876982638221330371252613725855423571592146896758029880815370773533166968689127694703613734175707262846305586680102089283714672783584517247301712969997094188100846219871156880235250247262980941183982704470095357213637606107507347453851859858258698250607011513572535484062678271610484502455298006740369910804762417997008476244552290202422317383157478396506467483547744680169844974572967951447559272841442146195443163534430952926895944261405130537737083631290680916949035417377083444415613476470341303467658036432355832593865630222641297800142546121968228846670197431109658981524433553756516953169470270906175492638718257553629213095100747917452682253534211285832629838466511684445690038642779739911400231376076345271912866270126103787029556428130767593052626081831221831223069580448091335438929310705480858617960388692829148459668614553232856571359456182303111874697232026093026735470157165631651212560517025642976319831045781661538333599277034496981219269694512980275812089778730557632740797476353145760258328215998308472261145339422239050482532352129878920788865567995314629458455327155286460238383601946131961867426246265063123310726106693688718664044349515654363702741294452618335274329308578472175698617007182314284268398046497119531245936875755301603221798084316149598933360094885522867791011019273879574214058612225280983080451350767657126400778161555154304319817144617977921922780590457889389437733151154458594456669604913268357425018532675449321843724352306079286744292171948217434515478917308576498176270964164503811434926456683997368072955780726407859396433392794616507815229616209090535536963109780002140901827906975627967234293316955484216859007738529128975244401216085490915871531024507388309924318957155664906647334284585657638205005354547972419069669305452946639321947833394012435994802212916314476136632901669877608954569163544585174720274193743687733458152918021103753102103947757555536761250496423878947836539892181876319734828966403334468831996533582017308189424762055828357515602936391523294046491166211479541642683423998481465228274715001337998653123393277987627077776818291591865084393516551743127086475215375488202768688468221850610667101157756129583386649154755248232529575715947587573192188002157902017334436011038795700079402462826143560097658389200375725241631103202999992556312624592938137480846350848412026903419748096472380721662811550019522587811231052807795247261396319322540786904514244002649655444936516678315615815509490655441432557060506710854423809303803799832928358980279269976326443553767226117625378677721292146178144549137705670729846916993352305260256590882027591743518081622859024428432168499789050705296010312198688149480829077360824768339796901501769440011904610841999354713730007228733819400623210253248584255483381392135718982605469783073713176584693762824529856548255829134252116676403607113453428329546378911527121717218999162743029739470118529567736972067845106858183596445431859293814234467541362869837645245531687840718971450084815430300571277137631369480578785256511883434866398115621625953321395003577260895315118187411368327379978003552361264941991367588687121311204075732836962000799670126804000341688676901753702477021783266973371801241580953827616710188316672824198593419336050954281253130376778353822189824793800377718546601238247633120718659688831387817435649580877050448379012109503469868396520377378126968305945002734231194704115340864046955006030320932229997317614731989768411151227868361921843660344264921010915708495738985694574122911876672320122306870878930188687145058261733930157339319798025944904157368343854051187139367584319089952511053991867768078683402834031280370390040928451335081517037741108170426931092914661068970885818584596678595958636380828215961484655468488414470923291859914117819582725965617477747349015436236760229667348629664530116390566373561395785664859008004089692090065941440053939927994563495221580087238773509064814875447794256225 3 119911077684388654464905913640776437154226670795608893126674401497793499190599280364130861725657104256566310462928507333209140730941832679850546964169574064502302506332980156346356353770204888295893093063184171997362057589517916010232980225391190320750952316465242324362891959100433858192271524147327414193082762890942035801958435316746500255772469345443216706039859433187598295446068294406788893004692563776136880999772523175303498038904595251052460892879542020390119365589551790081268294658670278839814000163620963699270901605327269182105315861334765282825877117237939020225059516048118822507748006320140239127478171838351066517019561839074929762330738028988275952662573265475737958301112851610595197531548497931446195952199321225970603280237392220002522234886604777354155305811126368542319814508734009724324574699762651933585658723268760338177467622997981508947488138668393644460194683162338182424638860784463205640320448417099383855382072818522929202040238994871533168133096831111510329881339134763052538793876982638221330371252613725855423571592146896758029880815370773533166968689127694703613734175707262846305586680102089283714672783584517247301712969997094188100846219871156880235250247262980941183982704470095357213637606107507347453851859858258698250607011513572535484062678271610484502455298006740369910804762417997008476244552290202422317383157478396506467483547744680169844974572967951447559272841442146195443163534430952926895944261405130537737083631290680916949035417377083444415613476470341303467658036432355832593865630222641297800142546121968228846670197431109658981524433553756516953169470270906175492638718257553629213095100747917452682253534211285832629838466511684445690038642779739911400231376076345271912866270126103787029556428130767593052626081831221831223069580448091335438929310705480858617960388692829148459668614553232856571359456182303111874697232026093026735470157165631651212560517025642976319831045781661538333599277034496981219269694512980275812089778730557632740797476353145760258328215998308472261145339422239050482532352129878920788865567995314629458455327155286460238383601946131961867426246265063123310726106693688718664044349515654363702741294452618335274329308578472175698617007182314284268398046497119531245936875755301603221798084316149598933360094885522867791011019273879574214058612225280983080451350767657126400778161555154304319817144617977921922780590457889389437733151154458594456669604913268357425018532675449321843724352306079286744292171948217434515478917308576498176270964164503811434926456683997368072955780726407859396433392794616507815229616209090535536963109780002140901827906975627967234293316955484216859007738529128975244401216085490915871531024507388309924318957155664906647334284585657638205005354547972419069669305452946639321947833394012435994802212916314476136632901669877608954569163544585174720274193743687733458152918021103753102103947757555536761250496423878947836539892181876319734828966403334468831996533582017308189424762055828357515602936391523294046491166211479541642683423998481465228274715001337998653123393277987627077776818291591865084393516551743127086475215375488202768688468221850610667101157756129583386649154755248232529575715947587573192188002157902017334436011038795700079402462826143560097658389200375725241631103202999992556312624592938137480846350848412026903419748096472380721662811550019522587811231052807795247261396319322540786904514244002649655444936516678315615815509490655441432557060506710854423809303803799832928358980279269976326443553767226117625378677721292146178144549137705670729846916993352305260256590882027591743518081622859024428432168499789050705296010312198688149480829077360824768339796901501769440011904610841999354713730007228733819400623210253248584255483381392135718982605469783073713176584693762824529856548255829134252116676403607113453428329546378911527121717218999162743029739470118529567736972067845106858183596445431859293814234467541362869837645245531687840718971450084815430300571277137631369480578785256511883434866398115621625953321395003577260895315118187411368327379978003552361264941991367588687121311204075732836962000799670126804000341688676901753702477021783266973371801241580953827616710188316672824198593419336050954281253130376778353822189824793800377718546601238247633120718659688831387817435649580877050448379012109503469868396520377378126968305945002734231194704115340864046955006030320932229997317614731989768411151227868361921843660344264921010915708495738985694574122911876672320122306870878930188687145058261733930157339319798025944904157368343854051187139367584319089952511053991867768078683402834031280370390040928451335081517037741108170426931092914661068970885818584596678595958636380828215961484655468488414470923291859914117819582725965617477747349015436236760229667348629664530116390566373561395785664859008004089692090065941440053939927994563495221580087238773509064814875447794256225" | nc -N localhost 3000</code></p>
| [
{
"answer_id": 74256321,
"author": "username_313",
"author_id": 20305773,
"author_profile": "https://Stackoverflow.com/users/20305773",
"pm_score": 0,
"selected": false,
"text": "iPhone:~/netcat-0.7.1/src# grep -Hn \"4096\" *\nmisc.c:264: char buf[4096], *p, *rest;\niPhone:~/netcat-0.7.... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2422617/"
] |
74,256,187 | <p>I created a data set <code>employee_data</code>. I loaded tables <code>departments</code> and <code>employee</code>. When I INNER JOIN the tables the error says <code>departments</code> should be qualified with a dataset.</p>
<p><a href="https://i.stack.imgur.com/mK5Fr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mK5Fr.png" alt="SQL Query" /></a></p>
| [
{
"answer_id": 74259679,
"author": "Scott B",
"author_id": 17720354,
"author_profile": "https://Stackoverflow.com/users/17720354",
"pm_score": 1,
"selected": false,
"text": "JOIN"
},
{
"answer_id": 74522542,
"author": "Waleed Ibrahim Osman",
"author_id": 20565179,
"au... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19810650/"
] |
74,256,231 | <p>I'm currently doing this for each column:</p>
<pre><code>df['slope'].isin(['?'])
</code></pre>
<p>How do I print all columns that have at least one value <code>'?'</code>?</p>
<p>Data set looks like this:</p>
<pre><code>age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal target
0 28.0 1.0 2.0 130 132 0 2 185 0 0 ? ? ? 0
</code></pre>
<p>I'm looking for a function that will print <code>slope,ca,thal</code> (the ones that contains <code>'?'</code>)</p>
| [
{
"answer_id": 74259679,
"author": "Scott B",
"author_id": 17720354,
"author_profile": "https://Stackoverflow.com/users/17720354",
"pm_score": 1,
"selected": false,
"text": "JOIN"
},
{
"answer_id": 74522542,
"author": "Waleed Ibrahim Osman",
"author_id": 20565179,
"au... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14995131/"
] |
74,256,236 | <p>I'm coding in C on visual studio and can't seem to figure out a fix for scanf_s scanning only once.</p>
<pre><code>#include <stdio.h>
#include <string.h>
int main() {
int duration;
int cost;
printf("1 day = 50$\nFor students:\n2 days = 90$\n3 days = 120$\n");
question_1:
printf("What's your stay duration in days?\n");
scanf_s("%d", &duration);
if (duration == 1)
{
printf("That will be 50$.");
}
else
{
if (duration == 2 || duration == 3)
{
question_2:
printf("Are you a student?\n");
char answer[20];
scanf_s("%s", &answer, sizeof(answer));
if (strcmp(answer, "yes") == 0)
{
if (duration == 2)
{
printf("That will be 90$.");
}
else
{
printf("That will be 120$.");
}
}
else
{
if (strcmp(answer, "no") == 0)
{
cost = duration * 50;
printf("That will be %d$.", cost);
}
else
{
goto question_2;
}
}
}
else
{
goto question_1;
}
}
}
</code></pre>
<p>When inputting a word instead of a number for "duration" the program repeatedly prints "What's your stay duration in days?" instead of scanning for another input, what should I change?</p>
| [
{
"answer_id": 74259679,
"author": "Scott B",
"author_id": 17720354,
"author_profile": "https://Stackoverflow.com/users/17720354",
"pm_score": 1,
"selected": false,
"text": "JOIN"
},
{
"answer_id": 74522542,
"author": "Waleed Ibrahim Osman",
"author_id": 20565179,
"au... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373993/"
] |
74,256,250 | <p>I like the Build XY Graph express VI, because it allows you to add one point at a time and it incrementally plots the new point. However, it allows only one plot in XY graph. If I want to have two or more plots in the same XY graph, is there an equivalent of the Build XY Graph express vi?
Thank you.
Girish Joglekar</p>
| [
{
"answer_id": 74259679,
"author": "Scott B",
"author_id": 17720354,
"author_profile": "https://Stackoverflow.com/users/17720354",
"pm_score": 1,
"selected": false,
"text": "JOIN"
},
{
"answer_id": 74522542,
"author": "Waleed Ibrahim Osman",
"author_id": 20565179,
"au... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2600148/"
] |
74,256,261 | <p>I want to filter an array object, into a separate individual variable with array?</p>
<pre><code>// The given array
const dummy = [
{
id: 1,
name: 'John',
},
{
id: 2,
name: 'Jane',
},
{
id: 3,
name: 'Jane',
},
]
// Expected Output
// let number = [1,2]
// let name = ["John", "Jane"]
</code></pre>
| [
{
"answer_id": 74256357,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 0,
"selected": false,
"text": "const dummy = [\n {\n id: 1,\n name: 'John',\n },\n {\n id: 2,\n name: 'Jane',\n },\n {\n ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18258422/"
] |
74,256,266 | <h2>Scenario</h2>
<p>I'm given a function with an asynchronous callback like</p>
<pre class="lang-js prettyprint-override"><code>let readFile: (path: string, callback: (line: string, eof: boolean) => void) => void
</code></pre>
<p>Though I would prefer a function using <em><strong>AsyncIterable</strong></em>/<em><strong>AsyncGenerator</strong></em> signature instead:</p>
<pre class="lang-js prettyprint-override"><code>let readFileV2: (path: string) => AsyncIterable<string>
</code></pre>
<h2>Problem</h2>
<p>Without <code>readFileV2</code>, I have to read a file like</p>
<pre class="lang-js prettyprint-override"><code>let file = await new Promise((res, err) => {
let file = ''
readFile('./myfile.txt', (line, eof) => {
if (eof) { return res(file) }
file += line + '\n'
})
})
</code></pre>
<p>.. while <code>readFileV2</code> allows me to do it cleaner like</p>
<pre class="lang-js prettyprint-override"><code>let file = '';
for await (let line of readFileV2('./myfile.txt')) {
file += line + '\n'
}
</code></pre>
<h2>Question</h2>
<p><strike>Is there a way for me to transform <code>readFile</code> into <code>readFileV2</code>?</strike></p>
<p><strong>Updated for clarification:</strong></p>
<p>Is there a <em>general approach</em> to transform a function with an async callback argument to an AsyncGenerator/AsyncIterable variant?</p>
<p>And can this approach be demonstrated on the <code>readFile</code> function above?</p>
<h2>References</h2>
<p>I see two related questions here:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/50862698/how-to-convert-node-js-async-streaming-callback-into-an-async-generator/60962966#60962966">How to convert Node.js async streaming callback into an async generator?</a></li>
<li><a href="https://stackoverflow.com/questions/43699067/how-to-convert-callback-based-async-function-to-async-generator">How to convert callback-based async function to async generator</a></li>
</ul>
<p>However, they don't seem to provide a clear answer.</p>
| [
{
"answer_id": 74263898,
"author": "vitaly-t",
"author_id": 1102051,
"author_profile": "https://Stackoverflow.com/users/1102051",
"pm_score": 1,
"selected": false,
"text": "const {createReadStream} = require('fs');\nconst {createInterface} = require('readline');\n\nfunction readFileLines... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13088508/"
] |
74,256,278 | <p>I wanted to improve my Firestore query, but I got an error.
I have simple Firestore db: collection 'Spanish' where each collection has only one document 'words'.
The original working code code is:</p>
<pre><code>var myData = await FirebaseFirestore.instance
.collection('Spanish')
.get()
.then((snapshot) {
if (snapshot != null) {
snapshot.docs.forEach((element) {
element.data().forEach((key, value) {
myMap.putIfAbsent(key, () => value);
myDictionary.add(key + '@' + value);
});
});
</code></pre>
<p>Since the collection has only one document I tried to improve the query by getting all fields from the selected document, so my new query is:</p>
<pre><code>var myData = await FirebaseFirestore.instance
.collection('Spanish').doc('words')
.get()
.then((snapshot) {
if (snapshot != null) {
snapshot.data().forEach((key, value) {
myMap.putIfAbsent(key, () => value);
myDictionary.add(key + '@' + value);
});
</code></pre>
<p>Now I am getting error on forEach, which says:</p>
<blockquote>
<p>"The method 'forEach' can't be unconditionally invoked because the receiver can be 'null'.</p>
<p>Try making the call conditional (using '?.') or adding a null check to the target"</p>
</blockquote>
<p>But I am checking for null in "if (snapshot != null)"
Any ideas why?</p>
| [
{
"answer_id": 74263898,
"author": "vitaly-t",
"author_id": 1102051,
"author_profile": "https://Stackoverflow.com/users/1102051",
"pm_score": 1,
"selected": false,
"text": "const {createReadStream} = require('fs');\nconst {createInterface} = require('readline');\n\nfunction readFileLines... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373986/"
] |
74,256,279 | <p>I am able to send notifications to android and apple devices using the "Compose notification" on firebase.
<a href="https://i.stack.imgur.com/3lX3g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3lX3g.png" alt="firebase compose notification pic" /></a></p>
<p>I am trying to send a message using cloud functions but I am having a hard time.</p>
<p>I can see all the data I want from the following code snip (cloud function)</p>
<pre><code>const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.onUpdate = functions.firestore
.document("chat messages/{docId}")
.onCreate((snapshot, context) => {
console.log("1");
console.log(snapshot.data());
console.log("2");
console.log(snapshot.data()["User id"] );
console.log(snapshot.data()["Chat message"] );
console.log("3");
});
</code></pre>
<p>now I need to target the phone to send the notification.
How do I do this?</p>
| [
{
"answer_id": 74257755,
"author": "Juan Casas",
"author_id": 17281101,
"author_profile": "https://Stackoverflow.com/users/17281101",
"pm_score": 1,
"selected": true,
"text": "/*\nto fix issues:\n(cd functions && npx eslint . --fix)\nto upload code:\nfirebase deploy\nto do both:\n(cd fun... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17281101/"
] |
74,256,286 | <p>I have got some of the latest version of the VirtualTreeView and try to
change the background color of the whole row of <code>TVirtualStringTree</code> both in selected and in non-selected states (<code>toFullRowSelect</code> is included somewhere). There is a lot of similar questions with different answers but none seems to fit well. In all of them you just write a handler that includes the code snippet like this:</p>
<pre><code> TargetCanvas.Brush.Color := SomeColor;
TargetCanvas.FillRect(SomeRect);
</code></pre>
<p>But it's not that simple as I thought:</p>
<ol>
<li><code>OnBeforeCellPaint</code> handler works well only if the row is not
selected</li>
<li><code>OnDrawText</code> handler works in both states but the entire
row looks divided by spaces between cells</li>
<li><code>OnBeforeItemErased</code> affects the whole row but again if it is not in selected state</li>
<li>The painting in some other handlers either are repainted later automatically or require fully manual drawing which looks excessive for a simple task.</li>
</ol>
<p>So I failed to find an easy way.</p>
<p>I added the additional conditions:</p>
<ol>
<li>The row must stay in selected state cause the tree could be in MultiSelected mode (<code>toMultiSelect</code> is included).</li>
<li>The colors of selected and unselected states of the row may differ as well as different selected rows may have different colors too.</li>
</ol>
<p>The best I could create is to write a handler on <code>OnDrawTexr</code> event:
<a href="https://i.stack.imgur.com/t9lWe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t9lWe.png" alt="tree" /></a></p>
<p>This tree is produced by an array of records (oversimplified):</p>
<pre><code>type
TJob=record
Running:Boolean;// the job is stopped or running
MaxDuration:integer;//0 - infinite, or seconds
Start:TDateTime;//The job start time
end;
</code></pre>
<ul>
<li>if the job is stopped its row should behave in the default treeview
way.</li>
<li>If the job is running and infinite it should be colored e.g. as
green, if selected - as thick green</li>
<li>If the job is running and have
limited duration its row should have a transitioned color between
green and red that changes constantly while meeting its deadline. If
selected the color should be brighter.</li>
</ul>
| [
{
"answer_id": 74257755,
"author": "Juan Casas",
"author_id": 17281101,
"author_profile": "https://Stackoverflow.com/users/17281101",
"pm_score": 1,
"selected": true,
"text": "/*\nto fix issues:\n(cd functions && npx eslint . --fix)\nto upload code:\nfirebase deploy\nto do both:\n(cd fun... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886550/"
] |
74,256,289 | <p>I have a problem, I don't know how to solve it, I will try not to give too much context and focus on the problem</p>
<p>A worker marks hours every day in his work, this is stored in the "dayli_data" array when the worker did not perform his hours then the "time_off" array is returned</p>
<p>I have two arrays that I don't know how to unify, when dayli_data brings the information I must check if the user_id is different from the time_off and if it is, I must bring the list of "...dayli_data" + what it found in "...time_off"</p>
<p>So let's say that the user with ID = 957706 on <strong>10/29/2022</strong> marked 8 hours</p>
<pre><code>[
{
user_id: 957706,
tracked: 8,
date: "2022-10-29"
},
{
user_id: 1171637,
tracked: 8,
date: "2022-10-29"
}
]
</code></pre>
<p>But on <strong>10/31/2022</strong> he don't mark hours, so in the record "dayli_data" it won't come <strong>(just a short example of the data)</strong></p>
<pre><code>[
{
user_id: 1171637,
tracked: 8,
date: "2022-10-29"
}
]
</code></pre>
<p>But it brings information in the time_off array</p>
<pre><code>[{ user_id: 957706, reason: 'permission', tracked: 4, entry_date: "2022-10-31"}]
</code></pre>
<p>then I should be able to unify the arrays and return:</p>
<pre><code>[
{
user_id: 957706,
tracked: 4,
reason: 'permission',
date_start: "2022-10-31",
date: "2022-10-31"
},
{
user_id: 1171637,
tracked: 7,
date: "2022-10-31"
}
]
</code></pre>
<p>How can I conditionally merge arrays?</p>
<p>I tried this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let data_daily = [{
"id": 6583194952,
"date": "2022-10-31",
"user_id": 1171637,
"project_id": 2082652,
"task_id": 111873721,
"keyboard": 3891,
"mouse": 8714,
"overall": 11875,
"tracked": 29494,
"input_tracked": 29494,
"manual": 0,
"idle": 0,
"resumed": 0,
"billable": 17700,
"created_at": "2022-10-31T14:14:05.300434Z",
"updated_at": "2022-10-31T11:02:04.105898Z"
},
{
"id": 6583205067,
"date": "2022-10-31",
"user_id": 1762437,
"project_id": 2082652,
"task_id": 111407896,
"keyboard": 3843,
"mouse": 13066,
"overall": 15760,
"tracked": 29275,
"input_tracked": 29275,
"manual": 0,
"idle": 0,
"resumed": 0,
"billable": 29275,
"created_at": "2022-10-31T14:15:54.284572Z",
"updated_at": "2022-10-31T11:01:52.894533Z"
}
]
let time_off = [{
"user_id": 957963,
"date_start": "2022-10-31",
"date_end": "2022-11-05",
"rol": "DEV",
"reason": "Permiso",
"created_at": "2022-10-31T15:46:42+00:00",
"kpi": "permission",
"activity": 60,
"tracked": 4,
"user": {
"user_id": 957963,
"name": "Isaac xxx",
"email": "isaac.correo@c.com",
"status": "active",
"created_at": "2022-10-31T06:36:42.898255Z",
"updated_at": "2022-10-31T13:59:08.095330Z",
"daily_hours": 8,
"username": "ISAAC XXX",
"time_work": "FULLTIME",
"job_position": "Junior"
}
},
{
"user_id": 957706,
"date_start": "2022-10-31",
"date_end": "2022-10-31",
"rol": "DEV",
"reason": "permission",
"created_at": "2022-10-31T06:18:25+00:00",
"kpi": "permission",
"activity": 60,
"tracked": 4,
"user": {
"user_id": 957706,
"name": "Cesar xxxx",
"email": "cesarz@c.com",
"status": "active",
"created_at": "2022-10-31T19:41:27.759263Z",
"updated_at": "2022-10-31T15:20:46.296994Z",
"daily_hours": 8,
"username": "CESAR XXXX",
"time_work": "FULLTIME",
"job_position": "Junior "
}
}
]
const result = data_daily.map(element => {
return time_off.length > 0 ? { ...time_off
} : { ...element
}
});
console.log(result)</code></pre>
</div>
</div>
</p>
<p>But it only returns the elements of the time_off. What am I doing wrong?</p>
| [
{
"answer_id": 74257755,
"author": "Juan Casas",
"author_id": 17281101,
"author_profile": "https://Stackoverflow.com/users/17281101",
"pm_score": 1,
"selected": true,
"text": "/*\nto fix issues:\n(cd functions && npx eslint . --fix)\nto upload code:\nfirebase deploy\nto do both:\n(cd fun... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14050441/"
] |
74,256,310 | <p>I am doing some code challenges using Typescript in VS code. When I try to run the code and see the output, I get "Code Language is not supported or defined". The language mode is set to Typescript React (I also tried just Typescript). And the file has a .tsx ending. Finally, I also did compile the file and make a duplicate .js version. Is there something I am forgetting?</p>
| [
{
"answer_id": 74256577,
"author": "score30",
"author_id": 12521653,
"author_profile": "https://Stackoverflow.com/users/12521653",
"pm_score": 3,
"selected": true,
"text": ".ts"
},
{
"answer_id": 74257057,
"author": "MalwareMoon",
"author_id": 20241005,
"author_profil... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18301718/"
] |
74,256,314 | <pre><code>char *ft_between(char *str, size_t from, size_t to)
{
char *between;
between = malloc(16);
while ((from >=0) && (from < to) && (to < ft_strlen(str)))
{
*(between++) = str[from++];
}
*between = '\0';
printf("%s\n", between); // print nothing
printf("%s\n", between - 16); // print between but never had to do this before...
return (between);// even on calling function the pointer still at end of string
}
</code></pre>
<p>I think it's because I changed the address of between using ++ but I usually do that and never had this behavior... is that because of malloc ???</p>
<p>Is there someting I missed ?
Is thear a way to "rewind" the string lol
If I do it via a counter ie. between[counter++] = str[from++]; it works but I wanted to do via pointers as it's faster... from what I've red !</p>
<p>in this example str is itterate with ++ until the end to add char
but when return in calling function a printf will print all str</p>
<pre><code>void ft_nbr2str(char *str, size_t nbr, char *base, size_t base_len)
{
if (nbr >= base_len)
{
ft_nbr2str(str, (nbr / base_len), base, base_len);
while (*str != '\0')
str++;
*str = base[nbr % base_len];
}
else
*str = base[nbr];
}
</code></pre>
| [
{
"answer_id": 74256489,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 1,
"selected": false,
"text": "between"
},
{
"answer_id": 74256531,
"author": "Vlad from Moscow",
"author_id": 2877241,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20369940/"
] |
74,256,337 | <p>from the original code I can't get the same result</p>
<p>here is the original code</p>
<pre><code> loadPreviousEvents() {
mySelectedEvents = {
"2022-09-13": [
{"eventDescp": "11", "eventTitle": "111"},
{"eventDescp": "22", "eventTitle": "22"}
],
"2022-09-30": [
{"eventDescp": "22", "eventTitle": "22"}
],
"2022-09-20": [
{"eventTitle": "ss", "eventDescp": "ss"}
]
};
print(mySelectedEvents);
}
</code></pre>
<p>I want to retrieve the same thing from my database</p>
<p>here is what i tried without success</p>
<pre><code>loadPreviousEvents() async {
var url = 'http://prospection.global-aeit.com/getEvents.php';
var res = await http.get(Uri.parse(url));
var response = json.decode(res.body) as List;
print(response);
var mySelectedEvents =
(response.map((e) async => GroupBy.fromJson(e))).toList();
print(mySelectedEvents);
return mySelectedEvents;
}
</code></pre>
<p>by making print of <code>print(mySelectedEvents);</code></p>
<pre><code>[Instance of 'Future<GroupBy>', Instance of 'Future<GroupBy>', Instance of 'Future<GroupBy>', Instance of 'Future<GroupBy>', Instance of 'Future<GroupBy>']
</code></pre>
<p>print of <code>print(response);</code> gives</p>
<p>[{date: 2022-09-17, eventDescp: azerty, eventTitle: azertyui}, {date: 2022-09-17, eventDescp: 11, eventTitle: AZE}, {date: 2022-09-17, eventDescp: 22, eventTitle: 4556}, {date: 2022-09-20, eventDescp: 77, eventTitle: HHJ}, {date: 2022-09-17, eventDescp: 44, eventTitle: BYYY}]</p>
| [
{
"answer_id": 74256428,
"author": "venir",
"author_id": 15831316,
"author_profile": "https://Stackoverflow.com/users/15831316",
"pm_score": 0,
"selected": false,
"text": "map"
},
{
"answer_id": 74257243,
"author": "Zana Souleymane Coulibaly",
"author_id": 17205746,
"... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17205746/"
] |
74,256,341 | <p>I want to ask about how to make a trigger that run when there are changes on different spreadsheet (<strong>Source spreadsheet</strong>) and on specific column.
<br />
I have <strong>2 different spreadsheet</strong> (<strong>Source Spreadsheet and Target spreadsheet</strong>) and the trigger will working on target spreadsheet when there are changes that happened in the specific column of the source spreadsheet. I've just made the code, but it's not working. <strong>This code was made on the target spreadsheet</strong>. I've already use the onEdit() and onChange() trigger, but nothing happen or run this script.
<br />
This code still show some error like:</p>
<blockquote>
<p>TypeError: e.source.openById is not a function</p>
</blockquote>
<br />
Here is the code that I've been made on the target spreadsheet:
<br />
<pre><code>function inChange(e) {
var source_spreadsheet_sheetName = e.source.openById('').getName(); //ID of source spreadsheet
var Row = e.source.getActiveCell().getRow();
var Column = e.source.getActiveCell().getColumn();
if (source_spreadsheet_sheetName == '' && Row >= 2 && Column == 2) { //the name of sheet from source spreadsheet and the specific column that has changes on it.
myFunction(); //It will run the process of this myFunction script that I've been made on target spreadsheet
}
}
</code></pre>
| [
{
"answer_id": 74256700,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 0,
"selected": false,
"text": "source_spreadsheet == ''"
},
{
"answer_id": 74259023,
"author": "ValLeNain",
"author_id": 3410584,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18537212/"
] |
74,256,342 | <p>Does anyone else have this issue? For reference check this screenshot: <a href="https://i.stack.imgur.com/AVxy7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AVxy7.png" alt="Error" /></a></p>
<p>PIP is also up to date and I already tried reinstalling it but it didn't work neither. I'm using VS Code. It also worked just fine yesterday but today it didn't anymore for some reason.</p>
| [
{
"answer_id": 74256494,
"author": "learner",
"author_id": 17658327,
"author_profile": "https://Stackoverflow.com/users/17658327",
"pm_score": -1,
"selected": false,
"text": "py -m pip install mss\n"
},
{
"answer_id": 74258304,
"author": "JialeDu",
"author_id": 19133920,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374112/"
] |
74,256,365 | <p>While typing git init command in the dictionary in does not open a new repository file in the folder It shows- "Reinitialized existing Git repository in C:/Users/User/Desktop/MyProject/.git/" however in the folder - MyProject there is no actual git repository created. Could you please advise?</p>
<p>I tried to create a git repository file; opened the particular folder; typed cmd in the name of the folder; it opened command prompt and I typed git init; no repository created..</p>
| [
{
"answer_id": 74256494,
"author": "learner",
"author_id": 17658327,
"author_profile": "https://Stackoverflow.com/users/17658327",
"pm_score": -1,
"selected": false,
"text": "py -m pip install mss\n"
},
{
"answer_id": 74258304,
"author": "JialeDu",
"author_id": 19133920,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374142/"
] |
74,256,366 | <p>I have a ConcurentBag where Bin is an object of 4 members (int Max, in Min, int Avg, double median). I have hundreds and sometimes thousands of Bin objects in the list, and have to calculate Max, Min, Avg, and Medium for each member:</p>
<pre><code> binnedGeoData.Max = mSingleGpsBinList.Select(x => x.Max).Max();
binnedGeoData.Min = mSingleGpsBinList.Select(x => x.Min).Min();
binnedGeoData.Avg = (int)mSingleGpsBinList.Select(x => x.Avg).Average();
// Must convert to double[]
double[] medArray = mSingleGpsBinList.Select(x => (double)x.Median).ToArray();
binnedGeoData.Median = (int)Math.Round(Statistics.Median(medArray), 0);
</code></pre>
<p>However, somehow the result of all calculations gives me 0.
For example if Max of bin1 is 4 and bi2n is 8, and bin3 is 2,
The Max of those would be 8, but the result is 0.</p>
<p>One more thing: the collection can also be changed to SerializedCollection...</p>
<p>Any ideas?</p>
| [
{
"answer_id": 74256494,
"author": "learner",
"author_id": 17658327,
"author_profile": "https://Stackoverflow.com/users/17658327",
"pm_score": -1,
"selected": false,
"text": "py -m pip install mss\n"
},
{
"answer_id": 74258304,
"author": "JialeDu",
"author_id": 19133920,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8407516/"
] |
74,256,368 | <p>I have the following dataframe</p>
<pre><code>import pandas as pd
movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama', 'Comedy', 'Animation'], 'runtime' : [0, 100, 0, 120,0]}
df = pd.DataFrame(movies)
</code></pre>
<p>I also have the following dictionary which contains the median runtime of a movie for a given genre</p>
<pre><code>genre_dict = {'Action': 107.0, 'Adventure': 108.0, 'Animation': 86.0, 'Comedy': 99.0, 'Crime': 111.0, 'Drama': 111.0, 'Family': 92.0, 'Fantasy': 103.0, 'History': 124.0, 'Horror': 94.5, 'Music': 105.0, 'Mystery': 100.5, 'Romance': 104.0, 'Science Fiction': 106.0, 'TV Movie': 92.0, 'Thriller': 102.0, 'War': 118.0, 'Western': 119.0}
</code></pre>
<p>I would like to replace the runtime values which equal 0 with the median based on the genre which would result in the following dataframe</p>
<pre><code>movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama', 'Comedy', 'Animation'], 'runtime' : [107, 100, 111, 120,86]}
df = pd.DataFrame(movies)
</code></pre>
<p>I tried using a map with the following code</p>
<pre><code>df['runtime'] = df['genre'].map(genre_dict)
</code></pre>
<p>However, this replaced the runtime of every movie as there is no condition to state only replace if the current runtime is 0. Any help on how to include the condition would be appreciated, thank you.</p>
| [
{
"answer_id": 74256454,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374111/"
] |
74,256,401 | <p>I have a function whose return type should depend on the provided arguments.</p>
<pre class="lang-js prettyprint-override"><code>const test = (flag: boolean): typeof flag extends true ? "yes" : "no" => {
if (flag === true) {
return "yes"
} else {
return "no"
}
}
</code></pre>
<p>Why does TSC raise the error <code>Type '"yes"' is not assignable to type '"no"'.ts(2322)</code> for the line <code>return "yes"</code>?</p>
<p>Using Typescript 4.8.4</p>
| [
{
"answer_id": 74256454,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2143524/"
] |
74,256,406 | <p>In a laravel blade page I have a controller sending <code>planTypes</code> and stored like this:</p>
<pre><code>arr = [];
var planTypes = @json($planTypes);
$('#multiselect').change(function (e) {
var plan_id = $(this).val();
arr.push(plan_id);
});
</code></pre>
<p>What it does? For any change in a dropdown listing all planTypes I capture the unique id and store it in a js array (<code>arr</code>)</p>
<p>The user has the possibility to add multiple planTypes in the same page without the need to refresh and that is why the <code>change</code> js function</p>
<p>Whenever I render the new dropdown, I would like to only display the remaining unused planTypes and I try to do it like this:</p>
<pre><code>var item=
+' <select id="multiselect" name="planTypes[0][]" class="selectpicker form-control type">'
+' <option value="">--</option>'
@foreach($planTypes as $planType)
if(!arr[{{ $planType->id }}]) {
+' <option value="{{ $planType->id }}">{{ $planType->name }}</option>'
}
@endforeach
</code></pre>
<p>But for some strange reasons, I cannot make it work like that, combining blade @foreach and javascript if</p>
<p>Could someone point me to the correct approach?</p>
<p>Thank you!
+' '</p>
| [
{
"answer_id": 74256454,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671880/"
] |
74,256,449 | <p>I need to sort a vector of coordinates (x, y >= 1) in a way that every next point from the vector is the closest one to the previous by calculating the distance with the formula from getDistance().</p>
<p>My current solution is too slow as I need the program to be able to finish in 5 seconds or less with vector length (N) equal to 100 000.</p>
<pre><code>struct Point {
int ind;
int x;
int y;
double dist;
};
double getDist(int x1, int y1, int x2, int y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
vector<Point> cordSort(vector<Point> vect) {
vector<Point> finalDistVect;
finalDistVect.push_back(vect[0]);
Point firstPoint = vect[0];
vect.erase(vect.begin());
for (i = 0; i < pcVect.size() - 1; i++) {
sort(vect.begin(), vect.end(), [firstPoint](const Point & a, const Point & b) {
return getDist(firstPoint.x, firstPoint.y, a.x, a.y) < getDist(firstPoint.x, firstPoint.y, b.x, b.y);
});
finalDistVect.push_back(vect[0]);
finalDistVect[i].dist = getDist(firstPoint.x, firstPoint.y, vect[0].x, vect[0].y);
firstPoint = vect[0];
vect.erase(vect.begin());
}
return finalDistVect;
}
</code></pre>
<p>vect is the initial vector with coordinates sorted by:</p>
<pre><code> sort(vect.begin(), vect.end(), [](const Point & a, const Point & b) {
if (a.x + a.y != b.x + b.y) {
return a.x + a.y < b.x + b.y;
}
return a.x < b.x;
});
</code></pre>
<p>I am thinking about implementing bucket sort but I don't know if it will work for my problem.</p>
| [
{
"answer_id": 74256454,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 0,
"selected": false,
"text": "movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374132/"
] |
74,256,462 | <p>I have two columns to compare. All cell values come from the ROUNDUP function. <strong>=ROUNDUP(C6/D12,0)</strong> etc.</p>
<p><a href="https://i.stack.imgur.com/n6ESr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n6ESr.png" alt="enter image description here" /></a></p>
<p>I want the larger, or equal, of the two in each row to be green and the smaller red. Using the formula, it does not work as expected. If I do the same with numbers typed, not the formula, it works. It appears the formatting applies to the formula and not the value.</p>
<p>That is the first half of the problem. I also want to autofill/paint the conditional formatting to numerous cells, but it always compares to the top left cell, rather than the two cells on the same row.</p>
<p>If I use the color scales formatting it works, but I do not want the scales, just red/green.</p>
<p>It seems hard to believe that what I want to do is not possible. Can someone please help me with this. Thanks in advance.</p>
| [
{
"answer_id": 74257389,
"author": "Max R",
"author_id": 19662289,
"author_profile": "https://Stackoverflow.com/users/19662289",
"pm_score": 0,
"selected": false,
"text": "copy"
},
{
"answer_id": 74261278,
"author": "Tom Sharpe",
"author_id": 3894917,
"author_profile"... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15789090/"
] |
74,256,470 | <p>How can I replace string in list using dictionary?</p>
<p>I have</p>
<pre><code>text = ["h#**o+","+&&&orld"]
</code></pre>
<pre><code>replacement = {"#":"e","*":"l","+":"w","&":""}
</code></pre>
<p>I want:</p>
<pre><code>correct = ["Hellow
World"]
</code></pre>
<p>I have try:</p>
<pre><code>def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
</code></pre>
<p>But:
AttributeError: 'list' object has no attribute 'replace'</p>
| [
{
"answer_id": 74256752,
"author": "Paul Becotte",
"author_id": 2259934,
"author_profile": "https://Stackoverflow.com/users/2259934",
"pm_score": 0,
"selected": false,
"text": "text"
},
{
"answer_id": 74256759,
"author": "Modularizer",
"author_id": 15607248,
"author_p... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373888/"
] |
74,256,472 | <p>I'm trying to make a dataframe pulled from an excel file more user-friendly by creating a "Type" column.
The data can be found here: <a href="https://www.dmo.gov.uk/data/pdfdatareport?reportCode=D1A" rel="nofollow noreferrer">https://www.dmo.gov.uk/data/pdfdatareport?reportCode=D1A</a> (direct download excel link here: <a href="https://www.dmo.gov.uk/umbraco/surface/DataExport/GetDataExport?reportCode=D1A&exportFormatValue=xls&parameters=%26COBDate%3D11%2F04%2F2011" rel="nofollow noreferrer">https://www.dmo.gov.uk/umbraco/surface/DataExport/GetDataExport?reportCode=D1A&exportFormatValue=xls&parameters=%26COBDate%3D11%2F04%2F2011</a>)</p>
<p>As you can probably see, the type of data is all grouped together in column A, like so: <a href="https://i.stack.imgur.com/1hraD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1hraD.png" alt="enter image description here" /></a></p>
<p>What I'd like to do is is change title "Conventional Gilts" to being "Name", and create a "Type" column that has the different categories pulled from their grouped title. In the linked file, the "Types" would be: "Ultra-Short", "Short", "Medium", "Long", "Index-linked Gilts (3-month Indexation Lag)", "Undated Gilts (non "rump")", and ""Rump" Gilts".</p>
<p>While I feel I would need to do some form of pattern recognition using a package like grepl, I'm not sure how I can achieve this from a 'dynamic' perspective (changing if new categories are created).</p>
<p>Any advice on how to achieve this (or even achieve this in a function) would be greatly appreciated.</p>
| [
{
"answer_id": 74256911,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "library(readxl)\nlibrary(tidyverse)\n\ngilts <- read_xls(\"C:/Users/Administrator/Documents/gilts.xls\")\n\ng... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11721283/"
] |
74,256,483 | <p>I have a data set with statistics that I collect from text. The processing method sometimes does not work correctly, and I need to correct the output data. I know they are supposed to be cumulative, but sometimes I get incorrect data.</p>
<p>Time series data that should accumulate over time. Right now I'm getting the following, sample snippet:</p>
<pre><code>df
date value
2021-07-20 21347.0
2021-07-24 21739.0
2021-08-02 22.0
2021-08-03 22.0
2021-08-06 22947.0
2021-08-17 4.0
</code></pre>
<p>As you can see, the data is cumulative, but some values are defined incorrectly.
I would like such values to be converted to <code>nan</code>.</p>
<p>How can I do that? The final result is expected to be as follows:</p>
<pre><code>df
date value
2021-07-20 21347.0
2021-07-24 21739.0
2021-08-02 nan
2021-08-03 nan
2021-08-06 22947.0
2021-08-17 nan
</code></pre>
| [
{
"answer_id": 74256911,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "library(readxl)\nlibrary(tidyverse)\n\ngilts <- read_xls(\"C:/Users/Administrator/Documents/gilts.xls\")\n\ng... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744714/"
] |
74,256,527 | <p>This code contains 3 file handling related functions which read from a file named "mno". But only the 1st called function in the main() is working. If the 1st function of the list is commented then, only the 2nd function will work and the third won't. Same goes for the 3rd one</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
void countVowel(char fin[])
{
FILE *fl;
char ch;
int count = 0;
fl = fopen(fin, "r");
while (ch != EOF)
{
ch = tolower(fgetc(fl));
count += (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') ? 1 : 0;
}
fclose(fl);
printf("Number of Vowels in the file \" %s \"-> \t %d \n", fin, count);
}
void countConsonant(char fin[])
{
FILE *fl;
char ch;
int count = 0;
fl = fopen(fin, "r");
while (ch != EOF)
{
ch = tolower(fgetc(fl));
count += (!(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') && (ch >= 'a' && ch <= 'z')) ? 1 : 0;
}
fclose(fl);
printf("Number of Consonant in the file \" %s \"-> \t %d \n", fin, count);
}
void countAlphabet(char fin[])
{
FILE *fl;
char ch;
int count = 0;
fl = fopen(fin, "r");
while (ch != EOF)
{
ch = tolower(fgetc(fl));
count += (ch >= 'a' && ch <= 'z') ? 1 : 0;
}
fclose(fl);
printf("Number of Alphabets in the file \" %s \"-> \t %d \n", fin, count);
}
int main()
{
countVowel("mno"); // output -> 10
countConsonant("mno"); // output -> 0
countAlphabet("mno"); // output -> 0
return 0;
}
</code></pre>
<p>Here are the contents of "mno" file -></p>
<pre><code>qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM, 1234567890
</code></pre>
| [
{
"answer_id": 74256606,
"author": "Tenobaal",
"author_id": 18861247,
"author_profile": "https://Stackoverflow.com/users/18861247",
"pm_score": 1,
"selected": true,
"text": "ch"
},
{
"answer_id": 74256863,
"author": "Craig Estey",
"author_id": 5382650,
"author_profile... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19692380/"
] |
74,256,539 | <p>While there is user in the database, another user with exactly the same credentials is "successfully" inserted in the database...</p>
<p>Hello! I'm building my own ecommerce app and I included spring security. Now, while I was developing security part of the app, I tried it to see if it's working and once I entered desired info in the request body, for the first request the user was successfully inserted in the database, but when I tried to do it the second time, to check if the <code>userExists</code> which throws and error that user is already registered, works, it just added another user with the same credentials (name, lastname, mail and so). I go to userRepository to check if there is already the user with the same email, it makes sense what i wrote, but it doesnt work...Please help...Here are all the files:</p>
<hr />
<p>EDIT : Mistakenly copied UserRegistrationController twice...So here is the userService.java:</p>
<pre><code>package com.marin.thrift.service;
import com.marin.thrift.dao.UserRepository;
import com.marin.thrift.entity.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final static String USER_NOT_FOUND = "user with email %s not found";
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByUsername(email).orElseThrow(()-> new UsernameNotFoundException(String.format(USER_NOT_FOUND, email)));
}
public String singUpUser(User user){
boolean userExists = userRepository.findByUsername(user.getEmail()).isPresent();
if(userExists){
return "user already in place";
}
String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
return "it works";
}
}
</code></pre>
<hr />
<pre class="lang-java prettyprint-override"><code>package com.marin.thrift.registration;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "api/v1/registration")
@AllArgsConstructor
public class UserRegistrationController {
private RegistrationService registrationService;
@PostMapping
public String register(@RequestBody registrationRequest request){
return registrationService.register(request);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.marin.thrift.registration;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "api/v1/registration")
@AllArgsConstructor
public class UserRegistrationController {
private RegistrationService registrationService;
@PostMapping
public String register(@RequestBody registrationRequest request){
return registrationService.register(request);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.marin.thrift.registration;
import com.marin.thrift.entity.Role;
import com.marin.thrift.entity.User;
import com.marin.thrift.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class RegistrationService {
private final EmailValidator emailValidator;
private final UserService userService;
public String register(registrationRequest request) {
Boolean isValidEmail = emailValidator.test(request.getEmail());
if (!isValidEmail){
throw new IllegalStateException("Email is not valid");
}
return userService.singUpUser(new User(request.getFirstName(), request.getLastName(),
request.getPassword(), request.getEmail(), Role.USER));
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.marin.thrift.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
@Entity
@Data
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "date_of_birth")
private Date dateOfBirth;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "email")
private String email;
private Role role;
private Boolean locked = false;
private Boolean enabled = false;
public User(String firstName, String lastName, String password, String email, Role role) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.email = email;
this.role = role;
}
public User() {
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.name());
return null;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername(){
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.marin.thrift.security.config;
import com.marin.thrift.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@AllArgsConstructor
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf()
.disable().authorizeRequests()
.antMatchers("/api/v*/registration/**").permitAll()
.anyRequest().authenticated().and().formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(bCryptPasswordEncoder);
provider.setUserDetailsService(userService);
return provider;
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.marin.thrift.registration;
import lombok.*;
@Getter
@AllArgsConstructor
@EqualsAndHashCode
@ToString
public class registrationRequest {
private final String firstName;
private final String lastName;
private final String password;
private final String email;
}
</code></pre>
| [
{
"answer_id": 74256606,
"author": "Tenobaal",
"author_id": 18861247,
"author_profile": "https://Stackoverflow.com/users/18861247",
"pm_score": 1,
"selected": true,
"text": "ch"
},
{
"answer_id": 74256863,
"author": "Craig Estey",
"author_id": 5382650,
"author_profile... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13372981/"
] |
74,256,544 | <p>I have a data frame:</p>
<pre><code>col1 col2 col3
a 1 n1
a 1 n2
a 2 n3
a 2 n4
b 2 n5
b 3 n6
c 4 n7
c 5 n8
c 6 n9
</code></pre>
<p>And I want to return all rows in which the value in col2 is shared by two or more categories in col1, i.e:</p>
<pre><code>a 2 n3
a 2 n4
b 2 n5
</code></pre>
<p>This seems like such a simple problem, but I've been pulling my hair out trying to find a solution that works. Been playing about with combinations of filter, duplicate in dplyr etc. to no avail. Much of the trouble comes from there being multiple duplicates in col2 I don't want to filter out (as they're the same in col1).</p>
<pre><code>data %>% group_by(col1) %>% filter(???)
</code></pre>
<p>Any help very much appreciated!</p>
| [
{
"answer_id": 74256606,
"author": "Tenobaal",
"author_id": 18861247,
"author_profile": "https://Stackoverflow.com/users/18861247",
"pm_score": 1,
"selected": true,
"text": "ch"
},
{
"answer_id": 74256863,
"author": "Craig Estey",
"author_id": 5382650,
"author_profile... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374241/"
] |
74,256,556 | <p>I am trying to figure out how to do a calculation on the single return from a SELECT and use the results of the calculation as part of an INSERT on the same sheet as used in the SELECT.</p>
<p>In order to clarify what I am trying (and failing) to do I created a simple example.</p>
<p>I have a table called numbers.
It has only one column,'x'.
Each row has an integer in the 'x' column.</p>
<p>I want to find the greatest integer, add 2 to it, and create a new row with that result.</p>
<pre><code>SELECT MAX(x)+2 FROM numbers
</code></pre>
<p>gives me the correct result, 10.</p>
<pre><code>INSERT INTO numbers VALUE(10)
</code></pre>
<p>works, but</p>
<pre><code>INSERT INTO numbers VALUE(SELECT MAX(x)+2 FROM numbers)
</code></pre>
<p>does not. It returns</p>
<blockquote>
<p>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT MAX(x)+2 FROM numbers)' at line 1"</p>
</blockquote>
<p>How should I rewrite the INSERT to use the result of SELECT in a calculation that then becomes the data inserted in the same sheet?</p>
| [
{
"answer_id": 74256613,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "insert/select"
},
{
"answer_id": 74278434,
"author": "Georg Richter",
"author_id": 6930501,
"autho... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5521490/"
] |
74,256,582 | <p>I'm struggling with making the program to summarize price of the products.</p>
<pre><code>prices_and_their_products = {
"Apple": 1,
"Water": 2,
"Grape": 3
}
shopping_list = ['Apple', 'Water']
</code></pre>
<p>I want the program to print "3".</p>
<p>The code I was trying to do it:</p>
<pre><code>total = 0
for particular_items in shopping_list:
total += prices_and_their_products.get(particular_items)
print(total)
</code></pre>
<p>I wont program to print the summary of products in "shopping_list". In this case: 3</p>
| [
{
"answer_id": 74256609,
"author": "E Joseph",
"author_id": 18011737,
"author_profile": "https://Stackoverflow.com/users/18011737",
"pm_score": 0,
"selected": false,
"text": "prices_and_their_products = {\n \"Apple\": 1,\n \"Water\": 2,\n \"Grape\": 3\n}\nshopping_list = ['Apple... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19713151/"
] |
74,256,619 | <p>Is there a way to quantify how many Firestore reads come from clients and how many from Google Cloud Functions?
I'd like to reduce my project reads costs.</p>
| [
{
"answer_id": 74256609,
"author": "E Joseph",
"author_id": 18011737,
"author_profile": "https://Stackoverflow.com/users/18011737",
"pm_score": 0,
"selected": false,
"text": "prices_and_their_products = {\n \"Apple\": 1,\n \"Water\": 2,\n \"Grape\": 3\n}\nshopping_list = ['Apple... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19290739/"
] |
74,256,644 | <p>I am new to programming in C and I am doing some activities for my first year in CS. The following activity consists of calculating the sum of squares of the digits of a user input number and the output should be as follows:</p>
<pre class="lang-none prettyprint-override"><code>Number: 1234
n=1234; sum=16
n=123; sum=25
n=12; sum=29
n=1; sum=30
Result: 30
</code></pre>
<p>I have got it for the most part, the thing that I don't understand is how to store a value in a variable, update said variable and print the result, all whilst being inside a loop.</p>
<p>This is what I came up with:</p>
<pre><code>int main() {
int num,i,sum=0,result,square;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
i=0;
while(num>i)
{
sum=num%10;
square=sum*sum;
printf("\nn=%d; sum= %d",num,square);
num=num/10;
}
result=sum;
printf("\nResult: %d",sum);
return 0;
}
</code></pre>
<p>How can I sum the square of the digits all together and print them as the example given?</p>
| [
{
"answer_id": 74256676,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "int digit = num % 10;\nsquare = digit * digit;\nsum += square;\nprintf(\"\\n=%d; sum= %d\", num, sum );\n"
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374015/"
] |
74,256,645 | <p>I am using Express and <a href="https://npmjs.com/package/http-proxy-middleware" rel="nofollow noreferrer">HPM</a> to proxy all requests to my website. This is all wrapped together into a little tool I call <code>ws-proxy</code> (ws for web server, not websocket).</p>
<p>One of the things proxied is my PVE/Proxmox Virtual Environment node, which uses secure WebSockets for the xterm.js and NoVNC consoles.</p>
<p><a href="https://paste.0xlogn.dev/punodedehe.js" rel="nofollow noreferrer">ws-proxy mre</a></p>
<p>What is weird about this, is after starting ws-proxy, I have about 30 seconds to open a console which will be sustained, but connections after this time will be closed with a 404 Not Found error. In the console, I see</p>
<pre><code>[HPM] Upgrading to WebSocket
[HPM] Upgrading to WebSocket (sometimes up to 4 times)
[HPM] Client disconnected
</code></pre>
<p>In my browser, I see the connection returned as 404.</p>
<p>With <code>websocat</code>, I get:</p>
<pre><code>websocat: WebSocketError: Received unexpected status code (404 Not Found)
websocat: error running
</code></pre>
<p>After additional debugging, I see something in the stack is sending a 404 and closing the connection, where just afterwards PVE sends the 101 Switching Protocols. This also sometimes causes a write after end error, sometimes socket hangup.</p>
<p>I've spent months looking into this and I have nowhere else to look at this point.</p>
<p><a href="https://github.com/chimurai/http-proxy-middleware/issues/826" rel="nofollow noreferrer">http-proxy-middleware#826 (by me)</a></p>
<p>404 in inspect element:</p>
<p><img src="https://i.stack.imgur.com/JLZ4i.png" alt="error shown in inspect element" /></p>
<p>error log in console after a recent attempt (error will change)</p>
<p><img src="https://i.stack.imgur.com/6ZAy8.png" alt="console showing errors" /></p>
<p>Full list of steps between client and server:</p>
<ul>
<li>Cloudflare</li>
<li>DigitalOcean w/ ssh-forward (not the problem)</li>
<li>ws-proxy</li>
<li>server</li>
</ul>
<p>Non-websocket (HTTP) requests work fine. This is with HPM v2 and Node.js v16.</p>
<hr />
<p><strong>Update 1</strong>
After Ryker's answer, I attempted the solution which should have fixed it, but I see something else of concern after setting the logLevel to debug:</p>
<pre><code>0|ws-proxy | pve.internal.0xlogn.dev ::1 - - [02/Nov/2022:23:17:14 +0000] "POST /api2/json/nodes/proxmox/lxc/105/termproxy HTTP/1.1" 200 487 "https://pve.internal.0xlogn.dev/?console=lxc&vmid=105&node=proxmox&resize=scale&xtermjs=1" "Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0"
0|ws-proxy | Upgrade request for vhost pve.internal.0xlogn.dev, proxy out
0|ws-proxy | [HPM] GET /api2/json/nodes/proxmox/lxc/105/vncwebsocket?port=5900&vncticket=REDACTED -> https://10.0.1.2:8006
0|ws-proxy | [HPM] GET /api2/json/nodes/proxmox/lxc/105/vncwebsocket?port=5900&vncticket=REDACTED -> http://10.0.1.108:80
0|ws-proxy | [HPM] Upgrading to WebSocket
0|ws-proxy | [HPM] Upgrading to WebSocket
0|ws-proxy | [HPM] Client disconnected
0|ws-proxy | [HPM] GET /api2/json/cluster/resources -> https://10.0.1.2:8006
</code></pre>
<p>Notice the <em>two</em> GET requests? Something is duplicating the request.</p>
<p>My <code>'upgrade'</code> event listener:</p>
<pre class="lang-js prettyprint-override"><code>httpsServer.on('upgrade', (req, socket, head) => {
if (!req.headers.host) {
console.log('No vhost specified in upgrade request. Ignoring.');
socket.end();
return;
} else {
console.log(`Upgrade request for vhost ${req.headers.host}, proxy out`);
vhostProxyMiddlewareList[req.headers.host].upgrade(req, socket, head);
}
})
</code></pre>
<p>What's even weirder here, is after restarting, I get a short time where the request isn't duplicated. Plus, there is a normal HTTP request anyway.</p>
<hr />
<p><strong>Update 2</strong>
After noticing the dual requests, I believe it is possible the module <a href="https://github.com/expressjs/vhost" rel="nofollow noreferrer">vhost</a> is causing a weird wildcard and sending the request to two target nodes. I will update shortly.</p>
<hr />
<p><strong>Update 3</strong>
After further work I believe this is true. However, vhost is not at fault, rather something is implicitly calling <code>next()</code>.</p>
| [
{
"answer_id": 74256676,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "int digit = num % 10;\nsquare = digit * digit;\nsum += square;\nprintf(\"\\n=%d; sum= %d\", num, sum );\n"
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14133230/"
] |
74,256,649 | <p>My question might sound weird because of how precise the problem is.</p>
<p>So, for the context, i have created a multidimensional array class :</p>
<pre><code>
template <typename TYPE>
requires std::integral<TYPE> || std::floating_point<TYPE>
class MultiArray {
int mDim = 0;
std::vector<int> mShape = {};
std::vector<TYPE> mArray = {};
[METHODS]
}
</code></pre>
<p>(A multiArray object need a dimension, a shape that is the same size of the dimension and the "mArray" is the array that have all the elements of the MultiArray which type is dependent of the template)</p>
<p>I'm trying to do an "=" operator overloading but my MultiArray objects can do maths operations (like numpy in python) so their type can change.
I want to be able to do things like this :</p>
<pre><code> MultiArray<int> M(2,5); //Creating a 5x5 matrix of zeroes
M = M+2.12; //I want M to be 5x5 matrix of 2.12
</code></pre>
<p>BUT my M is an "int" MultiArray and, because i'm adding a float, "M+2.12" return a "double" MultiArray so I have to convert my M into a MultiArray "double".</p>
<p>With the operator overloading, I tried :</p>
<pre><code> template <typename TYPE>
void operator=(MultiArray<TYPE> MultiArr) {
// defining the return type
using TYP_RE = std::conditional_t<std::is_floating_point<TYPE>::value, double, int>;
// we allocate the dimension and the shape
this->mDim = MultiArr.getDim();
this->mShape = MultiArr.getShape();
// we calculate the size of the 1-D mArray
int taille = 1;
for (int i = 0 ; i < mDim ; i++) {
taille *= this->mShape[i];
}
// we create a new array that will contain the new values
std::vector<TYP_RE> Array;
std::vector<TYPE>& Arr = MultiArr.getArray();
for (int i = 0 ; i < taille ; i++) {
Array.push_back(static_cast<TYP_RE>(Arr[i]));
}
// We allocate this new array into the old array
this->mArray.clear();
this->mArray.swap(Array);
}
</code></pre>
<p>The problem is with the last command. I can't swap a "double" vector with an "int" vector and I'm stuck here.</p>
<p>Have a nice day !</p>
| [
{
"answer_id": 74256676,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "int digit = num % 10;\nsquare = digit * digit;\nsum += square;\nprintf(\"\\n=%d; sum= %d\", num, sum );\n"
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20303832/"
] |
74,256,650 | <pre><code>SELECT
CONCAT(CONCAT(FIRST_NAME, ' '), LAST_NAME) AS "Fn and Ln",
HIRE_DATE AS "HireDate",
COMMISSION_PCT AS "Premium",
REPLACE('COMMISSION_PCT', '-', '0')
FROM HR.EMPLOYEES
</code></pre>
<p>I have to replace empty values in column <code>COMISSION_PCT</code> with 0, but I get a new column named 'REPLACE('COMMISSION_PCT','-','0')'</p>
<p>With new solution i get this
<a href="https://i.stack.imgur.com/1VKjl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1VKjl.png" alt="enter image description here" /></a></p>
<p>But it doesnt replace empty values with 0</p>
| [
{
"answer_id": 74257264,
"author": "Chris Schaller",
"author_id": 1690217,
"author_profile": "https://Stackoverflow.com/users/1690217",
"pm_score": 1,
"selected": false,
"text": "COMMISSION_PCT"
},
{
"answer_id": 74262444,
"author": "Zakaria Matlaoui",
"author_id": 201677... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18502120/"
] |
74,256,659 | <p>I am having an error while trying to use Jsonb / JsonbBuilder in a JakartaEE maven project.</p>
<p>Error StackTrace</p>
<pre><code>java.lang.RuntimeException: jakarta/json/bind/JsonbBuilder
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerBase.handlePojoMethodException(PojoMessageHandlerBase.java:119)
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:107)
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:415)
at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageText(WsFrameServer.java:129)
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:515)
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:301)
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133)
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:85)
at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:183)
at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:162)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:157)
at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:60)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:59)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:870)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1762)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.NoClassDefFoundError: jakarta/json/bind/JsonbBuilder
at com.example.websockets.WebChat.onMessage(WebChat.java:21)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:105)
... 18 more
Caused by: java.lang.ClassNotFoundException: jakarta.json.bind.JsonbBuilder
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1449)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1257)
... 22 more
</code></pre>
<p>POM</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>websockets</artifactId>
<version>1.0-SNAPSHOT</version>
<name>websockets</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>18</maven.compiler.target>
<maven.compiler.source>18</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>9.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>The method throwing the error and the class imports</p>
<pre><code>@OnMessage
public void onMessage(Session session, String text) {
try(Jsonb jsonb = JsonbBuilder.create()) {
Message message = jsonb.fromJson(text, Message.class);
System.out.println("Message received: " + message);
if(message.getType().equals("join")){
session.getUserProperties().put("name", message.getUserName());
session.getUserProperties().put("active", true);
Message info = new Message(message.getUserName(), "join", message.getUserName() + " has joined the chat");
Message updateUserList = new Message(message.getUserName(), "users", getUserNames(session));
sendAll(session , info);
sendAll(session , updateUserList);
} else if(message.getType().equals("chat")){
sendAll(session, message);
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
</code></pre>
<p>It looks like your post is mostly code; please add some more details.</p>
<pre><code>
import jakarta.json.Json;
import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import java.util.stream.Collectors;
</code></pre>
<p>The error is shown when I try to use JsonbBuilder
And I do have jakarta/json/bind/JsonbBuilder in maven dependencies.</p>
| [
{
"answer_id": 74257264,
"author": "Chris Schaller",
"author_id": 1690217,
"author_profile": "https://Stackoverflow.com/users/1690217",
"pm_score": 1,
"selected": false,
"text": "COMMISSION_PCT"
},
{
"answer_id": 74262444,
"author": "Zakaria Matlaoui",
"author_id": 201677... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20073058/"
] |
74,256,670 | <p>I'm trying to code a quiz game, which every time you get a correct answer adds 1 point; at the end of the game the program prints out the number of points. The thing is, I'm trying to code it by using a function.</p>
<pre><code>def qea(x, y, z):
if x == y:
print("Correct!")
z += 1
else:
print('Wrong!')
points = 0
question1 = input("Who is the president of USA?: ").upper()
answer1 = "JOE BIDEN"
qea(question1, answer1, points)
question1 = input("Alexander...: ").upper()
answer1 = "THE GREAT"
qea(question1, answer1, points)
print(points)
</code></pre>
<p>Why is the program output always 0?</p>
| [
{
"answer_id": 74256697,
"author": "codingtuba",
"author_id": 17199922,
"author_profile": "https://Stackoverflow.com/users/17199922",
"pm_score": 0,
"selected": false,
"text": "z"
},
{
"answer_id": 74256734,
"author": "quamrana",
"author_id": 4834,
"author_profile": "... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374362/"
] |
74,256,683 | <p>I am fairly new to Powershell and have run into a bit of a pickle.</p>
<p>I'm trying to find string "o_dwh" in scripts, but if there is exec before this statement like this - "exec o_dwh" - I don't want to select that. How do I do that?</p>
<p>So far I have this:</p>
<pre><code>Get-ChildItem -Path "$packagepath\Scripts\" -Include *.txt -Recurse | Select-String -Pattern "o_dwh"
</code></pre>
<p>I tried this, but I know it's wrong:</p>
<pre><code>Get-ChildItem -Path "$packagepath\Scripts\" -Include *.txt -Recurse | Select-String -Pattern "o_dwh" and "exec o_dwh" -notmatch
</code></pre>
| [
{
"answer_id": 74256697,
"author": "codingtuba",
"author_id": 17199922,
"author_profile": "https://Stackoverflow.com/users/17199922",
"pm_score": 0,
"selected": false,
"text": "z"
},
{
"answer_id": 74256734,
"author": "quamrana",
"author_id": 4834,
"author_profile": "... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9549176/"
] |
74,256,684 | <pre><code>SELECT
job_id, emp_name, salary, AVG(SALARY) AS AVERAGE_SALARY
FROM
employees
GROUP BY
emp_name, department_id;
</code></pre>
<p>I've tried this but this doesn't seem to work.</p>
<p>table: <a href="https://i.stack.imgur.com/3jB6x.png" rel="nofollow noreferrer">https://i.stack.imgur.com/3jB6x.png</a></p>
<p>output
: <a href="https://i.stack.imgur.com/q7R5T.png" rel="nofollow noreferrer">https://i.stack.imgur.com/q7R5T.png</a>
my output: <a href="https://i.stack.imgur.com/EfxcZ.png" rel="nofollow noreferrer">https://i.stack.imgur.com/EfxcZ.png</a></p>
| [
{
"answer_id": 74256791,
"author": "royce3",
"author_id": 881603,
"author_profile": "https://Stackoverflow.com/users/881603",
"pm_score": 1,
"selected": true,
"text": "select\n job_id, emp_name, salary, (\n select avg(salary) from employees b where b.department_id = a.department_i... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14948137/"
] |
74,256,723 | <p><a href="https://regex101.com/r/2L613R/1" rel="nofollow noreferrer">You can check the regex101 page from here.</a></p>
<p>I have a list of adresses in different formats and non-english. Assume my list is like below.</p>
<pre><code>KENNEDY CAD. SİRKECİ ARABALI VAPUR İSKELESİ FATİH/ İSTANBUL
YAVUZTÜRK MAH. KARADENİZ CAD. NO:2 ÜSKÜDAR/ İSTANBUL
HAMİDİYE MAH. ALPEREN SOK. NO:15/2 ÇEKMEKÖY/ İSTANBUL
UĞUR MUMCU MAH. YUNUS EMRE CAD. NO:25 KARTAL/ İSTANBUL
</code></pre>
<p>The regex I've written is as following:</p>
<p><code>(?:(?:\p{L}* M[Aa]?[Hh][. ])? *|(?:\p{L}* C[Aa]?[Dd][. ])? *)</code></p>
<p>My regex return each character as match, but i need to get 4 matches which are:</p>
<pre><code>KENNEDY CAD.
YAVUZTÜRK MAH. KARADENİZ CAD.
HAMİDİYE MAH.
UĞUR MUMCU MAH. YUNUS EMRE CAD.
</code></pre>
<p>How can I solve that problem?</p>
| [
{
"answer_id": 74256791,
"author": "royce3",
"author_id": 881603,
"author_profile": "https://Stackoverflow.com/users/881603",
"pm_score": 1,
"selected": true,
"text": "select\n job_id, emp_name, salary, (\n select avg(salary) from employees b where b.department_id = a.department_i... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18795946/"
] |
74,256,728 | <p>This is the graph</p>
<p><a href="https://i.stack.imgur.com/UAdXa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UAdXa.png" alt="enter image description here" /></a></p>
<p>So, I try DFS code like this</p>
<pre><code># Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['G', 'H'],
'D' : [],
'E' : ['F'],
'G' : [],
'H' : ['I'],
'F' : [],
'I' : ['J'],
'J' : []
}
visited = [] # Set to keep track of visited nodes of graph.
visited_new = []
def dfs(visited, graph, node, goal): #function for dfs
if node not in visited:
# print (visited)
visited.append(node)
for neighbour in graph[node]:
# print(visited)
if neighbour not in visited:
dfs(visited, graph, neighbour, goal)
if neighbour == goal:
idx_goal = visited.index(goal)
return visited[:idx_goal+1]
# Driver Code
print("Following is the Depth-First Search")
print(dfs(visited, graph, 'A', 'C'))
</code></pre>
<p>The output like this :</p>
<pre><code>Following is the Depth-First Search
['A', 'B', 'D', 'E', 'F', 'C']
</code></pre>
<p>But when I change parameter 'A' to 'F' like this <code>dfs(visited, graph, 'A', 'C')</code> and the output is :</p>
<pre><code>Following is the Depth-First Search
None
</code></pre>
<p>I expect ['A', 'B', 'D', 'E', 'F']</p>
<p>Not only 'A' to 'F', the output code is working only 'A' to 'B' and 'A' to 'C'</p>
<p>How I can solve this problem?</p>
| [
{
"answer_id": 74256761,
"author": "Diram_T",
"author_id": 17754986,
"author_profile": "https://Stackoverflow.com/users/17754986",
"pm_score": 0,
"selected": false,
"text": " if neighbour not in visited:\n dfs(visited, graph, neighbour, goal)\n"
},
{
"an... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19585121/"
] |
74,256,747 | <p>I converted my .py file which contains the alive progress bar package <a href="https://pypi.org/project/alive-progress/" rel="nofollow noreferrer">https://pypi.org/project/alive-progress/</a> into a .exe for windows using the pyinstaller command <code>pyinstaller --console </code>. I however receive an error when I run the program. It runs fine until the alive bar is called and then it prints out the error below.</p>
<pre><code>Traceback (most recent call last):
File "network_nodes_ping.py", line 38, in <module>
File "alive_progress\core\progress.py", line 106, in alive_bar
File "alive_progress\core\configuration.py", line 149, in create_context
File "alive_progress\core\configuration.py", line 183, in lazy_init
File "alive_progress\core\configuration.py", line 14, in _spinner_input_factory
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "alive_progress\styles\__init__.py", line 1, in <module>
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "alive_progress\styles\exhibit.py", line 9, in <module>
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "alive_progress\styles\internal.py", line 126, in <module>
File "alive_progress\styles\internal.py", line 12, in create_spinners
File "alive_progress\animations\spinners.py", line 43, in frame_spinner_factory
File "alive_progress\animations\spinners.py", line 43, in <genexpr>
File "alive_progress\animations\spinners.py", line 43, in <genexpr>
File "alive_progress\utils\cells.py", line 145, in to_cells
File "alive_progress\utils\cells.py", line 149, in split_graphemes
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "grapheme\__init.py", line 9, in <module>
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "grapheme\api.py", line 2, in <module>
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "grapheme\finder.py", line 3, in <module>
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "grapheme\grapheme_property_group.py", line 97, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\BRYANV~1\\AppData\\Local\\Temp\\_MEI85082\\grapheme\\data/grapheme_break_property.json'
[13328] Failed to execute script 'network_nodes_ping' due to unhandled exception!
</code></pre>
| [
{
"answer_id": 74328211,
"author": "Pluckerpluck",
"author_id": 1189471,
"author_profile": "https://Stackoverflow.com/users/1189471",
"pm_score": 0,
"selected": false,
"text": "alive-progress"
},
{
"answer_id": 74377648,
"author": "Maxim Pekurin",
"author_id": 17096801,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10647846/"
] |
74,256,795 | <p>I am learning Kotlin for backend.<br />
I am using Ktor, and following tutorials on <a href="https://ktor.io" rel="nofollow noreferrer">ktor.io</a> website.</p>
<p>I am using IntelliJ IDEA CE (Community Edition), so I do not have access to Ktor configuration page nor plugins page (available on IntelliJ IDEA Ultimate, a premium edition).</p>
<p>I have to use the <a href="https://start.ktor.io/" rel="nofollow noreferrer">web based project generator</a>, which asks me all the plugins I will need.</p>
<p>However, I might not know which plugins I will need : my project can grow, and I might need more plugins later.</p>
<p>Is there an efficient way to add plugins to an already existing project ?</p>
| [
{
"answer_id": 74265478,
"author": "nicowi",
"author_id": 5397752,
"author_profile": "https://Stackoverflow.com/users/5397752",
"pm_score": 0,
"selected": false,
"text": "plugins {\napplication\nkotlin(\"jvm\") version \"1.7.20\"\nid(\"io.ktor.plugin\") version \"2.1.2\"\nkotlin(\"plugin... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8286029/"
] |
74,256,807 | <p>I am attempting to fit nls() for 520 users to achieve the coefficients of the exponential fitting. The following is a small representation of my data.</p>
<pre><code>dput(head(Mfrq.df.2))
structure(list(User.ID = c("37593", "38643", "49433", "60403",
"70923", "85363"), V1 = c(9L, 3L, 4L, 80L, 19L, 0L), V2 = c(10L,
0L, 29L, 113L, 21L, 1L), V3 = c(5L, 2L, 17L, 77L, 7L, 2L), V4 = c(2L,
2L, 16L, 47L, 4L, 3L), V5 = c(2L, 10L, 16L, 40L, 1L, 8L), V6 = c(4L,
0L, 9L, 22L, 1L, 7L), V7 = c(6L, 8L, 9L, 8L, 0L, 6L), V8 = c(2L,
17L, 16L, 24L, 2L, 1L), V9 = c(3L, 20L, 7L, 30L, 0L, 4L), V10 = c(2L,
11L, 5L, 11L, 2L, 3L)), row.names = c(NA, 6L), class = "data.frame")
</code></pre>
<p>Finally, I found two ways of doing this. However for both, I get an error stating singular gradient.</p>
<pre><code>#Way I
x=1:10
Mfrq.df.2_long <- pivot_longer(Mfrq.df.2, matches("V\\d{1,2}"), names_to = NULL, values_to = "Value")
Mfrq.df.2_long %>%
group_by(User.ID) %>%
mutate(fit = nls(Value ~ A * exp(-k * x), start = c(A =2, k = 0.01)) %>% list())
</code></pre>
<pre><code>#Way2
L1 = c()
for (i in unique(Mfrq.df.2$User.ID)) {L1[[as.character(i)]]=seq(1,10)}
length(L1) #520 users
dput(head(L1))
list(`37593` = 1:10, `38643` = 1:10, `49433` = 1:10, `60403` = 1:10,
`70923` = 1:10, `85363` = 1:10)
</code></pre>
<pre><code>#Way 2 Continue
L2=list.ids.RecSOC.2
length(L2) #520 users
dput(head(L2))
list(`37593` = c(9L, 10L, 5L, 2L, 2L, 4L, 6L, 2L, 3L, 2L), `38643` = c(3L,
0L, 2L, 2L, 10L, 0L, 8L, 17L, 20L, 11L), `49433` = c(4L, 29L,
17L, 16L, 16L, 9L, 9L, 16L, 7L, 5L), `60403` = c(80L, 113L, 77L,
47L, 40L, 22L, 8L, 24L, 30L, 11L), `70923` = c(19L, 21L, 7L,
4L, 1L, 1L, 0L, 2L, 0L, 2L), `85363` = c(0L, 1L, 2L, 3L, 8L,
7L, 6L, 1L, 4L, 3L))
</code></pre>
<pre><code>#Way 2 Continue
control=nls.control(maxiter=1000)
res <- mapply(function(x,y){
nls(y~A*(exp(-k*x)),
start=list(A=100, k=0.01), control=control,
trace= TRUE, data=data.frame(x, y))},L1,L2, SIMPLIFY=FALSE)
</code></pre>
<p>To the best of my understanding, it has something to do with the starting values. I find it hard to find starting values that would work for all 520. Especially knowing not all of them are following the defined curve. I still need all 520 coefficients (A&k) to do my further analyses.</p>
<p>Any recommendations? Thanks</p>
| [
{
"answer_id": 74265478,
"author": "nicowi",
"author_id": 5397752,
"author_profile": "https://Stackoverflow.com/users/5397752",
"pm_score": 0,
"selected": false,
"text": "plugins {\napplication\nkotlin(\"jvm\") version \"1.7.20\"\nid(\"io.ktor.plugin\") version \"2.1.2\"\nkotlin(\"plugin... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15507628/"
] |
74,256,824 | <pre><code>def createfile(name, location, extension):
print(name, extension, location)
</code></pre>
<p>I have this code and I need to make a file with these variables</p>
<p>I have tried a couple of things but they never seemed to work.</p>
| [
{
"answer_id": 74265478,
"author": "nicowi",
"author_id": 5397752,
"author_profile": "https://Stackoverflow.com/users/5397752",
"pm_score": 0,
"selected": false,
"text": "plugins {\napplication\nkotlin(\"jvm\") version \"1.7.20\"\nid(\"io.ktor.plugin\") version \"2.1.2\"\nkotlin(\"plugin... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19804326/"
] |
74,256,848 | <p>In the <code>DataFrame</code> below</p>
<pre><code>df = pd.DataFrame([('Ve_Paper', 'Buy', '-','Canada',np.NaN),
('Ve_Gasoline', 'Sell', 'Done','Britain',np.NaN),
('Ve_Water', 'Sell','-','Canada,np.NaN),
('Ve_Plant', 'Buy', 'Good','China',np.NaN),
('Ve_Soda', 'Sell', 'Process','Germany',np.NaN)], columns=['Name', 'Action','Status','Country','Value'])
</code></pre>
<p>I am trying to update the <code>Value</code> column based on the condition if <code>Action</code> is <code>Sell</code> check if the <code>Status</code> is not <code>-</code> if that is true then the first two characters of the <code>Country</code> needs to be updated as the <code>Value</code> column else if <code>Status</code> column is <code>-</code> the <code>Value</code> column needs to be updated with the <code>Name</code> column without the characters <code>Ve_</code>, if <code>Action</code> is not <code>Sell</code> leave the <code>Value</code> column as <code>np.NaN</code></p>
<p>What I have tried so far is</p>
<pre><code>import numpy as np
df['Value'] = np.where(df['Action']== 'Sell',df['Country'].str[:2] if df['Status'].str != '-' else df['Name'].str[3:],df['Value'])
</code></pre>
<p>but I am getting the output as <code><pandas.core.strings.StringMethods object at 0x000001EDB8F662B0></code> wherever Iam trying to extract substrings
so the output looks like this</p>
<pre><code> Name Action Status Country Value
Ve_Paper Buy - Canada np.NaN
Ve_Gasoline Sell Done Britain <pandas.core.strings.StringMethods object at 662B0>
Ve_Water Sell - Canada <pandas.core.strings.StringMethods object at 0x000001EDB8F662B0>
Ve_Plant Buy Good China np.NaN
Ve_Soda Sell Process Germany <pandas.core.strings.StringMethods object at 0x000001EDB8F662B0>
</code></pre>
<p>But the <code>output</code> I am expecting is</p>
<pre><code> Name Action Status Country Value
Ve_Paper Buy - Canada np.NaN # Because Action is not Sell
Ve_Gasoline Sell Done Britain Br # The first two characters of Country Since Action is sell and Status is not "-"
Ve_Water Sell - Canada Water # The Name value without 'Ve_' since Action is Sell and the Status is '-'
Ve_Plant Buy Good China np.NaN
Ve_Soda Sell Process Germany Ge
</code></pre>
<p>As mentioned in the answer below the method I tried works for someone but doesn't work for me. Is there any alternative approaches or better approaches than what I have tried, since that is not working for me</p>
| [
{
"answer_id": 74265478,
"author": "nicowi",
"author_id": 5397752,
"author_profile": "https://Stackoverflow.com/users/5397752",
"pm_score": 0,
"selected": false,
"text": "plugins {\napplication\nkotlin(\"jvm\") version \"1.7.20\"\nid(\"io.ktor.plugin\") version \"2.1.2\"\nkotlin(\"plugin... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,256,865 | <p>I want a middleware on my website for: People can edit their own posts but others posts. I tried this:</p>
<p>I get all posts that have the same post->user_id and user_id</p>
<pre><code>$matches = Post::where('user_id', auth()->user()->id)->get();
</code></pre>
<p>This gives back an array of posts that match the condition</p>
<p>Now what I want is to check if you are on a post that matches this condition, if the post->user_id and user_id do not match abort.</p>
<p>This is what I have, but you still can get on posts where the condition is <strong>NOT</strong> met.</p>
<pre><code>if (!$matches){
abort(403);
}
return $next($request);
</code></pre>
<p>Abort when the criteria is not met and return the request when it is met</p>
| [
{
"answer_id": 74258127,
"author": "Harshana",
"author_id": 6952359,
"author_profile": "https://Stackoverflow.com/users/6952359",
"pm_score": 0,
"selected": false,
"text": "http://127.0.0.1:5500/posts/1"
},
{
"answer_id": 74259081,
"author": "xenooooo",
"author_id": 20283... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20332808/"
] |
74,256,876 | <p>I want to run the following at 22:00 PM everyday using import datetime.
I'm trying to use a codeRan boolean to trigger it, but I can't get it to work. It's always False:</p>
<pre><code>import datetime
timeNow = datetime.datetime.now() # 2022-10-31 10:23:10.461374
timeHour = timeNow.strftime("%H") # 22
timeFull = timeNow.strftime("%X") # 10:21:59
timeAMPM = timeNow.strftime("%p") # AM or PM
codeRan = False
if timeHour == "22" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)
</code></pre>
| [
{
"answer_id": 74256952,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "while not codeRan:\n if timeHour == \"22\" and codeRan == False:\n print(timeHour + \" That ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7770930/"
] |
74,256,904 | <p>I'm trying to convert an array of arrays into an array of nested objects in JavaScript. Let's assume each subarray in the array represents a file path. I want to create an array of objects where each object has 2 properties, the name of the current file and any files/children that come after the current file/parent.</p>
<p>So for example, if I have this array of arrays where each subarray represents a file path:</p>
<pre><code>[['A', 'B', 'C'], ['A', 'B', 'D'], ['L', 'M', 'N']]
</code></pre>
<p>I want to get this as the result:</p>
<pre><code>[
{
name :'A',
children: [
{
name: 'B',
children: [
{
name: 'C',
children: []
},
{
name: 'D',
children: []
}
]
}
]
},
{
name: 'L',
children: [
{
name: 'M',
children: [
{
name: 'N',
children: []
}
]
}
]
}
]
</code></pre>
<p>I tried mapping through the array of arrays and creating an object for the current file/parent if it hasn't been created yet. I think I may be on the right track but I can't seem to think of the best way to do so.</p>
| [
{
"answer_id": 74256952,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "while not codeRan:\n if timeHour == \"22\" and codeRan == False:\n print(timeHour + \" That ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374510/"
] |
74,256,932 | <p>Was trying to make a ToDo list and everything was going well until every time I tried to fill out a form and it started giving me that syntax error that is mentioned in the title.</p>
<p>Here's my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//Random Alert
alert('Better get to it or moms going to be angry')
//Real work below
the window.addEventListener('load', () => {
const form = document.querySelector("#new-task-form");
const input = document.querySelector("#new-task-input");
const list_el = document.querySelector("#task-list");
form.addEventListener('submit', (e) => {
e.preventDefault();
const task = input.value;
if (!task) {
alert("Please add/fill out the task");
return;
}
const task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
task_content_el.innerText = task;
task_el.appendChild(task_content_el);
list_el.appendChild(task_el);
})
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<header>
<h1>ToDo list 2022(version 1)</h1>
<form id="new-task-form">
<input type="text" id="new-task-input" placeholder="what's on your mind today?">
<input type="submit" id="new-task-submit" value="Add task">
</form>
</header>
<main>
<section class="task-list">
<h2>Tasks</h2>
</section>
</main>
</body></code></pre>
</div>
</div>
</p>
<p>Google keeps telling me to add a script src after every HTML element has been placed(I placed it above <code></body></code>) but it doesn't change anything. The output is meant to list out the input infinite times and when I do it nothing comes up but a console error.</p>
| [
{
"answer_id": 74256952,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "while not codeRan:\n if timeHour == \"22\" and codeRan == False:\n print(timeHour + \" That ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374543/"
] |
74,256,933 | <p>I am working something that utilizes the azure services & azure functions(with sb trigger), and trying to figure out if it matters to distribute the messages by creating multiple subscriptions VS Just one?</p>
<p>Please see the Before VS After in below chart:
<a href="https://i.stack.imgur.com/jvDDe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jvDDe.png" alt="enter image description here" /></a></p>
<p>I am trying to improve the performance of entire process as there are too many messages sitting in there.
There's no difference between the 3 functions in the After chart, all they do is upserting DB records. Does it even matter if I have 1 sub vs 3 sub in this flow ?</p>
| [
{
"answer_id": 74256952,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "while not codeRan:\n if timeHour == \"22\" and codeRan == False:\n print(timeHour + \" That ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374491/"
] |
74,256,977 | <p>Consider this encryption function:</p>
<pre class="lang-js prettyprint-override"><code>async function encrypt(message: string) {
const salt = randomBytes(16);
const iv = randomBytes(16);
const password = 'Password used to generate key';
const key = (await promisify(scrypt)(password, salt, 32)) as Buffer;
const cipher = createCipheriv('aes-256-ctr', key, iv);
const encryptedMessage = Buffer.concat([
cipher.update(message),
cipher.final(),
]);
return { encryptedMessage, iv, salt };
}
</code></pre>
<p>and this <a href="https://nodejs.org/api/crypto.html#using-strings-as-inputs-to-cryptographic-apis" rel="nofollow noreferrer">section</a> from <code>crypto</code> docs where it is said that the password, IV, and salt should not be stored as strings, rather byte sequences.</p>
<p>From what I've learned and know about symmetric encryption, I have to store salt and initialization vector with the encrypted message.</p>
<p>The questions I want to ask are:</p>
<ul>
<li>Should I store the password as a byte sequence? If yes, can I store it in a <code>.env</code> file? And, if yes, how would that look like?</li>
<li>How do I store salt, IV, and encrypted message as bytes in a database? Is it possible to be stored in one field, separated by some special character?</li>
</ul>
| [
{
"answer_id": 74256952,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "while not codeRan:\n if timeHour == \"22\" and codeRan == False:\n print(timeHour + \" That ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13855835/"
] |
74,256,980 | <pre><code>var generated_pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEY17rXBY86d3b e2e70cf35bc6b9490 0a0e76a27a9fc15e769 d674e3a9ce7d6bad5== =G4p6 -----END PGP PUBLIC KEY BLOCK----- "
</code></pre>
<p>I want to replace the space that comes after "-----BEGIN PGP PUBLIC KEY BLOCK-----" with \n\n and replace all other spaces with 1 \n while keeping the spaces between the wording “ -----BEGIN PGP PUBLIC KEY BLOCK-----” without any replacement also keeping “END PGP PUBLIC KEY BLOCK”</p>
<p>So the result becomes:</p>
<pre><code>"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nxjMEY17rXBY86d3b\ne2e70cf35bc6b9490\n0a0e76a27a9fc15e769\nd674e3a9ce7d6bad5==\n=G4p6\n-----END PGP PUBLIC KEY BLOCK-----\n"
</code></pre>
<p>Note: The public key generated will be random.The double \n\n will always be installed after the first “BLOCK-----“ as shown above, the public key string will always end with a space that should be replaced with a single \n while other spaces will be replaced with single \n.</p>
<p>I have already tried:</p>
<pre><code>generated_pubkey.replaceAll(" ", "\n")
</code></pre>
<p>But that replaced even the spacing between the wording of BEGIN PGP etc and END PGP etc</p>
| [
{
"answer_id": 74257030,
"author": "Pearli",
"author_id": 7935435,
"author_profile": "https://Stackoverflow.com/users/7935435",
"pm_score": 0,
"selected": false,
"text": "let generated_pubkey = \"-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEY17rXBY86d3b e2e70cf35bc6b9490 0a0e76a27a9fc15e769 ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19222846/"
] |
74,256,987 | <pre><code>import React, { useEffect, useState } from 'react';
import { EmployeeList } from '../EmployeeList/EmployeeList';
export default function EmployeeMenu(props) {
const [employeeList, setEmployeeList] = useState(() => new EmployeeList());
useEffect(() => employeeList.getEmployees(), [employeeList]);
const handleEmployeeChange = (event, data) => {
props.setEmployee(event.target.value);
console.log(event.target.value);
}
function EmployeeMenu() {
let temp = employeeList.employees.map((employee) => (
<div>
<input type="radio" id={employee.phone_number} name="employee_name" value={employee.first_name} />
<label htmlFor={employee.phone_number}>{employee.first_name} {employee.last_name}</label>
</div>
));
return temp;
}
return(
<form onChange={handleEmployeeChange}>
<EmployeeMenu />
</form>
);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/RQO3p.png" rel="nofollow noreferrer">code produces</a></p>
<p>This is what the code produces. It's close to what I wanted to accomplish, but my radio buttons do not check/uncheck when I select different employees.</p>
<p>That's because I have each input and label inside a separate div when I map the information from the employeeList array. But if I don't wrap them, I get "JSX expressions must have one parent element". Does anyone have any advice on how I could better map radio buttons from an array so that they remain inside the same form group?</p>
| [
{
"answer_id": 74257030,
"author": "Pearli",
"author_id": 7935435,
"author_profile": "https://Stackoverflow.com/users/7935435",
"pm_score": 0,
"selected": false,
"text": "let generated_pubkey = \"-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEY17rXBY86d3b e2e70cf35bc6b9490 0a0e76a27a9fc15e769 ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74256987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12985749/"
] |
74,257,001 | <p>Is it possible to add type in laravel/OctoberCMS?</p>
<pre><code>columns:
field:
value: field
type: specialdate
</code></pre>
<p>I'd like to have specialtype in backend (colors depends on value or some text instead of exact value (e.g. ZERO instead of 0 ;D</p>
| [
{
"answer_id": 74276377,
"author": "Hardik Satasiya",
"author_id": 3076866,
"author_profile": "https://Stackoverflow.com/users/3076866",
"pm_score": 0,
"selected": false,
"text": "partial"
}
] | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/354420/"
] |
74,257,009 | <p>I have two divs that should take whole page while each one is 50% of the page (50vh) but once I apply that the resizing goes crazy and elements overlap when the size becomes smaller and smaller, any workaround? I would like to achieve the typical disappearing of whole page that it gets removed from viewport, not overlapping.</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>#top {
background-color: red;
}
#bottom {
background-color: blue;
}
div {
height: 50vh;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='top'>
<h1>Test</h1>
<input id='testInputOne' type='text'>
</div>
<button id='testButton' type='button'>Test</button>
<div id='bottom'>
<input id='testInputTwo' type='text'>
<h1>Test</h1>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/tr40z716/" rel="nofollow noreferrer">https://jsfiddle.net/tr40z716/</a></p>
<p>I tried to add one more div that would hold the two divs but no help.</p>
| [
{
"answer_id": 74260097,
"author": "HackerFrosch",
"author_id": 20357737,
"author_profile": "https://Stackoverflow.com/users/20357737",
"pm_score": 0,
"selected": false,
"text": "divs"
},
{
"answer_id": 74260944,
"author": "tatactic",
"author_id": 1247977,
"author_pro... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374616/"
] |
74,257,084 | <p>A pattern I've often seen in Helm charts (<a href="https://github.com/k8s-at-home/charts/blob/77d4398e0a1c7393d180d1c987bf718245ff91e2/charts/incubator/dendrite/templates/dendrite-config.yaml#L87" rel="nofollow noreferrer">e.g.</a>) is to set a boolean value to <a href="https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-default-function" rel="nofollow noreferrer">default</a> to <code>true</code> unless some overriding value is provided:</p>
<pre><code>feature_enabled_in_k8s_resource: {{ default true .Values.foo_feature_enabled }}
</code></pre>
<p>That is - "<em>if <code>foo_feature_enabled</code> is set to any value in the inputs to Helm (via <code>--set</code>, <code>values.yaml</code>, etc.), set <code>feature_enabled_in_k8s_resource</code> to that value - else (if it is unset), set <code>feature_enabled_in_k8s_resource</code> to <code>true</code></em>"</p>
<p>However, I'm not able to override that value as I would expect - both setting a <code>false</code> value in <code>values.yaml</code>, and/or passing <code>--set foo_feature_enabled=false</code> as an argument, still result in the template holding a value of <code>true</code>.</p>
<p>I suspect that this is because <code>false</code> is a "<a href="https://gist.github.com/jfarmer/2647362" rel="nofollow noreferrer"><em>falsy</em></a>" value, and so <code>default</code> parses it as "needing replacement".</p>
<p>Passing a string value (<code>"false"</code> in <code>values.yaml</code>, or <code>--set-string foo_feature_enabled=false</code>) does appear (from <code>helm template [...]</code> output) to set <code>feature_enabled_in_k8s_resource</code> to <code>"false"</code> - but it's not clear whether that will be correctly interpreted by the actual application which results from the Kubernetes (that is - it might interpret a non-empty string as "truthy", setting us right back to the original default behaviour). Even if this <em>works</em>, it feels hacky in a way that suggests that I'm missing the "proper" solution.</p>
<p>(Presumably, the <em>actual</em> fix would be Helm charts to never <code>default</code> to <code>true</code> - but that doesn't help me when working with charts that I don't control!)</p>
| [
{
"answer_id": 74257234,
"author": "SBI",
"author_id": 4630229,
"author_profile": "https://Stackoverflow.com/users/4630229",
"pm_score": 0,
"selected": false,
"text": "feature_enabled_in_k8s_resource: {{ .Values.foo_feature_enabled | default true }}\n"
},
{
"answer_id": 74262000,... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040915/"
] |
74,257,100 | <p>I've been reading through the documentation at Laravel's website but struggling to piece this all together.</p>
<p>We have users who can be assigned to specific roles and/or teams at different times. For example, User A could be assigned to Team 1 as Leader between two dates, then following that could be assigned to Team 1 as Operator. My thought was to use a hasManyThrough relationship to control this. Model example layout below.</p>
<hr />
<p>-- user model</p>
<p>id</p>
<p>user_name</p>
<p>-- placements model (the <em>through</em>)</p>
<p>id</p>
<p>user_id</p>
<p>position_id</p>
<p>team_id</p>
<p>start (date)</p>
<p>end (date)</p>
<p>--positions</p>
<p>id</p>
<p>name</p>
<hr />
<p>So the user and positions model will only have one row per record but placements model could have several rows per user but will never cross dates (can only be assigned to one placement at a time).</p>
<p>My goal is to be able to do things like, $users->position($date) or $users->currentPosition, as well as $team->members($date) or $team->currentMembers</p>
<p>I have tried a variety of relationships and hasManyThrough seems to make the most sense but i'm running into errors like this where the SQL makes me think the relationship is defined differently to how I was expecting.</p>
<pre class="lang-php prettyprint-override"><code>class Team extends Model
{
use HasFactory;
public function members()
{
return $this->hasManyThrough(User::class, Placement::class, 'team_id');
}
}
</code></pre>
<p>is equating to this SQL which makes me think i'm doing it wrong</p>
<pre class="lang-sql prettyprint-override"><code>select `users`.*, `placements`.`team_id` as `laravel_through_key` from `users` inner join `placements` on `placements`.`id` = `users`.`placement_id` where `placements`.`team_id` = 1
</code></pre>
<p>Any assistance would be greatly appreciated!</p>
<p>Thanks so much</p>
| [
{
"answer_id": 74257234,
"author": "SBI",
"author_id": 4630229,
"author_profile": "https://Stackoverflow.com/users/4630229",
"pm_score": 0,
"selected": false,
"text": "feature_enabled_in_k8s_resource: {{ .Values.foo_feature_enabled | default true }}\n"
},
{
"answer_id": 74262000,... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2097717/"
] |
74,257,101 | <p><strong>I have two components where one comp provides a search input field where the user will enter data(e.g; city name) and another comp provides the main weather data( based on the user search input from comp 1) like temp, wind, etc.. how should I pass the user input to the API so it will render the data of that city. I have been stuck on this issue for the last 3 days. any solution?</strong></p>
<p><strong>Comp1 (search comp)</strong></p>
<pre><code>import React, { useState } from "react";
import "../Componentstyle/search.css";
export default function Search() {
const [location, setLocation] = useState();
const handlesubmit = (event)=>{
event.preventDefault();
setLocation(event.target.value)
}
return (
<>
<div className="main">
<nav className="istclass">
<form className="form">
<div className="search">
<input
value={location}
placeholder="search city"
className="searchbox"
onChange={(e) => setLocation(e.target.value)}
/>
<button className="nd" type="button" onClick={handlesubmit}>
Submit
</button>
</div>
</form>
</nav>
</div>
</>
);
}
</code></pre>
<p><strong>Comp2 (maindata comp)</strong></p>
<pre><code>import React, { useState, useEffect } from "react";
import "../Componentstyle/Main.css";
export default function Maindata() {
const [data, setData] = useState();
let city = "mansehra";
let weather = async () => {
// if(!city)return;
const key = "XYZ";
await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}&units=metric&formatted=0`
)
.then((response) => response.json())
.then((actualData) => setData(actualData));
};
useEffect(() => {
weather();
}, []);
if (!data) {
return <div>Loading...</div>;
}
const link = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`;
return (
<>
<div className="maindata">
<div className="city">{data.name}</div>
<div className="temp">{data.main.temp} C</div>
<div className="icon">
<img src={link} alt="not found" />{" "}
</div>
<div className="feel">feels Like {data.main.feels_like} C</div>
<div className="wind">Wind {data.wind.speed} Km/hr</div>
<div className="cloudy">{data.weather[0].main}</div>
<div className="humidity">humidity {data.main.humidity}%</div>
<div className="sunrise">
sunrise :- {new Date(data.sys.sunrise * 1000).toUTCString()}{" "}
</div>
<div className="sunset">
sunset :- {new Date(data.sys.sunset * 1000).toUTCString()}
</div>
</div>
</>
);
}
</code></pre>
<p><strong>App.js Comp</strong></p>
<pre><code>import "./App.css";
import Maindata from "./Components/Maindata";
import Search from "./Components/Search";
function App() {
return (
<div className="mainpage">
<div className="searchComp">
<Search />
</div>
<div className="details">
<Maindata />
);
}
export default App;
</code></pre>
| [
{
"answer_id": 74257339,
"author": "Neil Girardi",
"author_id": 1500241,
"author_profile": "https://Stackoverflow.com/users/1500241",
"pm_score": 1,
"selected": false,
"text": "LocationProvider"
},
{
"answer_id": 74259070,
"author": "Drew Reese",
"author_id": 8690857,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16762504/"
] |
74,257,104 | <p>I'm trying to create a minimum reproducible example, while doing so, i came across this error. How can i solve this?</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 22, in <module>
File "<string>", line 10, in verified
TypeError: can only concatenate tuple (not "list") to tuple
</code></pre>
<pre><code>import json
# Python3 program to convert a
# list into a tuple
def convert(list):
return tuple(list)
def verified(k_signer, sha256, d_signer, addr_from, seed, data, signature):
hash = (
k_signer +
tuple(sha256.encode()) +
d_signer +
tuple() +
tuple() +
tuple()
)
return hash
data = {'k_signer': [165, 118, 206, 164, 254, 84, 98, 136, 122, 95, 83, 186, 232, 134, 155, 198, 186, 72, 221, 207, 167, 67, 45, 62, 118, 121, 122, 42, 166, 42, 185, 149, 91, 39, 77, 188, 42, 215, 132, 148, 170, 99, 114, 144, 66, 93, 177, 127, 214, 55, 57, 230, 214, 246, 241, 122, 201, 13, 225, 173, 22, 195, 144, 54, 20, 193, 213, 187, 228, 24, 48, 239, 216, 157, 193, 255, 45, 103, 223, 33, 105, 92, 176, 197, 128, 158, 103, 130, 190, 139, 184, 224, 145, 150, 191, 81, 35, 135, 90, 182, 56, 203, 195, 183, 50, 188, 67, 49, 211, 170, 165, 70, 219, 215, 216, 160, 236, 89, 237, 193, 45, 71, 239, 153, 74, 229, 36, 101, 222, 222, 188, 168, 58, 99, 166, 37, 164, 63, 117, 54, 139, 205, 176, 154, 151, 130, 182, 87, 15, 116, 46, 165, 202, 95, 70, 204, 108, 152, 123, 28, 241, 120, 50, 249, 243, 45, 246, 248, 165, 107, 33, 198, 204, 178, 86, 169, 237, 248, 9, 175, 199, 136, 171, 161, 117, 229, 130, 238, 145, 143, 159, 103, 43, 205, 153, 61, 129, 65, 231, 41, 115, 89, 162, 13, 103, 95, 85, 147, 245, 152, 9, 99, 110, 61, 130, 210, 225, 188, 68, 224, 6, 173, 6, 177, 250, 82, 221, 12, 79, 5, 138, 218, 242, 239, 162, 99, 95, 249, 178, 163, 88, 37, 209, 141, 249, 163, 164, 231, 13, 30, 53, 207, 82, 163, 138, 11, 201, 187, 169, 117, 98, 174, 197, 131, 15, 206, 47, 211, 117, 219, 130, 92, 199, 147, 58, 22, 91, 55, 30, 160, 206, 178, 109, 61, 3, 124, 238, 242, 167, 67, 100, 224, 173, 96, 101, 97, 188, 222, 101, 47, 15, 123, 193, 232, 247, 235, 134, 171, 255, 180, 94, 234, 97, 193, 108, 28, 231, 164, 95, 232, 131, 181, 104, 11, 213, 222, 184, 175, 128, 157, 140, 148, 214, 43, 40, 135, 51, 197, 86, 123, 238, 85, 170, 51, 28, 133, 227, 124, 233, 7, 85, 99, 158, 203, 90, 160, 159, 105, 13, 164, 150, 126, 170, 155, 187, 104, 138, 173, 56, 46, 8, 82, 120, 170, 43, 62, 228, 146, 151, 26, 231, 42, 5, 130, 159, 37, 9, 70, 27, 14, 74, 17, 102, 83, 126, 243, 187, 131, 99, 114, 158, 239, 222, 175, 21, 215, 177, 13, 191, 151, 246, 229, 51, 112, 110, 42, 25, 122, 13, 96, 98, 81, 252, 122, 45, 165, 4, 108, 40, 101, 9, 75, 80, 97, 150, 218, 195, 175, 9, 133, 80, 131, 75, 244, 210, 232, 194, 227, 232, 22, 192, 40, 229, 208, 116, 121, 118, 164, 136, 115, 41, 97, 239, 7, 111, 193, 141, 228, 114, 22, 126, 192, 120, 130, 26, 110, 120, 183, 159, 149, 50, 3, 42, 15, 214, 160, 144, 193, 225, 243, 34, 35, 247, 249, 143, 24, 200, 240, 157, 7, 195, 35, 61, 233, 190, 163, 64, 188, 138, 89, 15, 102, 20, 11, 221, 158, 63, 61, 59, 153, 226, 58, 26, 131, 254, 138, 255, 84, 72, 32, 121, 123, 115, 69, 109, 96, 182, 171, 190, 154, 181, 131, 42, 177, 175, 26, 249, 112, 247, 126, 45, 231, 22, 241, 160, 12, 244, 104, 119, 149, 89, 156, 217, 65, 218, 95, 38, 190, 98, 95, 204, 149, 200, 121, 229, 195, 16, 213, 204, 4, 222, 187, 143, 171, 26, 56, 160, 16, 106, 166, 216, 91, 35, 178, 77, 115, 44, 143, 147, 130, 69, 209, 80, 133, 243, 23, 190, 100, 169, 245, 58, 58, 137, 187, 203, 74, 148, 112, 146, 82, 177, 210, 230, 253, 236, 144, 130, 15, 57, 45, 74, 110, 3, 167, 39, 227, 53, 91, 69, 252, 87, 195, 237, 239, 218, 45, 148, 237, 235, 150, 82, 99, 87, 11, 175, 136, 110, 220, 228, 15, 109, 76, 140, 59, 172, 122, 159, 78, 69, 38, 156, 239, 241, 130, 77, 115, 253, 203, 170, 103, 174, 163, 73, 121, 214, 115, 17, 119, 233, 244, 133, 38, 133, 106, 87, 144, 164, 64, 181, 74, 141, 82, 55, 78, 80, 132, 180, 225, 63, 213, 133, 219, 253, 142, 19, 210, 25, 232, 252, 36, 42, 176, 105, 27, 231, 72, 85, 80, 173, 229, 85, 90, 96, 102, 143, 152, 165, 13, 40, 0, 88, 100, 190, 180, 71, 184, 54, 60, 4, 253, 6, 97, 147, 196, 174, 239, 255, 19, 140, 234, 180, 7, 243, 80, 251, 57, 115, 103, 128, 231, 131, 196, 174, 116, 166, 105, 56, 148, 52, 29, 98, 116, 203, 23, 65, 66, 203, 71, 96, 233, 209, 170, 181, 36, 17, 86, 198, 174, 178, 176, 19, 47, 158, 5, 38, 249, 233, 63, 126, 67, 205, 131, 15, 189, 103, 153, 161, 153, 47, 19, 126, 197, 177, 129, 190, 105, 18, 22, 188, 194, 236, 170, 80, 28, 178, 24, 184, 54, 182, 202, 210, 239, 37, 41, 11, 204, 226, 214, 18, 140, 184, 230, 184, 42, 62, 99, 248, 126, 8, 237, 150, 79, 39, 69, 96, 87, 154, 3, 175, 193, 222, 212, 122, 173, 74, 88, 49, 92, 236, 186, 22, 114, 64, 41, 225, 20, 98, 34, 223, 29, 244, 71, 59, 23, 102, 46, 137, 14, 32, 54, 63, 190, 215, 16, 181, 112, 131, 146, 87, 142, 80, 234, 152, 36, 41, 175, 213, 244, 120, 186, 8, 159, 121, 93, 58, 82, 11, 112, 180, 44, 27, 158, 138, 231, 87, 190, 81, 174, 149, 171, 127, 119, 30, 244, 248, 155, 88, 117, 114, 26, 182, 103, 182, 142, 169, 30, 51, 70, 214, 63, 60, 152, 110, 14, 110, 148, 195, 107, 93, 12, 135, 35, 222, 187, 60, 117, 90, 51, 227, 127, 109, 24, 23, 223, 135, 98, 3, 119, 138, 16, 215, 134, 89, 243, 126, 218, 144, 52, 36, 59, 251, 243, 77, 118, 231, 147, 200, 212, 163, 242, 134, 78, 127, 252, 173, 98, 78, 151, 21, 106, 185, 139, 182, 228, 210, 79, 62, 63, 120, 15, 34, 189, 190, 164, 106, 133, 84, 156, 246, 128, 13, 94, 119, 182, 48, 251, 1, 170, 204, 193, 250, 114, 196, 50, 25, 5, 170, 167, 70, 128, 37, 168, 128, 200, 112, 104, 134, 182, 126, 202, 214, 170, 131, 198, 95, 237, 138, 205, 108, 135, 206, 102, 128, 94, 75, 209, 130, 175], 'd_pk': '81c0a09692ad852649aeca550e0c8a280814b1f2ee5b9cdba7fad5399e050c94', 'd_signer': [92, 179, 203, 137, 168, 215, 194, 231, 231, 220, 175, 55, 104, 195, 181, 202, 168, 124, 36, 109, 96, 52, 119, 111, 123, 228, 68, 52, 181, 176, 146, 52, 110, 192, 12, 72, 140, 192, 53, 100, 9, 182, 78, 181, 147, 164, 213, 10, 151, 175, 65, 17, 110, 223, 245, 47, 20, 208, 48, 41, 30, 236, 111, 168, 188, 193, 28, 201, 123, 106, 228, 90, 176, 80, 228, 237, 209, 104, 204, 165, 146, 66, 84, 137, 250, 123, 1, 169, 48, 28, 33, 131, 220, 15, 248, 189, 248, 196, 210, 54, 70, 84, 201, 197, 4, 169, 187, 74, 122, 147, 205, 245, 111, 164, 212, 30, 7, 134, 117, 220, 58, 85, 201, 124, 76, 119, 171, 16, 128, 75, 95, 142, 33, 112, 7, 235, 237, 106, 176, 42, 79, 101, 233, 123, 218, 40, 105, 40, 131, 178, 105, 26, 164, 83, 217, 72, 110, 192, 245, 134, 156, 200, 121, 190, 53, 159, 136, 149, 20, 92, 59, 158, 40, 180, 6, 85, 38, 37, 93, 140, 11, 230, 95, 178, 209, 159, 73, 21, 62, 164, 247, 235, 114, 164, 239, 84, 185, 99, 134, 105, 190, 168, 189, 167, 27, 238, 210, 2, 112, 69, 54, 80, 247, 122, 86, 253, 131, 10, 159, 124, 219, 234, 81, 177, 64, 99, 143, 18, 94, 3, 89, 126, 215, 254, 57, 136, 35, 251, 152, 4, 75, 83, 7, 14, 173, 250, 86, 240, 132, 155, 171, 59, 157, 144, 235, 150, 58, 239, 151, 106, 248, 62, 217, 115, 177, 243, 37, 62, 9, 112, 90, 140, 185, 240, 145, 164, 215, 124, 134, 196, 57, 138, 244, 108, 145, 11, 134, 234, 74, 14, 83, 168, 222, 161, 94, 196, 27, 62, 111, 11, 245, 13, 223, 217, 47, 99, 120, 59, 28, 42, 108, 190, 217, 153, 150, 225, 33, 129, 182, 150, 222, 184, 9, 211, 250, 40, 251, 26, 87, 30, 105, 113, 145, 86, 251, 186, 2, 48, 64, 78, 226, 97, 29, 180, 111, 247, 49, 19, 172, 160, 115, 128, 187, 240, 111, 243, 248, 11, 153, 91, 245, 24, 58, 252, 112, 187, 27, 121, 31, 167, 186, 76, 120, 233, 82, 227, 216, 104, 215, 29, 12, 12, 64, 186, 167, 219, 232, 4, 42, 243, 80, 133, 189, 137, 153, 195, 94, 197, 53, 121, 178, 185, 130, 75, 22, 139, 144, 149, 183, 245, 40, 120, 155, 165, 174, 7, 167, 181, 162, 119, 237, 197, 38, 65, 9, 118, 213, 181, 211, 221, 15, 59, 203, 170, 144, 112, 198, 212, 142, 173, 131, 227, 47, 242, 125, 175, 250, 168, 202, 212, 196, 247, 16, 252, 32, 130, 19, 183, 197, 152, 227, 141, 52, 55, 200, 15, 20, 97, 204, 65, 93, 10, 120, 31, 15, 181, 5, 206, 152, 136, 15, 123, 62, 56, 41, 77, 186, 12, 130, 52, 214, 202, 19, 248, 159, 45, 60, 27, 161, 44, 27, 187, 86, 213, 105, 23, 80, 153, 214, 245, 35, 66, 210, 98, 56, 245, 117, 156, 78, 78, 47, 35, 204, 105, 234, 210, 165, 101, 148, 112, 48, 233, 236, 73, 113, 182, 166, 187, 148, 32, 131, 68, 76, 85, 241, 41, 160, 23, 156, 84, 103, 66, 137, 3, 154, 30, 167, 192, 237, 211, 122, 65, 195, 65, 212, 121, 49, 235, 68, 201, 11, 13, 93, 149, 14, 221, 51, 31, 108, 134, 83, 93, 155, 61, 32, 57, 240, 180, 161, 235, 211, 66, 126, 100, 95, 131, 109, 198, 54, 37, 62, 137, 50, 82, 153, 255, 213, 2, 181, 72, 145, 248, 127, 150, 33, 22, 116, 128, 52, 102, 39, 17, 42, 83, 116, 80, 245, 220, 80, 113, 226, 20, 196, 84, 91, 215, 172, 92, 88, 128, 146, 220, 102, 243, 125, 13, 216, 215, 253, 102, 224, 212, 225, 126, 145, 135, 188, 163, 4, 71, 218, 141, 77, 112, 100, 235, 236, 104, 27, 214, 216, 97, 49, 245, 236, 45, 136, 5, 96, 17, 171, 70, 254, 205, 252, 85, 26, 11, 3, 50, 153, 5, 6, 18, 38, 87, 251, 25, 111, 236, 216, 28, 95, 163, 218, 170, 16, 59, 140, 96, 220, 87, 191, 133, 47, 127, 100, 184, 241, 40, 167, 140, 115, 193, 17, 28, 209, 208, 43, 4, 50, 117, 181, 65, 236, 131, 71, 163, 119, 101, 67, 174, 160, 220, 231, 177, 245, 80, 115, 201, 34, 195, 158, 24, 42, 103, 198, 136, 152, 93, 190, 61, 169, 105, 188, 109, 185, 90, 14, 126, 238, 33, 234, 17, 151, 148, 91, 178, 93, 198, 188, 178, 26, 218, 78, 236, 16, 156, 146, 19, 227, 18, 103, 254, 182, 51, 186, 96, 223, 105, 129, 228, 81, 12, 150, 92, 88, 146, 171, 73, 243, 9, 126, 195, 1, 57, 60, 113, 204, 21, 87, 160, 166, 162, 118, 26, 112, 45, 153, 59, 41, 84, 247, 190, 29, 26, 26, 45, 99, 202, 65, 224, 37, 142, 37, 192, 116, 255, 129, 13, 246, 71, 172, 40, 138, 140, 44, 255, 209, 188, 175, 60, 230, 215, 86, 229, 217, 141, 115, 38, 154, 5, 123, 32, 247, 173, 166, 149, 70, 91, 68, 172, 168, 92, 147, 170, 5, 95, 75, 188, 101, 48, 160, 145, 225, 66, 192, 56, 138, 208, 121, 222, 23, 164, 228, 78, 3, 182, 172, 94, 107, 237, 114, 208, 233, 191, 209, 69, 58, 38, 255, 207, 226, 212, 124, 62, 186, 3, 198, 55, 147, 17, 52, 84, 78, 137, 172, 200, 140, 70, 8, 187, 55, 235, 129, 247, 186, 96, 194, 225, 9, 94, 38, 19, 119, 170, 247, 243, 43, 54, 112, 54, 172, 67, 29, 201, 17, 141, 143, 37, 105, 62, 82, 244, 131, 148, 106, 99, 147, 46, 0, 7, 242, 47, 231, 201, 105, 127, 111, 140, 58, 228, 216, 128, 236, 33, 42, 245, 128, 88, 111, 95, 200, 56, 37, 84, 184, 80, 179, 102, 226, 39, 179, 112, 188, 90, 137, 111, 158, 162, 116, 63, 169, 250, 126, 29, 22, 41, 31, 148, 193, 99, 64, 67, 216, 160, 73, 154, 184, 129, 246, 44, 102, 21, 168, 126, 145, 169, 203, 232, 6, 59, 65, 125, 180, 122, 28, 33, 91, 66, 68, 11, 246, 74, 118, 52, 229, 200, 28, 209, 215, 255, 68, 122, 40, 146, 124, 181, 245, 25, 179, 139, 95, 42, 74, 228, 207, 206, 2, 239, 156, 136, 73, 221, 73, 248, 94, 184, 75, 148, 126, 25, 71, 22, 237, 14, 53, 132, 145, 216, 64, 172, 212, 153, 178, 182, 93, 71, 113, 109, 64, 41, 146, 190, 22, 198, 238, 171, 72, 155, 6, 182, 205, 234, 157, 74, 43, 188, 187, 28, 94, 0, 138, 133, 238, 30, 216, 154, 160, 31, 87, 137, 58, 217, 221, 186, 154, 138, 244, 50, 30, 253, 220, 34, 175, 0, 139, 55, 26, 103, 35, 136, 210, 180, 7, 223, 221, 201, 212, 190, 39, 128, 63, 46, 210, 156, 149, 19, 41, 41, 77, 147, 26, 253, 40, 253, 134, 125, 115, 89, 117, 156, 169, 47, 154, 227, 178, 155, 20, 40, 79, 82, 164, 103, 55, 107, 251, 8, 95, 197, 237, 81, 14, 18, 16, 62, 14, 48, 28, 206, 137, 27, 247, 69, 214, 38, 201, 128, 128, 105, 197, 72, 135, 246, 249, 24, 244, 244, 6, 73, 146, 2, 186, 54, 50, 143, 77, 118, 185, 187, 252, 195, 32, 11, 40, 224, 212, 41, 26, 238, 23, 81, 67, 81, 200, 3, 15, 19, 45, 129, 22, 17, 189, 107, 111, 239, 235, 57, 58, 145, 230, 37, 212, 75, 189, 44, 191, 123, 9, 250, 137, 224, 186, 84, 145, 158, 236, 11, 83, 142, 103, 92, 71, 98, 214, 103, 184, 10, 36, 208, 143, 74, 186, 201, 158, 166, 67, 144, 15, 183, 228, 12, 193, 220, 199, 141, 64, 234, 145, 94, 212, 110, 15, 14, 92, 84, 57, 50, 164, 252, 198, 205, 233, 18, 175, 239, 161, 196, 89, 188, 165, 189, 16, 162, 108, 6, 187, 140, 197, 165, 202, 107, 193, 54, 44, 163, 10, 241, 218, 30, 197, 37, 1, 189, 180, 133, 214, 32, 245, 16, 46, 49, 239, 156, 56, 151, 36, 115, 170, 222, 96, 135, 165, 9, 191, 10, 207, 128, 219, 170, 102, 85, 2, 8, 59, 237, 132, 35, 94, 187, 139, 136, 243, 50, 103, 43, 140, 167, 51, 70, 252, 200, 198, 120, 13, 212, 85, 35, 170, 135, 196, 38, 190, 172, 190, 136, 12, 50, 67, 209, 125, 228, 189, 164, 247, 38, 69, 79, 122, 149, 172, 221, 41, 25, 254, 126, 156, 38, 201, 56, 239, 158], 'sig': True, 'addr': [], 'seed': [], 'data': []}
serialized_data = json.dumps(data)
data = json.loads(serialized_data)
is_verified = verified(convert(data['k_signer']), data['d_pk'], data['d_signer'], data['sig'], data['addr'], data['seed'], data['data'])
print(is_verified)
</code></pre>
| [
{
"answer_id": 74257130,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 3,
"selected": true,
"text": "is_verified = verified(\n convert(data['k_signer']),\n data['d_pk'],\n convert(data['d_signer'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12500668/"
] |
74,257,106 | <p>I try to call a function in <code>secim()</code> because I want to shorten this function, but it gives a c3861 error. I try a lot of things, but every time it gives a different error. I thought it would be best to share the function without splitting it, because I don't know which way is true. I am new to programming, I think it's an easy problem, but I can't solve it.</p>
<pre><code>#include <iostream>
using namespace std;
int fact(int n) { // function to calculate factorial of a number
if (n <= 1)
return 1;
return n * fact(n - 1);
}
int npr(int n, int r) { // finding permutation
int pnr = fact(n) / fact(n - r);
return pnr;
}
int combin(int n, int r)
{
int f1, f2, f3, y;
f1 = fact(n);
f2 = fact(r);
f3 = fact(n - r);
y = f1 / (f2 * f3);
return y;
}
int secimm2(int s, int n, int r)
{
int ss;
cout << "yeniden denemek ister misiniz 1-evet 2-hayir" << endl;
cin >> ss;
if (ss == 1) {
return secim();
}
else {
return 0;
}
}
int secim()
{
int s, n, r;
cout << "islem seciniz\n1-faktoriyel\n2-perm\n3-kombinasyon\n";
cin >> s;
if (s == 1) {
cout << "1 adet sayi girin\ " << endl;
cin >> n;
cout << fact(n) << endl;
return secimm2(s,n,r);
}
else if (s == 2) {
cout << "2 adet sayi girin\n ";
cin >> n;
cin >> r;
cout << npr(n, r) << endl;
return secimm2(s, n, r);
}
else if (s == 3) {
cout << "2 adet sayi girin\n ";
cin >> n;
cin >> r;
cout << combin(n, r) << endl;
return secimm2(s, n, r);
}
else {
cout << "hatali giris tekrar dene\n" << endl;
return secimm2(s, n, r);
}
}
int main()
{
int s;
cout << "islem seciniz\n1-faktoriyel\n2-perm\n3-kombinasyon\n";
cin >> s;
cout << secim();
}
</code></pre>
| [
{
"answer_id": 74257130,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 3,
"selected": true,
"text": "is_verified = verified(\n convert(data['k_signer']),\n data['d_pk'],\n convert(data['d_signer'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17998759/"
] |
74,257,129 | <p>I've tried doing so much stuff, but nothing works.</p>
<p>My code and directory:</p>
<p><a href="https://i.stack.imgur.com/RU3Pl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RU3Pl.png" alt="my code and directory" /></a></p>
<p>Terminal after I try running it:</p>
<p><a href="https://i.stack.imgur.com/igb0P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/igb0P.png" alt="terminal after i try running it" /></a></p>
<p><a href="https://i.imgur.com/G5qwhK4.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/G5qwhK4.png" alt="another attempt" /></a></p>
<p>I tried disabling some extensions. Nothing
I tried running the command in my terminal. Nothing.
I tried looking at other posts about it. Nothing.</p>
| [
{
"answer_id": 74257130,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 3,
"selected": true,
"text": "is_verified = verified(\n convert(data['k_signer']),\n data['d_pk'],\n convert(data['d_signer'... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374699/"
] |
74,257,178 | <p>I have sentences in the following form. I want to extract all numeric values occurring after any given token. For example, I want to extract all numeric values after the phrase <code>"tangible net worth"</code></p>
<p>Example sentences:</p>
<ol>
<li>"A company must maintain a minimum tangible net worth of $100000000 and leverage ratio of 0.5"</li>
<li>"Minimum required tangible net worth the firm needs to maintain is $50000000".</li>
</ol>
<p>From both of these sentences, I want to extract <code>"$100000000"</code> and <code>"$50000000"</code> and create a dictionary like this:</p>
<pre><code>{
"tangible net worth": "$100000000"
}
</code></pre>
<p>I am unsure how to use the <code>re</code> python module to achieve this. Also, one needs to be careful here, a significant portion of sentences contain multiple numeric values. So, I want only to extract the immediate value occurring after the match. I have tried the following expressions, but none of them are giving desired results</p>
<pre><code>re.search(r'net worth.*(\d+)', sent)
re.search(r'(net worth)(.*)(\d+)', sent)
re.search(r'(net worth)(.*)(\d?)', sent)
re.findall(r'tangible net worth (.*)?(\d* )', sent)
re.findall(r'tangible net worth (.*)?( \d* )', sent)
re.findall(r'tangible net worth (.*)?(\d)', sent)
</code></pre>
<p>A little help with the regular expression will be highly appreciated. Thanks.</p>
| [
{
"answer_id": 74257252,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "tangible net worth.*?(\\$?\\d+)\n"
},
{
"answer_id": 74257260,
"author": "Nick",
"author_id"... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13952588/"
] |
74,257,190 | <p>How do I fix some of these styling issues of overlapping and sizing?</p>
<p><a href="https://i.stack.imgur.com/aITta.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aITta.png" alt="enter image description here" /></a></p>
<pre><code><table class="table table-striped table-sm table-bordered">
<thead>
<tr>
<th>Date Worked</th>
<th>Event Code</th>
<th>Event Name</th>
<th>Time In</th>
<th>Time Out</th>
<th>Hours Worked</th>
</tr>
</thead>
<tbody>
<tr>
<td><input @bind=newEntry.DateWorked /></td>
<td>
<select name="counties" id="counties" @onchange="@((args)=>Test(args, newEntry))">
<option value=" ">Select</option>
<option value="SWN">SWN</option>
<option value="WT">WT</option>
<option value="SE">SE</option>
<option value="HG">HG</option>
<option value="LM">LM</option>
<option value="WM">WM</option>
<option value="CLEAN">CLEAN</option>
</select>
</td>
<td>@newEntry.EventName</td>
<td><input @bind=newEntry.TimeIn /></td>
<td><input @bind=newEntry.TimeOut /></td>
@if (!string.IsNullOrWhiteSpace(newEntry.TimeIn) && !string.IsNullOrWhiteSpace(newEntry.TimeOut))
{
<td>@(GetTimeElapsed(newEntry.TimeIn, newEntry.TimeOut))</td>
}
<td>
<button @onclick="SaveNewRecord" class="btn btn-primary">Save</button>
</td>
</tr>
</tbody>
</table>
</code></pre>
| [
{
"answer_id": 74257291,
"author": "Dimitris Maragkos",
"author_id": 10839134,
"author_profile": "https://Stackoverflow.com/users/10839134",
"pm_score": 2,
"selected": false,
"text": "table"
},
{
"answer_id": 74259641,
"author": "Suprabhat Biswal",
"author_id": 3513848,
... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] |
74,257,191 | <p>This is the code:</p>
<pre><code>word_count = {}
with open(file, "r") as fi:
for line in fi:
words = line.split()
for word in words:
word = word.lower()
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
print(word_count)
</code></pre>
<p>Output:</p>
<pre><code>{'thou': 2, 'ancient,': 1, 'free': 1}
</code></pre>
<p>I want to somehow get access to the numbers 2,1 and 1 so I can get the average usage of the words in my text file. So my question is how do I do it?</p>
<p>I've tried to use the dictionary somehow to add up the numbers in the dictionary but in it, I have both the words and the numbers so I get "TypeError: 'int' object is not iterable".</p>
| [
{
"answer_id": 74257213,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 0,
"selected": false,
"text": "total = sum(word_count.values())\n"
},
{
"answer_id": 74257218,
"author": "Michael M.",
"author_... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374726/"
] |
74,257,233 | <p>I have a strange behaviour between setlocale and mbstowcs.</p>
<p>Here is a sample code :</p>
<pre><code>#include <cstdlib>
#include <iostream>
#include <clocale>
int main()
{
std::setlocale(LC_CTYPE, "");
char * cur_ctype_locale = std::setlocale(LC_CTYPE, NULL); // line 1
std::cout << cur_ctype_locale << std::endl; // line 2
std::string src = "éèùç";
size_t result_size = std::mbstowcs(NULL, &src[0], 0);
if (result_size == (size_t)-1)
{
std::cout << "failed" << std::endl;
return 1;
}
std::wstring result;
result.resize(result_size + 1);
result_size = std::mbstowcs(&result[0], &src[0], result_size + 1);
std::wcout << result << std::endl;
return 0;
}
</code></pre>
<p>When executed (on linux), the output is garbage.</p>
<p>When I remove the lines commented as "line 1" and "line 2" the output is correct (I see the string as defined in the sources).</p>
<p>As far as I read on the documentation of <a href="https://man7.org/linux/man-pages/man3/setlocale.3.html" rel="nofollow noreferrer">setlocale</a>:</p>
<pre><code>If locale is NULL, the current locale is only queried, not modified.
</code></pre>
<p>The lines commented as "line 1" and "line 2" should only return the current locale for LC_CTYPE and not modify the locale.</p>
<p>Am I missing something here ?</p>
<p>Thank you for your attention.</p>
| [
{
"answer_id": 74257213,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 0,
"selected": false,
"text": "total = sum(word_count.values())\n"
},
{
"answer_id": 74257218,
"author": "Michael M.",
"author_... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11112946/"
] |
74,257,299 | <p><a href="https://i.stack.imgur.com/rJtte.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJtte.png" alt="enter image description here" /></a></p>
<p>As the arrow shows .. everything after the closed fragment comes in the same weird color, at the beginning I thought it might be a theme issue but then I recognized that it is not. I really need a solution for this.
I'm new to react by the way</p>
<p>I thought it might be a theme issue but then I recognized that it is not. I really need a solution for this.</p>
| [
{
"answer_id": 74257213,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 0,
"selected": false,
"text": "total = sum(word_count.values())\n"
},
{
"answer_id": 74257218,
"author": "Michael M.",
"author_... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14271438/"
] |
74,257,315 | <p>A planned software upgrade causes stricter SQL parsing of Flyway migration scripts. The syntax needs to fixed, but this will change the checksum and fail Flyway's validation. The semantics of the SQL do not change. Is there of making the scripts legal without clumsily repairing databases?</p>
<p>It looks like a 32-bit checksum, so that is unlikely to be secure. Ideally I'd like:</p>
<ul>
<li>just a few magic printable US ASCII letters in a comment at the top of the file</li>
<li>not require me to give my SQL away</li>
<li>generated by code that I can understand</li>
<li>not need any special hardware or configuration</li>
</ul>
<p>Does anyone have any cunning techniques?</p>
| [
{
"answer_id": 74257213,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 0,
"selected": false,
"text": "total = sum(word_count.values())\n"
},
{
"answer_id": 74257218,
"author": "Michael M.",
"author_... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4725/"
] |
74,257,336 | <p>I need to create a single table with same column metrics aggregated for different time periods in Redshift SQL. Instead of repeating the code so many times with varying "WHERE" clause, is there a way I can reuse the code and keep it simple?</p>
<pre><code>select
c1 as c1,
sum(c2) t30_c2,
sum(c3) t30_c3,
max(c4) t30_c4,
from t1
join t2 ()
join t3()
join date_tbl
where date between current_date -30 and current_date;
select
c1 as c1,
sum(c2) t90_c2,
sum(c3) t90_c3,
max(c4) t90_c4,
from t1
join t2 ()
join t3()
join date_tbl
where date between current_date -90 and current_date;
.
.
where date between current_date -120 and current_date
</code></pre>
<p>Finally place all these column level metrics in a single table.</p>
| [
{
"answer_id": 74257213,
"author": "FLAK-ZOSO",
"author_id": 15888601,
"author_profile": "https://Stackoverflow.com/users/15888601",
"pm_score": 0,
"selected": false,
"text": "total = sum(word_count.values())\n"
},
{
"answer_id": 74257218,
"author": "Michael M.",
"author_... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4912477/"
] |
74,257,366 | <p>I have been trying to make a chat logger for a discord server I run that looks at a conversation takes the messages and store them in a txt file. I am unsure of any ways to log this as my current code can only log contents that mention the bot itself. I do have the intent set to true on the discord application portal, do I need to actually do anything in the code to allow it to get the contents of any message?</p>
<p>`</p>
<pre><code>@client.event
async def on_message(message):
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
usermessage = "{} {} {}".format(dt_string, message)
with open('data/discord/log.txt', 'a+') as y:
y.write(usermessage + '\n')
print(message.content)
client.run(TOKEN)
</code></pre>
<p>`</p>
<p>I tried making the message var into a str using
<code>text = str(message.content)</code>
but it gave the message content when the bot was mentioned.</p>
| [
{
"answer_id": 74282278,
"author": "Dauern",
"author_id": 20367901,
"author_profile": "https://Stackoverflow.com/users/20367901",
"pm_score": 1,
"selected": false,
"text": "client = discord.Client(intents=discord.Intents.default())"
},
{
"answer_id": 74367022,
"author": "supe... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20367901/"
] |
74,257,374 | <p>Given a string s, return true if the s can be palindrome after deleting at most one character from it.</p>
<p>Example 1:</p>
<pre><code>Input: s = "aba"
Output: true
</code></pre>
<p>Example 2:</p>
<pre><code>Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
</code></pre>
<p>Example 3:</p>
<pre><code>Input: s = "abc"
Output: false
</code></pre>
<p>For this problem in leetcode my code has passed 462/469 test cases:</p>
<p>Following is the test case for which my code is failing the test.</p>
<pre><code>"aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga"
</code></pre>
<p>My code is:</p>
<pre><code>class Solution:
def validPalindrome(self, s: str) -> bool:
skip=0
l,r=0,len(s)-1
while l<r:
if s[l]==s[r]:
l+=1
r-=1
elif s[l]!=s[r] and skip<1 and s[l+1]==s[r]:
l+=1
skip=1
elif s[l]!=s[r] and skip<1 and s[r-1]==s[l]:
r-=1
skip=1
else:
return False
return True
</code></pre>
<p>What is the problem with my code?</p>
<p>Note: in this string the output should be true, mine returns false</p>
<p>From left there are characters 'lcup' and from right there are characters 'lucup'
My code is supposed to skip the letter u from right side and continue.</p>
<pre><code>"aguokepatgbnvfqmgm**lcup**uufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuu**pucul**mgmqfvnbgtapekouga"
</code></pre>
<p>Another example: It returns true for the following string:
<code>s='adau'</code></p>
<p>Skips letter 'u' as expected.</p>
<p>However when I use the example according to the test case string that failed, it returns False. <code>s= 'cuppucu'</code></p>
<p>It should skip first u from the right side and return True but it doesn't.</p>
<p>However as soon as I replace that last letter 'u' with letter 'a' it skips the letter 'a' and returns True. What's the problem here?</p>
| [
{
"answer_id": 74282278,
"author": "Dauern",
"author_id": 20367901,
"author_profile": "https://Stackoverflow.com/users/20367901",
"pm_score": 1,
"selected": false,
"text": "client = discord.Client(intents=discord.Intents.default())"
},
{
"answer_id": 74367022,
"author": "supe... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19557051/"
] |
74,257,381 | <p>I am looking after a portal on a low-code platform. I am trying to update the background-color for a box on our portal, however am really struggling to update this.</p>
<p>I have copied the selector and also included a screenshot from the console.</p>
<p>If someone could point me in the right direction I would really appreciate that.</p>
<p><a href="https://i.stack.imgur.com/zOG5U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zOG5U.png" alt="console" /></a></p>
<p>div.ideas-list--cntr.ng-scope > div > div.panel.panel-default.ideas-list--panel > div > div.panel-body.ideas-list--content > ul > li:nth-child(1) > div > div.idea-details--cntr > div.ideas-categories--cntr > a</p>
<p>Thanks
Mike</p>
<p>I have tried updating the background color as follows and was expecting a white background for the box:</p>
<pre><code>.ideas-list--panel .ideas-categories--cntr a {
background-color: white;
}
</code></pre>
<p>However, I am still seeing #33466C background color.
<a href="https://i.stack.imgur.com/xnepl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xnepl.png" alt="box" /></a></p>
| [
{
"answer_id": 74282278,
"author": "Dauern",
"author_id": 20367901,
"author_profile": "https://Stackoverflow.com/users/20367901",
"pm_score": 1,
"selected": false,
"text": "client = discord.Client(intents=discord.Intents.default())"
},
{
"answer_id": 74367022,
"author": "supe... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19614013/"
] |
74,257,386 | <p>Could anyone please help with one right solution?
Convert to english with certain spaces between every letter and words.
l did:</p>
<pre><code>eng_dict = {'.-': 'a', '-...': 'b', '-.-.': 'c',
'-..': 'd', '.': 'e', '..-.': 'f',
'--.': 'g', '....': 'h', '..': 'i',
'.---': 'j', '-.-': 'k', '.-..': 'l',
'--': 'm', '-.': 'n', '---': 'o',
'.--.': 'p', '--.-': 'q', '.-.': 'r',
'...': 's', '-': 't', '..-': 'u',
'...-': 'v', '.--': 'w', '-..-': 'x',
'-.--': 'y', '--..': 'z', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
nomorse = input("Enter your code here: ")
nomorse_list = nomorse.split(' ')
text = ''
morse= True
for letter in nomorse_list:
for key in morse_eng_dict.keys():
if letter == key:
text = text + str(morse_eng_dict[key])
if letter == '':
text = text + " "
if morse == True:
string = "".join(text)
print(string)
</code></pre>
<p>the problem.. Sometimes there can be not possible conversion of some coded symbols. that symbols can be displayed like " * "</p>
<p>for example: "- .... .. ....... - . .- --" should be "thi* team"</p>
<p>if try to put like</p>
<pre><code> if letter != key:
letter = '*'
text = text + str(morse_eng_dict[key] + '*')
</code></pre>
<p>that shows * after every doubled letter
the rest of my attempts all resulted text with spaces in every certain letters.</p>
| [
{
"answer_id": 74257417,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 1,
"selected": false,
"text": "if letter in morse_eng_dict:\n # letter is in the dict. handle appropriately\nelse:\n # letter is not in th... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280838/"
] |
74,257,395 | <p>I know that in libaaa.so there is an exported (the symbol is in the text/code section) function obj1() at address 0x12345 from the start of the library.</p>
<p><code>CLibrary libaaa = (CLibrary)Native.load("aaa", CLibrary.class);</code></p>
<p>I want to invoke a function obj2() which I know to be at address 0x12444 from the start of the library OR the address of (obj1() + 0xff) (0x12444-0x12345=0xff)</p>
<p>The obj2() symbol is NOT in the text/code section, so I can only invoke it by its address (which I know.) I understand that I could use <code>Function.getFunction(new Pointer(funcAddr), 0, "utf8");</code> if I had the function's address, but I do not know what address JNA will load the library.</p>
<p>I can easily access the obj1() function (aaa.obj1()) that's trivial, but how could I access the aaa.obj2() function which is not in the text section, and thereby only referable from its offset in the library (or offset from another function in the text/code section.)</p>
<p>Thank you.</p>
| [
{
"answer_id": 74264462,
"author": "user2543253",
"author_id": 2543253,
"author_profile": "https://Stackoverflow.com/users/2543253",
"pm_score": 0,
"selected": false,
"text": "Function"
},
{
"answer_id": 74277259,
"author": "matt",
"author_id": 2067492,
"author_profil... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252930/"
] |
74,257,396 | <p>Could someone explain why can't I change the value of var in that case ?</p>
<pre><code>fun main(args: Array<String>) {
var number = 3
changeNumber(number)
}
fun changeNumber(number: Int) {
number = 4 //here I see a warning "val cannot be reassigned"
}
</code></pre>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10405000/"
] |
74,257,403 | <p>I have an interface that looks like this:</p>
<pre><code>export interface GeneralInfo{
Name: string;
Description: string;
}
</code></pre>
<p>Later in a component class, I have the following code</p>
<pre><code>export class SignalsComponent implements OnInit {
objGeneral: GeneralInfo;
constructor(private _apiService: APIService)
openPopUp(){
this._apiService.getJsonData().subscribe(
(res => {
var tempJson = JSON.parse(res);
this.objGeneral = tempJson.General as GeneralInfo;
console.log("json --->", this.objGeneral.Description);
}),
(err => { })
);
}
}
</code></pre>
<p>When I look at the browser console all works and I see the data I expect to see. However, when I try to invoke the objGeneral.Description property in HTML, it fails. This is my HTML:</p>
<pre><code><div class="col-lg-6 col-md-6">
{{objGeneral.Description}}
</div>
</code></pre>
<p>What am I doing wrong?</p>
<p>Thank you</p>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3991432/"
] |
74,257,432 | <p>I am using the latest (as of today) version of React+ React-Redux.<br />
When I start my app, I load a list of data I need to store in a slice that is used for one purpose. For this example, a list of table names and their fields.<br />
I also have a slice that manages UI state, Which needs <strong>only</strong> the table names to create a sub-menu.<br />
The list of tables with all it's data is loaded into slice <strong>tree</strong> and I need to copy just the table names into a slice called <strong>UI</strong>.</p>
<p>I am not very clear on the best way (or the right way) to move data between two sibling slices.</p>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67153/"
] |
74,257,433 | <p>I have a folder with 200+ excel files. I have the respective path and sheet names for each file in the folder. Is it possible to merge all of these files into one or a couple large excel file via python? If so, what libraries would be good for me to start reading up on for this type of script?</p>
<p>I am trying to condense the files into 1-8 excel files in total not 200+ excel files.</p>
<p>Thank you!</p>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20360218/"
] |
74,257,508 | <p>I am trying to make a dictionary where the compiler reads from a text file where there are two words per line. I have parsed it through the split() method but I am struggling on how to add the corresponding keys and values from the line to the dictionary container. I am trying to add it in the ReadStream2() function after doing the split() in the line line.add(rez,rez). I know this is wrong but I have no idea how to combine what I am parsing into the dictionary in terms of keys and values. Thanks!</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Dictionary<string, string> line = new Dictionary<string, string>();
FileStream filestream = null;
string path = "Dictionary.txt";
//WriteByte(filestream, path);
//ReadByte(filestream, path);
//WriteStream(filestream, path);
//ReadFromFile();
Menu(filestream, path);
ReadStream2(filestream,path);
Group(filestream, path);
}
static void WriteByte(FileStream filestream, string path)
{
string str;
Console.WriteLine("Enter word");
str = Console.ReadLine();
try
{
filestream = new FileStream("Dictionary.txt", FileMode.Open, FileAccess.Write);
byte[] by = Encoding.Default.GetBytes(str);
filestream.Write(by, 0, by.Length);
Console.WriteLine("File written");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
filestream.Close();
}
}
static void ReadByte(FileStream filestream, string path)
{
try
{
filestream = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] by = new byte[(int)filestream.Length];
filestream.Read(by, 0, by.Length);
string str = Encoding.Default.GetString(by);
Console.WriteLine("File read");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
filestream.Close();
}
}
static void WriteStream(FileStream filestream, string path)
{
using (filestream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter streamWriter = new StreamWriter(filestream))
{
//string str;
//Console.WriteLine("Enter word");
//str = Console.ReadLine();
//streamWriter.WriteLine(str);
}
}
}
static void ReadStream2(FileStream fileStream, string path)
{
using (fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
Dictionary<string, string> line = new Dictionary<string, string>();
using (StreamReader sw = new StreamReader(fileStream))
{
string rez = "";
while(sw.Peek() > 0)
{
rez = sw.ReadLine();
Console.WriteLine(rez);
string[] words = rez.Split(' ');
line.Add(rez, rez);
}
}
}
}
static void Group(FileStream fileStream, string path)
{
var list = File
.ReadLines(path)
.Select((v, i) => new { Index = i, Value = v })
.GroupBy(p => p.Index / 2)
.ToDictionary(g => g.First().Value, g => g.Last().Value);
}
static void Menu(FileStream fileStream, string path)
{
char choice;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Welcome this is a English dictionary press d to continue");
Console.ResetColor();
choice = Convert.ToChar(Console.ReadLine());
while (choice == 'd' || choice == 'D')
{
ReadStream2(fileStream, path);
}
}
static void askWord()
{
string ask;
Console.WriteLine("What english word would you like to translate");
ask = Console.ReadLine();
if (ask == )
}
}
</code></pre>
<p>}</p>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19192632/"
] |
74,257,513 | <p><strong>.env</strong></p>
<pre><code>STAGING_BUCKET=our-staging-bucket
</code></pre>
<p><strong>common.py</strong> (in same directory as .env)</p>
<pre><code>import os
STAGING_BUCKET = os.getenv('STAGING_BUCKET')
print(STAGING_BUCKET)
</code></pre>
<p>When we run our airflow project locally, we receive a different value <code>diff-staging-bucket</code> for our STAGING_BUCKET variable. We recently changed this variable in our .env from <code>diff-staging-bucket</code> to <code>our-staging-bucket</code>. It seems like <code>os.getenv('STAGING_BUCKET')</code> is grabbing a globally saved <code>STAGING_BUCKET</code> variable, rather than the one in the .env file, as we can run this code locally in python from our home directory and the old <code>diff-staging-bucket</code> is still returned.</p>
<p>How can we straighten this out so that we receive the correct <code>.env</code> variable here</p>
<p><strong>EDIT</strong> I ran <code>env</code> from the command line and yes there is a global STAGING_BUCKET variable that is <code>diff-staging-bucket</code></p>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5573294/"
] |
74,257,527 | <p>So if and elif statements are not working</p>
<pre><code>def weight_converter():
print("Welcome to Weight Converter")
operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram"))
if operation == " 1":
gram_one = int(input("Grams needed to convert to pound: "))
print("You have", gram_one * 453.57,"pounds")
elif operation == " 2":
pound_one = int(inpu())
weight_converter()
</code></pre>
<p>So I am expecting for the if statement to run but then the gram_one input does not show up. Please help me to fix that.</p>
| [
{
"answer_id": 74257468,
"author": "Agustin Pazos",
"author_id": 5451645,
"author_profile": "https://Stackoverflow.com/users/5451645",
"pm_score": 2,
"selected": false,
"text": "data class IntegerHolder( \n var v:Int\n)\n\nfun main() {\n var a:IntegerHolder = IntegerHolder(2)\n chang... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372870/"
] |
74,257,533 | <p>Does <code>std::remove_cvref</code> replace <code>std::decay</code> after C++20?</p>
<p>From <a href="https://github.com/thecppzoo/zoo/issues/7" rel="nofollow noreferrer">this link</a>,
I cannot understand what this means:</p>
<blockquote>
<p>C++20 will have a new trait <code>std::remove_cvref</code> that doesn't have undesirable effect of <code>std::decay</code> on arrays</p>
</blockquote>
<p>What is the undesirable effect of <code>std::decay</code>?</p>
<p>Example and explanation, please!</p>
| [
{
"answer_id": 74257596,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 4,
"selected": true,
"text": "std::remove_cvref"
},
{
"answer_id": 74257608,
"author": "Mikdore",
"author_id": 8309536,
"author... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13133437/"
] |
74,257,567 | <p>I was developing a GAN to generate 48x48 images of faces. However, the generator makes strange images no matter how much training is done, and no matter how much the discriminator thinks it's fake. This leads me to believe that it is an architectural problem.</p>
<hr />
<p>untrained output</p>
<p><a href="https://i.stack.imgur.com/QJElS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QJElS.png" alt="untrained" /></a></p>
<p>After 25 epochs</p>
<p><a href="https://i.stack.imgur.com/nu8Gd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nu8Gd.png" alt="25 epochs" /></a></p>
<p>The problem is obvious. Squares generating in patterns instead of random pixels, as would be expected from an untrained GAN.</p>
<p>This problem appears to be related to the filter size of the deconvolution layers in the generator, but I'm not sure how.</p>
<p>This is an image from a 5x5 kernel size</p>
<p><a href="https://i.stack.imgur.com/orCzq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/orCzq.png" alt="enter image description here" /></a></p>
<p>My question is:</p>
<ol>
<li><p>Why is this happening? What effect is the filter size having on the images that causes this sort of pattern</p>
</li>
<li><p>How can I tell what size filter to use in relation to the image size or other parameter?</p>
</li>
</ol>
<p>Models:</p>
<pre class="lang-py prettyprint-override"><code>
generator = keras.Sequential([
keras.layers.Dense(4*4*32, input_shape=(100,), use_bias=False),
keras.layers.LeakyReLU(),
keras.layers.Reshape((4, 4, 32)),
SpectralNormalization(keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding="same", use_bias=False)),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding="same", use_bias=False)),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2DTranspose(3, (2, 2), strides=(3, 3), padding="same", use_bias=False)),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2DTranspose(3, (2, 2), strides=(2, 2), padding="same", use_bias=False)),
])
discriminator = keras.Sequential([
keras.layers.Conv2D(128, (2, 2), strides=(2, 2), input_shape=(96, 96, 3), padding="same"),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2D(64, (2, 2), strides=(2, 2), padding="same")),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2D(32, (2, 2), strides=(2, 2), padding="same")),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2D(16, (2, 2), strides=(2, 2), padding="same")),
keras.layers.LeakyReLU(),
SpectralNormalization(keras.layers.Conv2D(8, (2, 2), strides=(2, 2), padding="same")),
keras.layers.LeakyReLU(),
keras.layers.Flatten(),
keras.layers.Dense(1, activation="sigmoid")
])
</code></pre>
<p>The training loop was taken from the <a href="https://www.tensorflow.org/tutorials/generative/dcgan#define_the_training_loop" rel="nofollow noreferrer">Tensorflow GAN tutorial</a></p>
<pre class="lang-py prettyprint-override"><code>
cross_entropy = tf.keras.losses.BinaryCrossentropy()
def discriminator_loss(real_output, fake_output):
real_loss = cross_entropy(tf.ones_like(real_output), real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
@tf.function
def train_step(images):
noise = tf.random.normal([32, 100])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
</code></pre>
| [
{
"answer_id": 74318442,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 2,
"selected": true,
"text": "strides"
},
{
"answer_id": 74508527,
"author": "Ayazzia01",
"author_id": 15636887,
"author_profile": ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14523193/"
] |
74,257,571 | <p>Telethon event handler waits 1 minute before sending out a burst of messages at the same time.</p>
<p>I tried removing functions from other souces as I thought that could be it and it did not work.
code:
`</p>
<pre><code>from telethon import TelegramClient, events
import logging
import time
#from main import add
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING)
api_id =
api_hash =
client = TelegramClient('anon', api_id, api_hash)
@client.on(events.NewMessage)
async def my_event_handler(event):
print(event.raw_text)
#add(event.raw_text)
client.start()
client.run_until_disconnected()
</code></pre>
<p>`</p>
| [
{
"answer_id": 74318442,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 2,
"selected": true,
"text": "strides"
},
{
"answer_id": 74508527,
"author": "Ayazzia01",
"author_id": 15636887,
"author_profile": ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374982/"
] |
74,257,586 | <p>I have two classes and a "use" class function that performs multiple actions using the various attributes as the inputs so that I can just call the one function and get different results based on which class object is referenced. Where I am getting stuck is that I want to have part of the use function check the 'effect' attribute and call the function found there. Currently, the function named in effect is called when the object c is defined, and everything I have tried within the use function has no effect or returns 'none' since I don't have a return statement in the add and sub functions.
I've provided a simplified example code below. C has 9 attributes and 10 different class functions that I would want to use in the effect spot. I plan on having 50+ different C objects, so not having to write out specific functions for each one would be spectacular.</p>
<p>In this example, the print(p.h) at the end returns 101, showing that designing the C object calls the add function I put in the attribute:</p>
<pre><code>M= []
class P:
def __init__(p, h, s):
p.h= h
p.s=s
class C:
def __init__(y, name, d, f effect,):
y.name= name
y.effect= effect
y.d= d
y.f= f
def use(c):
M.append(c)
p.h -= p. y.d
p.s += y.f
effect
def add(c, x):
p.h += x
def sub(c, x):
p.h -=x
p= P(100)
c= C('test1', add(1), 1)
print(p.h)
</code></pre>
<p>I have tried the add and sub functions as both class and standalone, which didn't seem to make a difference, calling y.effect as though it were a function which just returns 'none' as mentioned, and adding the property decorator, which threw an error, probably because I don't quite understand what that is supposed to do yet.</p>
| [
{
"answer_id": 74318442,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 2,
"selected": true,
"text": "strides"
},
{
"answer_id": 74508527,
"author": "Ayazzia01",
"author_id": 15636887,
"author_profile": ... | 2022/10/30 | [
"https://Stackoverflow.com/questions/74257586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366887/"
] |
74,257,594 | <p>I have three functions. I want to write another function where I can use an argument in the form of an integer, in order to chose which one of the other functions to invoke. For example, using the argument "1" will invoke sayNum1 etc.</p>
<p>Or, can I write a function that with the use of an integer, invokes a specific console.log instead?</p>
<pre><code>function sayNum1() {
console.log("One");
}
function sayNum2() {
console.log("Two");
}
function sayNum3() {
console.log("Three");
}
</code></pre>
| [
{
"answer_id": 74257871,
"author": "logesh sankar",
"author_id": 19225737,
"author_profile": "https://Stackoverflow.com/users/19225737",
"pm_score": 0,
"selected": false,
"text": "function sayNum1(){\n alert(\"one\");\n}\n\nfunction sayNum2(){\n alert(\"two\");\n}\n \n function sayNum3... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18504257/"
] |
74,257,601 | <p>I want to get all tokens that aren't only digits - so 'abc' and 'abc7' and '123xyz' are ok but '1234' isn't.</p>
<p>I know you can use</p>
<pre><code>\b\d+\b
</code></pre>
<p>to get just '1234' but when I try adding '^' to the front of that it doesn't match anything.</p>
| [
{
"answer_id": 74257628,
"author": "Milan",
"author_id": 3870905,
"author_profile": "https://Stackoverflow.com/users/3870905",
"pm_score": 1,
"selected": false,
"text": "(?!^\\d+$)^.+$\n"
},
{
"answer_id": 74257994,
"author": "Andrej Kesely",
"author_id": 10035985,
"a... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18750051/"
] |
74,257,605 | <p>While looking for solutions, I found some related discussions, but none of the solutions worked in my case.</p>
<p>I made a "RefreshableScrollFrame" widget in my app, which offers a generic frame for pages that should show a StatusBar (loading indicator, etc.) and which should provide a pull-down to refresh.</p>
<p>RefreshableScrollFrame</p>
<pre><code>return Center(
child: Column(
children: [
SizedBox(
height: 4,
child: const MyStatusbarWidget(),
),
RefreshIndicator(
onRefresh: onRefresh,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: child,
),
)
],
),
);
</code></pre>
<p>Child Option - ListView:</p>
<pre><code>ListView.builder(
itemCount: items.length,
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, i) => Card(
child: ListTile(
title: Text(items[i].name),
),
),
);
</code></pre>
<p>Child Option - Column with the <code>ListView</code> and static items:</p>
<pre><code>Column(
children: [
ListView.builder(
itemCount: items.length,
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, i) => Card(
child: ListTile(
title: Text(items[i].name),
),
),
),
...someStaticWidgets,
],
);
</code></pre>
<p>So far so good, everything works fine, except for one important detail.
The RefreshIndicator is only triggered in areas, which are covered by the child widget. If the content is small and covers just the top of the page, the gesture is detected only in that area.
If the content is just an empty ListView, I won't even be able to trigger a refresh.</p>
<p>I tried several suggested solutions in order to "expand" the child to the whole screen, but I always ran into exceptions, when trying to get rid of shrinkWrap, when adding Expanded(), and so on.</p>
<p>Any hints would be appreciated.</p>
| [
{
"answer_id": 74257628,
"author": "Milan",
"author_id": 3870905,
"author_profile": "https://Stackoverflow.com/users/3870905",
"pm_score": 1,
"selected": false,
"text": "(?!^\\d+$)^.+$\n"
},
{
"answer_id": 74257994,
"author": "Andrej Kesely",
"author_id": 10035985,
"a... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19601316/"
] |
74,257,623 | <p>I am trying to find the odd numbers in a range of numbers, and adding them all up.</p>
<ol>
<li>I set my variable which is the range of numbers (5)</li>
<li>I then made a function which had the for statement, looking for the numbers in range from 1 to 1+num(this is for including the number) and the comma after that to skip every other number.</li>
<li>Then I printed the total sum, and outside of the function I called the function.</li>
</ol>
<pre><code>num = 5
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 1):
sum = sum+i
print(sum)
sumOfOdds()
</code></pre>
<p>I tried to read other ways to fix this, but was unable to find a solution.</p>
| [
{
"answer_id": 74257648,
"author": "Filip Lav Maksimovic",
"author_id": 8466949,
"author_profile": "https://Stackoverflow.com/users/8466949",
"pm_score": 1,
"selected": false,
"text": "def sumOfOdds():\n sum = 0\n for i in range(1, 1+num, 2): # Here we set it to 2\n sum = s... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17776082/"
] |
74,257,650 | <p>I have a sequence, and I am trying to make a program to find the nth term of the sequence.</p>
<p>The sequence is as follows:</p>
<p>1, 11, 21, 1211, 111221, 312211...</p>
<p>In this sequence, each term describes the previous term. For example, "1211" means that the previous term; the previous term is "21" where there is <strong>one</strong> occurrence of a <strong>2</strong> and then <strong>one</strong> occurrence of a <strong>1</strong> (=1211). To get the third term, "21," you look at the second term: 11. There are <strong>two</strong> occurrences of a <strong>1</strong> which gives us "21."</p>
<pre><code>import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println( Main.num(n-1, "1"));
}
public static String num(int times, String x){
if(times == 0){
return x;
}else{
//System.out.println("meow");
String y = "" + x.charAt(0);
int counter = 0;
for(int i = 1; i < x.length(); i++){
if(x.charAt(i) == x.charAt(i-1)){
counter++;
}else{
y += "" + counter + x.charAt(i-1);
counter = 0;
}
}
return num(times--, y);
}
//return "";
}
}
</code></pre>
<p>My code uses recursion to find the nth term. But, it gives us errors :(</p>
<p>First, I start of the method "num" by passing it the number of terms-1 (since the first term is already given) and the first term (1).</p>
<p>In the method num, we start off by using a conditional to establish the base case (when you are done finding the nth term).</p>
<p>If the base case is false, then you find the next term in the sequence.</p>
| [
{
"answer_id": 74257677,
"author": "Aniketh Malyala",
"author_id": 14645101,
"author_profile": "https://Stackoverflow.com/users/14645101",
"pm_score": 4,
"selected": true,
"text": "n"
},
{
"answer_id": 74257925,
"author": "Community",
"author_id": -1,
"author_profile"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374980/"
] |
74,257,702 | <p>How can I remove this grey bar at the bottom of the CupertinoNavigationBar? I have tried changing the backgroundColor for the nav bar but it doesn't seem to have any effect on the grey bar. I can change it to transparent or match it with the Container's background color but the grey bar is still visible.</p>
<p><a href="https://i.stack.imgur.com/xyBA8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xyBA8.png" alt="enter image description here" /></a></p>
<pre><code>import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
class ModalFitCreate extends StatelessWidget {
const ModalFitCreate({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Material(
child: SafeArea(
top: false,
child: Container(
color: const Color(0xFFF5F5F5),
child: Column(
children: [
CupertinoNavigationBar(
backgroundColor: Colors.transparent,
automaticallyImplyLeading: false,
leading: TextButton(
style: ButtonStyle(
overlayColor: MaterialStateProperty.all(Colors.transparent),
),
onPressed: () {
Navigator.pop(context);
},
child: const Text(
'Cancel',
style: TextStyle(
fontSize: 16,
)
)
),
middle: const Text(
'New Event',
style: TextStyle(
fontSize: 16,
)
),
trailing: TextButton(
style: ButtonStyle(
overlayColor: MaterialStateProperty.all(Colors.transparent),
),
onPressed: () {},
child: const Text(
'Add',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
)
)
),
),
],
)
)
));
}
}
</code></pre>
| [
{
"answer_id": 74257677,
"author": "Aniketh Malyala",
"author_id": 14645101,
"author_profile": "https://Stackoverflow.com/users/14645101",
"pm_score": 4,
"selected": true,
"text": "n"
},
{
"answer_id": 74257925,
"author": "Community",
"author_id": -1,
"author_profile"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373971/"
] |
74,257,714 | <p>I have a list of emails and I want to group by <code>mylist</code> with domain names or specific substring that contains all of string items(eg: @gmail.com or @yahoo.com).</p>
<p>Please note that I don't want just gmail and yahoo because there are many domains like @yahoo.fr or @hotmail.com.</p>
<p>After that, I want to add all of subgroup items into own separated list string.</p>
<p><em>e.g.</em>:</p>
<pre><code>var Emails = new List<string>
{
"a@gmail.com",
"b@yahoo.fr",
"c@tafmail.com",
"b@mail.ru"
};
</code></pre>
<p>I tried group by with regex parameter, but it didn't work</p>
| [
{
"answer_id": 74257797,
"author": "Trey Mack",
"author_id": 237012,
"author_profile": "https://Stackoverflow.com/users/237012",
"pm_score": 1,
"selected": false,
"text": "using System.Text.Json;\n\nList<string> emails = new()\n{\n \"a@gmail.com\",\n \"b@yahoo.fr\",\n \"c@yahoo.... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20375009/"
] |
74,257,715 | <p>I want to remove the first 3 letters from every item (String) in my List.</p>
<p>My Listitems look like this:</p>
<pre><code>{2: test1.mp4
3: test2.mp4
4: test3.mp4
10: test4.mp4
11: test5.mp4
</code></pre>
<p>I want to remove the "{2: " from the firs item and for every other item i want to remove the number + the space, so that i only have the file name.</p>
| [
{
"answer_id": 74257760,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 2,
"selected": false,
"text": "substring"
},
{
"answer_id": 74257784,
"author": "Evan",
"author_id": 18686803,
"author_profile... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74257715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11724945/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.