qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,584,806
|
<p>i have an assignment coming up in which i have to code a dice game . its multiplayer random luck with gambling points and etc</p>
<p>one of the things its asking for though is to save the winning players name and their score into a text file and at the end print the five highest scores in the text file with the five players names, ive got the code so that it saves the players name and score along with some text but have absolutely no idea on how to read the whole text file and and pick out lines that have the 5 largest integers and print them</p>
<p>`</p>
<pre><code>name = str(input("Player 1 name"))
name2 = str(input("Player 2 name"))
score = str(input("Player 1 score"))
score2 = str(input("Player 2 score"))
text_file = open("CH30.txt", "r+")
if score > score2:
content = text_file.readlines(30)
if len(content) > 0 :
text_file.write("\n")
text_file.write(name)
text_file.write (" wins with ")
text_file.write (score)
text_file.write (" points")
else:
content = text_file.readlines(30)
if len(content) > 0 :
text_file.write("\n")
text_file.write (name2)
text_file.write (" wins with ")
text_file.write (score2)
text_file.write (" points")
</code></pre>
<p>`</p>
<p>the full game is not attached as I'm at my dads house currently and forgot to bring my usb stick
any help on how to do this would be much appreciated :)</p>
|
[
{
"answer_id": 74584961,
"author": "Ni3dzwi3dz",
"author_id": 12768056,
"author_profile": "https://Stackoverflow.com/users/12768056",
"pm_score": 0,
"selected": false,
"text": "\"Rick wins with 98 points\" scores.sort(key= lambda x : int(x.split(\" \")[3]))"
},
{
"answer_id": 74585202,
"author": "serafm",
"author_id": 11353686,
"author_profile": "https://Stackoverflow.com/users/11353686",
"pm_score": 1,
"selected": false,
"text": "Player1 wins with 30 points\nPlayer2 wins with 40 points\nPlayer3 wins with 85 points\nPlayer5 wins with 45 points\nPlayer7 wins with 10 points\nPlayer6 wins with 80 points\nPlayer4 wins with 20 points\nPlayer9 wins with 90 points\nPlayer8 wins with 70 points\nPlayer11 wins with 120 points\nPlayer10 wins with 15 points\n text_file.write(\"\\n\") text_file.write(name)\ntext_file.write (\" wins with \")\ntext_file.write (score)\ntext_file.write (\" points\")\ntext_file.write(\"\\n\")\n text_file = open('CH30.txt.', 'r')\nLines = text_file.readlines()\nPlayersScores = []\n\n# read each line get the player name and points \nfor line in Lines:\n # split the line into list of strings\n line = line.split(\" \")\n # removing \\n from last element\n line[-1] = line[-1].replace(\"\\n\", \"\")\n print(line)\n # find player name position\n playerName = line.index(\"wins\") - 1\n # find points position\n points = line.index(\"points\") - 1\n # add the tuple (playerName, points) in a list\n PlayersScores.append((line[playerName], line[points]))\n# descending order sort by player score\nPlayersScores = sorted(PlayersScores, key=lambda t: t[1], reverse=True)\n\n# get the first 5 players\nprint(\"Highest Scores:\\n\")\nfor i in range(5):\n print(str(i+1) + \". \" + PlayersScores[i][0] + \" \" + PlayersScores[i][1] + \" points\")\n Highest Scores:\n\n1. Player11 120 points\n2. Player9 90 points\n3. Player3 85 points\n4. Player6 80 points\n5. Player8 70 points\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301938/"
] |
74,584,816
|
<p>I have a list of columns in a dataframe that either contains a hashmark followed by a string or two hashmarks followed by a string. I wanted to eliminate the rows that contain only one hashmark.</p>
<p><code>df[df["column name"].str.contains("#") == False]</code></p>
<p>I've tried using the code above but it erased the entire column. I hoped that it would erase only the rows including only one hashmark. I do not know what to do.</p>
|
[
{
"answer_id": 74584961,
"author": "Ni3dzwi3dz",
"author_id": 12768056,
"author_profile": "https://Stackoverflow.com/users/12768056",
"pm_score": 0,
"selected": false,
"text": "\"Rick wins with 98 points\" scores.sort(key= lambda x : int(x.split(\" \")[3]))"
},
{
"answer_id": 74585202,
"author": "serafm",
"author_id": 11353686,
"author_profile": "https://Stackoverflow.com/users/11353686",
"pm_score": 1,
"selected": false,
"text": "Player1 wins with 30 points\nPlayer2 wins with 40 points\nPlayer3 wins with 85 points\nPlayer5 wins with 45 points\nPlayer7 wins with 10 points\nPlayer6 wins with 80 points\nPlayer4 wins with 20 points\nPlayer9 wins with 90 points\nPlayer8 wins with 70 points\nPlayer11 wins with 120 points\nPlayer10 wins with 15 points\n text_file.write(\"\\n\") text_file.write(name)\ntext_file.write (\" wins with \")\ntext_file.write (score)\ntext_file.write (\" points\")\ntext_file.write(\"\\n\")\n text_file = open('CH30.txt.', 'r')\nLines = text_file.readlines()\nPlayersScores = []\n\n# read each line get the player name and points \nfor line in Lines:\n # split the line into list of strings\n line = line.split(\" \")\n # removing \\n from last element\n line[-1] = line[-1].replace(\"\\n\", \"\")\n print(line)\n # find player name position\n playerName = line.index(\"wins\") - 1\n # find points position\n points = line.index(\"points\") - 1\n # add the tuple (playerName, points) in a list\n PlayersScores.append((line[playerName], line[points]))\n# descending order sort by player score\nPlayersScores = sorted(PlayersScores, key=lambda t: t[1], reverse=True)\n\n# get the first 5 players\nprint(\"Highest Scores:\\n\")\nfor i in range(5):\n print(str(i+1) + \". \" + PlayersScores[i][0] + \" \" + PlayersScores[i][1] + \" points\")\n Highest Scores:\n\n1. Player11 120 points\n2. Player9 90 points\n3. Player3 85 points\n4. Player6 80 points\n5. Player8 70 points\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20586193/"
] |
74,584,824
|
<p>I am trying to load a '|' delimited file, but it fails because some columns have crlf values.</p>
<p>I converted the text files to xlsx and imported them successfully using SQL Developer.</p>
<p>I noticed that SQL Developer using a Line Terminator option set to "standard: CR LF, CR or LF".</p>
<p>I suspect that I need to set that in my ctl file, but have been unable to find the correct syntax.</p>
<p>Any assistance would be appreciated.</p>
<p>Here is a screenshot from SQL Developer:</p>
<p><a href="https://i.stack.imgur.com/XoqkM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XoqkM.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74585517,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> create table test\n 2 (id number,\n 3 description varchar2(50));\n\nTable created.\n load data\ninfile *\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sat Nov 26 21:51:53 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n infile load data\ninfile * \"STR X'220D0A'\"\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 12:34:04 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n load data\ninfile * \"STR X'220D0A'\"\nreplace\ninto table test\n<snip>\nbegindata \n<snip>\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\n<snip>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'220D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n test11.txt |1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n <snip>\nCommit point reached - logical record count 1\n\nTable TEST:\n 1 Row successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n\nSQL>\n SQL> $type test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 15:30:39 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nControl File: test11.ctl\nData File: c:\\temp\\test11.txt\n File processing option string: \"STR X'220D0A'\"\n Bad File: test11.bad\n Discard File: none specified\n\n (Allow all discards)\n\nNumber to load: ALL\nNumber to skip: 0\nErrors allowed: 50\nBind array: 250 rows, maximum of 1048576 bytes\nContinuation: none specified\nPath used: Conventional\n\nTable TEST, loaded from every logical record.\nInsert option in effect for this table: REPLACE\nTRAILING NULLCOLS option in effect\n\n Column Name Position Len Term Encl Datatype\n------------------------------ ---------- ----- ---- ---- ---------------------\nDUMMY FIRST * | CHARACTER\n (FILLER FIELD)\nID NEXT * | CHARACTER\nDESCRIPTION NEXT * | CHARACTER\n\n\nTable TEST:\n 1 Row successfully loaded.\n 0 Rows not loaded due to data errors.\n 0 Rows not loaded because all WHEN clauses were failed.\n 0 Rows not loaded because all fields were null.\n\n\nSpace allocated for bind array: 129000 bytes(250 rows)\nRead buffer bytes: 1048576\n\nTotal logical records skipped: 0\nTotal logical records read: 1\nTotal logical records rejected: 0\nTotal logical records discarded: 0\n\nRun began on Sun Nov 27 15:30:39 2022\nRun ended on Sun Nov 27 15:30:39 2022\n\nElapsed time was: 00:00:00.17\nCPU time was: 00:00:00.11\n\nSQL>\n SQL> $type test11.bad\nThe system cannot find the file specified.\n\nSQL> $del test11.dsc\nCould Not Find c:\\temp\\test11.dsc\n\nSQL>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'7C0D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n |1|this is some text \nwith no meaning \nat all|\n|2|some \nmore text|\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 17:11:21 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * From test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n 2 some\n more text\n\n\nSQL>\n"
},
{
"answer_id": 74585851,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "INFILE 'target.dat' \"STR X'220D0A'\"\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5606717/"
] |
74,584,836
|
<p>the goal is to increase the dictionary key by 1 so all values generated by for loop are stored in a dictionary</p>
<p>code</p>
<pre><code>counting = {}
numbers = 1
for i in range(1, 11):
counting[numbers] = (i)
numbers + 1
print(counting)
</code></pre>
<p>but in the final result the dictionary only has one key and one stored value that is</p>
<p>result of running the code
{1: 10}</p>
<p>how do i make it that the keys changes with each loop and stores all the values generated</p>
<p>but in the final result the dictionary only has one key and one stored value that is</p>
<p>result of running the code
{1: 10}</p>
<p>how do i make it that the keys changes with each loop and stores all the values generated</p>
|
[
{
"answer_id": 74585517,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> create table test\n 2 (id number,\n 3 description varchar2(50));\n\nTable created.\n load data\ninfile *\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sat Nov 26 21:51:53 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n infile load data\ninfile * \"STR X'220D0A'\"\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 12:34:04 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n load data\ninfile * \"STR X'220D0A'\"\nreplace\ninto table test\n<snip>\nbegindata \n<snip>\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\n<snip>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'220D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n test11.txt |1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n <snip>\nCommit point reached - logical record count 1\n\nTable TEST:\n 1 Row successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n\nSQL>\n SQL> $type test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 15:30:39 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nControl File: test11.ctl\nData File: c:\\temp\\test11.txt\n File processing option string: \"STR X'220D0A'\"\n Bad File: test11.bad\n Discard File: none specified\n\n (Allow all discards)\n\nNumber to load: ALL\nNumber to skip: 0\nErrors allowed: 50\nBind array: 250 rows, maximum of 1048576 bytes\nContinuation: none specified\nPath used: Conventional\n\nTable TEST, loaded from every logical record.\nInsert option in effect for this table: REPLACE\nTRAILING NULLCOLS option in effect\n\n Column Name Position Len Term Encl Datatype\n------------------------------ ---------- ----- ---- ---- ---------------------\nDUMMY FIRST * | CHARACTER\n (FILLER FIELD)\nID NEXT * | CHARACTER\nDESCRIPTION NEXT * | CHARACTER\n\n\nTable TEST:\n 1 Row successfully loaded.\n 0 Rows not loaded due to data errors.\n 0 Rows not loaded because all WHEN clauses were failed.\n 0 Rows not loaded because all fields were null.\n\n\nSpace allocated for bind array: 129000 bytes(250 rows)\nRead buffer bytes: 1048576\n\nTotal logical records skipped: 0\nTotal logical records read: 1\nTotal logical records rejected: 0\nTotal logical records discarded: 0\n\nRun began on Sun Nov 27 15:30:39 2022\nRun ended on Sun Nov 27 15:30:39 2022\n\nElapsed time was: 00:00:00.17\nCPU time was: 00:00:00.11\n\nSQL>\n SQL> $type test11.bad\nThe system cannot find the file specified.\n\nSQL> $del test11.dsc\nCould Not Find c:\\temp\\test11.dsc\n\nSQL>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'7C0D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n |1|this is some text \nwith no meaning \nat all|\n|2|some \nmore text|\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 17:11:21 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * From test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n 2 some\n more text\n\n\nSQL>\n"
},
{
"answer_id": 74585851,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "INFILE 'target.dat' \"STR X'220D0A'\"\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14811053/"
] |
74,584,840
|
<p>I have a function inside a class method that is unread when being called into a forEach loop.</p>
<pre><code>class Mazefinder {
constructor() {
}
// class method
Graph() {
// This is an arrayList of Objects
this.vertices = this.mazeArray;
// function I want to use in my forEach loop
function setKey(key) {
let setKeyStack = [key];
return setKeyStack;
}
// forEach Loop
this.vertices.forEach((e) => {
if (e === s) {
const keyToAdd = this.nodeIDS + this.nodeIdCount.toString();
e.setKey()// function setKey cannot be read inside the forEach loop
}
})
}
}
</code></pre>
<p>I tried attaching it to a this key word</p>
<pre><code>this.setKey = setKey
</code></pre>
<p>but you cannot use the this keyword to attach variables to functions</p>
<p>ex: e.this.setKey(something)// not possible</p>
|
[
{
"answer_id": 74585517,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> create table test\n 2 (id number,\n 3 description varchar2(50));\n\nTable created.\n load data\ninfile *\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sat Nov 26 21:51:53 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n infile load data\ninfile * \"STR X'220D0A'\"\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 12:34:04 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n load data\ninfile * \"STR X'220D0A'\"\nreplace\ninto table test\n<snip>\nbegindata \n<snip>\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\n<snip>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'220D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n test11.txt |1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n <snip>\nCommit point reached - logical record count 1\n\nTable TEST:\n 1 Row successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n\nSQL>\n SQL> $type test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 15:30:39 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nControl File: test11.ctl\nData File: c:\\temp\\test11.txt\n File processing option string: \"STR X'220D0A'\"\n Bad File: test11.bad\n Discard File: none specified\n\n (Allow all discards)\n\nNumber to load: ALL\nNumber to skip: 0\nErrors allowed: 50\nBind array: 250 rows, maximum of 1048576 bytes\nContinuation: none specified\nPath used: Conventional\n\nTable TEST, loaded from every logical record.\nInsert option in effect for this table: REPLACE\nTRAILING NULLCOLS option in effect\n\n Column Name Position Len Term Encl Datatype\n------------------------------ ---------- ----- ---- ---- ---------------------\nDUMMY FIRST * | CHARACTER\n (FILLER FIELD)\nID NEXT * | CHARACTER\nDESCRIPTION NEXT * | CHARACTER\n\n\nTable TEST:\n 1 Row successfully loaded.\n 0 Rows not loaded due to data errors.\n 0 Rows not loaded because all WHEN clauses were failed.\n 0 Rows not loaded because all fields were null.\n\n\nSpace allocated for bind array: 129000 bytes(250 rows)\nRead buffer bytes: 1048576\n\nTotal logical records skipped: 0\nTotal logical records read: 1\nTotal logical records rejected: 0\nTotal logical records discarded: 0\n\nRun began on Sun Nov 27 15:30:39 2022\nRun ended on Sun Nov 27 15:30:39 2022\n\nElapsed time was: 00:00:00.17\nCPU time was: 00:00:00.11\n\nSQL>\n SQL> $type test11.bad\nThe system cannot find the file specified.\n\nSQL> $del test11.dsc\nCould Not Find c:\\temp\\test11.dsc\n\nSQL>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'7C0D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n |1|this is some text \nwith no meaning \nat all|\n|2|some \nmore text|\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 17:11:21 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * From test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n 2 some\n more text\n\n\nSQL>\n"
},
{
"answer_id": 74585851,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "INFILE 'target.dat' \"STR X'220D0A'\"\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19756134/"
] |
74,584,876
|
<p>I am a beginner in R, and I need to learn how to perform code. As you can see in my data frame, I want to check whether the egg in column commodity has the same unit in all rows.</p>
<p>data frame:</p>
<pre><code>df <- structure(list(commodity = c("eggs", "lentils (green)", "oil (vegetable)",
"rice", "sugar (white)", "eggs", "lentils (green)", "oil (vegetable)",
"rice", "sugar (white)", "eggs"), unit = c("1.8 kg", "900 g",
"810 g", "kg", "kg", "1.8 kg", "900 g", "810 g", "kg", "kg",
"1.8 kg")), class = "data.frame", row.names = c(NA, -11L))
commodity unit
1 eggs 1.8 kg
2 lentils (green) 900 g
3 oil (vegetable) 810 g
4 rice kg
5 sugar (white) kg
6 eggs 1.8 kg
7 lentils (green) 900 g
8 oil (vegetable) 810 g
9 rice kg
10 sugar (white) kg
11 eggs 1.8 kg
</code></pre>
<p>I do not know what I should do</p>
|
[
{
"answer_id": 74585517,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> create table test\n 2 (id number,\n 3 description varchar2(50));\n\nTable created.\n load data\ninfile *\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sat Nov 26 21:51:53 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n infile load data\ninfile * \"STR X'220D0A'\"\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 12:34:04 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n load data\ninfile * \"STR X'220D0A'\"\nreplace\ninto table test\n<snip>\nbegindata \n<snip>\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\n<snip>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'220D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n test11.txt |1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n <snip>\nCommit point reached - logical record count 1\n\nTable TEST:\n 1 Row successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n\nSQL>\n SQL> $type test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 15:30:39 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nControl File: test11.ctl\nData File: c:\\temp\\test11.txt\n File processing option string: \"STR X'220D0A'\"\n Bad File: test11.bad\n Discard File: none specified\n\n (Allow all discards)\n\nNumber to load: ALL\nNumber to skip: 0\nErrors allowed: 50\nBind array: 250 rows, maximum of 1048576 bytes\nContinuation: none specified\nPath used: Conventional\n\nTable TEST, loaded from every logical record.\nInsert option in effect for this table: REPLACE\nTRAILING NULLCOLS option in effect\n\n Column Name Position Len Term Encl Datatype\n------------------------------ ---------- ----- ---- ---- ---------------------\nDUMMY FIRST * | CHARACTER\n (FILLER FIELD)\nID NEXT * | CHARACTER\nDESCRIPTION NEXT * | CHARACTER\n\n\nTable TEST:\n 1 Row successfully loaded.\n 0 Rows not loaded due to data errors.\n 0 Rows not loaded because all WHEN clauses were failed.\n 0 Rows not loaded because all fields were null.\n\n\nSpace allocated for bind array: 129000 bytes(250 rows)\nRead buffer bytes: 1048576\n\nTotal logical records skipped: 0\nTotal logical records read: 1\nTotal logical records rejected: 0\nTotal logical records discarded: 0\n\nRun began on Sun Nov 27 15:30:39 2022\nRun ended on Sun Nov 27 15:30:39 2022\n\nElapsed time was: 00:00:00.17\nCPU time was: 00:00:00.11\n\nSQL>\n SQL> $type test11.bad\nThe system cannot find the file specified.\n\nSQL> $del test11.dsc\nCould Not Find c:\\temp\\test11.dsc\n\nSQL>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'7C0D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n |1|this is some text \nwith no meaning \nat all|\n|2|some \nmore text|\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 17:11:21 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * From test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n 2 some\n more text\n\n\nSQL>\n"
},
{
"answer_id": 74585851,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "INFILE 'target.dat' \"STR X'220D0A'\"\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20608930/"
] |
74,584,885
|
<p>When I try to update Windows features; When I update UseShellExecute to "true"; "The Process object must have the UseShellExecute property set to false in order to redirect IO streams." I get an error. When I set it to False; Unable to update. How can I do it ? Do you have any other suggestions?</p>
<pre><code> static void InstallIISSetupFeature()
{
var featureNames = new List<string>() {
"IIS-WebServerRole",
"IIS-WebServer",
"IIS-CommonHttpFeatures",
"IIS-HttpErrors",
"IIS-HttpRedirect",
"IIS-ApplicationDevelopment",
"IIS-Security",
"IIS-RequestFiltering",
"IIS-NetFxExtensibility",
"IIS-NetFxExtensibility45",
"IIS-HealthAndDiagnostics",
"IIS-HttpLogging",
"IIS-LoggingLibraries",
"IIS-RequestMonitor",
"IIS-HttpTracing",
"IIS-URLAuthorization",
"IIS-IPSecurity",
"IIS-Performance",
"IIS-HttpCompressionDynamic",
"IIS-WebServerManagementTools",
"IIS-ManagementScriptingTools",
"IIS-IIS6ManagementCompatibility",
"IIS-Metabase",
"IIS-HostableWebCore","IIS-StaticContent",
"IIS-DefaultDocument",
"IIS-DirectoryBrowsing",
"IIS-WebDAV",
"IIS-WebSockets",
"IIS-ApplicationInit",
"IIS-ASPNET",
"IIS-ASPNET45",
"IIS-ASP",
"IIS-CGI",
"IIS-ISAPIExtensions",
"IIS-ISAPIFilter",
"IIS-ServerSideIncludes",
"IIS-CustomLogging",
"IIS-BasicAuthentication",
"IIS-HttpCompressionStatic",
"IIS-ManagementConsole",
"IIS-ManagementService",
"IIS-WMICompatibility",
"IIS-LegacyScripts",
"IIS-LegacySnapIn",
"IIS-FTPServer",
"IIS-FTPSvc",
"IIS-FTPExtensibility",
"IIS-CertProvider",
"IIS-WindowsAuthentication",
"IIS-DigestAuthentication",
"IIS-ClientCertificateMappingAuthentication",
"IIS-IISCertificateMappingAuthentication",
"IIS-ODBCLogging",
"NetFx4-AdvSrvs",
"NetFx4Extended-ASPNET45",
"NetFx3",
"WAS-WindowsActivationService",
"WCF-HTTP-Activation",
"WCF-HTTP-Activation45",
"WCF-MSMQ-Activation45",
"WCF-NonHTTP-Activation",
"WCF-Pipe-Activation45",
"WCF-TCP-Activation45",
"WCF-TCP-PortSharing45",
"WCF-Services45",
};
ManagementObjectSearcher obj = new ManagementObjectSearcher("select * from Win32_OperatingSystem");
foreach (ManagementObject wmi in obj.Get())
{
string Name = wmi.GetPropertyValue("Caption").ToString();
Name = Regex.Replace(Name.ToString(), "[^A-Za-z0-9 ]", "");
if (Name.Contains("Server 2008 R2") || Name.Contains("Windows 7"))
{
featureNames.Add("IIS-ASPNET");
featureNames.Add("IIS-NetFxExtensibility");
featureNames.Add("WCF-HTTP-Activation");
featureNames.Add("WCF-MSMQ-Activation");
featureNames.Add("WCF-Pipe-Activation");
featureNames.Add("WCF-TCP-Activation");
featureNames.Add("WCF-TCP-Activation");
}
string Version = (string)wmi["Version"];
string Architecture = (string)wmi["OSArchitecture"];
}
foreach (var featureName in featureNames)
{
Run(string.Format("dism/online/Enable-Feature:{0}", featureName));
}
}
static void Run(string arguments)
{
try
{
string systemPath = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32");
var dism = new Process();
dism.StartInfo.WorkingDirectory = systemPath;
dism.StartInfo.Arguments = arguments;
dism.StartInfo.FileName = "dism.exe";
dism.StartInfo.Verb = "runas";
dism.StartInfo.UseShellExecute = true;
dism.StartInfo.RedirectStandardOutput = true;
dism.Start();
var result = dism.StandardOutput.ReadToEnd();
dism.WaitForExit();
}
catch (Exception ex)
{
}
}`
</code></pre>
<p>I tried to update the feature with dism.exe and cmd.exe, when it gave an authorization error, I used the Verb property
`</p>
|
[
{
"answer_id": 74585517,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> create table test\n 2 (id number,\n 3 description varchar2(50));\n\nTable created.\n load data\ninfile *\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sat Nov 26 21:51:53 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n infile load data\ninfile * \"STR X'220D0A'\"\nreplace\ncontinueif next preserve(1:1) != \"|\"\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n\nbegindata\n|1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 12:34:04 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\nPath used: Conventional\nCommit point reached - logical record count 1\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text with no meaning at all\n 2 some more text\n\nSQL>\n load data\ninfile * \"STR X'220D0A'\"\nreplace\ninto table test\n<snip>\nbegindata \n<snip>\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader-283: file processing string \"STR X'220D0A'\" ignored for INFILE *\n<snip>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'220D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n test11.txt |1|this is some text \nwith no meaning \nat all\n|2|some \nmore text\n <snip>\nCommit point reached - logical record count 1\n\nTable TEST:\n 1 Row successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * from test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n\nSQL>\n SQL> $type test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 15:30:39 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nControl File: test11.ctl\nData File: c:\\temp\\test11.txt\n File processing option string: \"STR X'220D0A'\"\n Bad File: test11.bad\n Discard File: none specified\n\n (Allow all discards)\n\nNumber to load: ALL\nNumber to skip: 0\nErrors allowed: 50\nBind array: 250 rows, maximum of 1048576 bytes\nContinuation: none specified\nPath used: Conventional\n\nTable TEST, loaded from every logical record.\nInsert option in effect for this table: REPLACE\nTRAILING NULLCOLS option in effect\n\n Column Name Position Len Term Encl Datatype\n------------------------------ ---------- ----- ---- ---- ---------------------\nDUMMY FIRST * | CHARACTER\n (FILLER FIELD)\nID NEXT * | CHARACTER\nDESCRIPTION NEXT * | CHARACTER\n\n\nTable TEST:\n 1 Row successfully loaded.\n 0 Rows not loaded due to data errors.\n 0 Rows not loaded because all WHEN clauses were failed.\n 0 Rows not loaded because all fields were null.\n\n\nSpace allocated for bind array: 129000 bytes(250 rows)\nRead buffer bytes: 1048576\n\nTotal logical records skipped: 0\nTotal logical records read: 1\nTotal logical records rejected: 0\nTotal logical records discarded: 0\n\nRun began on Sun Nov 27 15:30:39 2022\nRun ended on Sun Nov 27 15:30:39 2022\n\nElapsed time was: 00:00:00.17\nCPU time was: 00:00:00.11\n\nSQL>\n SQL> $type test11.bad\nThe system cannot find the file specified.\n\nSQL> $del test11.dsc\nCould Not Find c:\\temp\\test11.dsc\n\nSQL>\n load data\ninfile \"c:\\temp\\test11.txt\" \"STR X'7C0D0A'\"\nreplace\ninto table test\nfields terminated by '|'\ntrailing nullcols\n\n(\n dummy filler,\n id,\n description \n)\n |1|this is some text \nwith no meaning \nat all|\n|2|some \nmore text|\n SQL> $sqlldr scott/tiger@pdb1 control=test11.ctl log=test11.log\n\nSQL*Loader: Release 21.0.0.0.0 - Production on Sun Nov 27 17:11:21 2022\nVersion 21.3.0.0.0\n\nCopyright (c) 1982, 2021, Oracle and/or its affiliates. All rights reserved.\n\nPath used: Conventional\nCommit point reached - logical record count 2\n\nTable TEST:\n 2 Rows successfully loaded.\n\nCheck the log file:\n test11.log\nfor more information about the load.\n SQL> select * From test;\n\n ID DESCRIPTION\n---------- --------------------------------------------------\n 1 this is some text\n with no meaning\n at all\n\n 2 some\n more text\n\n\nSQL>\n"
},
{
"answer_id": 74585851,
"author": "p3consulting",
"author_id": 4956336,
"author_profile": "https://Stackoverflow.com/users/4956336",
"pm_score": 0,
"selected": false,
"text": "INFILE 'target.dat' \"STR X'220D0A'\"\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19299143/"
] |
74,584,886
|
<p>I am trying to do something like the following in NumPy:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def f(x):
return x[0] + x[1]
X1 = np.array([0, 1, 2])
X2 = np.array([0, 1, 2])
X = np.meshgrid(X1, X2)
result = np.vectorize(f)(X)
</code></pre>
<p>with the expected result being <code>array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])</code>, but it returns the following error:</p>
<pre><code> 2
3 def f(x):
----> 4 return x[0] + x[1]
5
6 X1 = np.array([0, 1, 2])
IndexError: invalid index to scalar variable
</code></pre>
<p>This is because it tries to apply <code>f</code> to all 18 scalar elements of the mesh grid, whereas I want it applied to 9 pairs of 2 scalars. What is the correct way to do this?</p>
<p><strong>Note:</strong> I am aware this code will work if I do not vectorize <code>f</code>, but this is important because <code>f</code> can be any function, e.g. it could contain an if statement which throws value error without vectorizing.</p>
|
[
{
"answer_id": 74584985,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 1,
"selected": false,
"text": "numpy.vectorize signature import numpy as np\n\ndef f(x):\n return x[0] + x[1]\n # Or\n # return np.add.reduce(x, axis=0)\n\n\nX1 = np.array([0, 1, 2])\nX2 = np.array([0, 1, 2])\nX = np.meshgrid(X1, X2)\n\n# np.asarray(X).shape -> (2, 3, 3)\n# shape of the desired result is (3, 3)\n\nf_vec = np.vectorize(f, signature='(n,m,m)->(m,m)')\nresult = f_vec(X)\nprint(result)\n [[0 1 2]\n [1 2 3]\n [2 3 4]]\n"
},
{
"answer_id": 74585037,
"author": "ddejohn",
"author_id": 6298712,
"author_profile": "https://Stackoverflow.com/users/6298712",
"pm_score": 0,
"selected": false,
"text": "f = lambda x: x[0] + x[1] if x[0] > 0 else 0\n np.where def f(x):\n return np.where(x > 0, x[0] + x[1], 0)\n # np.where(some_condition, value_if_true, value_if_false)\n for"
},
{
"answer_id": 74585399,
"author": "hpaulj",
"author_id": 901925,
"author_profile": "https://Stackoverflow.com/users/901925",
"pm_score": 0,
"selected": false,
"text": "np.vectorize In [91]: def foo(x,y): return x+y\n ...: f = np.vectorize(foo)\n In [92]: f(1,2)\nOut[92]: array(3)\n In [93]: f(np.array([1,2])[:,None], np.arange(1,4))\nOut[93]: \narray([[2, 3, 4],\n [3, 4, 5]])\n meshgrid In [94]: I,J = np.meshgrid(np.array([1,2]), np.arange(1,4),indexing='ij')\n\nIn [95]: I\nOut[95]: \narray([[1, 1, 1],\n [2, 2, 2]])\n\nIn [96]: J\nOut[96]: \narray([[1, 2, 3],\n [1, 2, 3]])\n\nIn [97]: f(I,J)\nOut[97]: \narray([[2, 3, 4],\n [3, 4, 5]])\n In [98]: I,J = np.meshgrid(np.array([1,2]), np.arange(1,4),indexing='ij', sparse=True)\n\nIn [99]: I,J\nOut[99]: \n(array([[1],\n [2]]),\n array([[1, 2, 3]]))\n In [100]: I+J\nOut[100]: \narray([[2, 3, 4],\n [3, 4, 5]])\n np.vectorize pyfunc vectorize In [103]: def foo1(x): return x[0]+x[1]\n ...: def foo2(x,y): return foo1((x,y))\n ...: f = np.vectorize(foo2)\n\nIn [104]: f(1,2)\nOut[104]: array(3)\n X In [105]: X = np.meshgrid(np.array([1,2]), np.arange(1,4),indexing='ij')\n\nIn [106]: X\nOut[106]: \n[array([[1, 1, 1],\n [2, 2, 2]]),\n array([[1, 2, 3],\n [1, 2, 3]])]\n f In [107]: f(X[0],X[1])\nOut[107]: \narray([[2, 3, 4],\n [3, 4, 5]])\n foo1 In [108]: foo1(X)\nOut[108]: \narray([[2, 3, 4],\n [3, 4, 5]])\n f = lambda x: x[0] + x[1] if x[0] > 0 else 0 if if"
},
{
"answer_id": 74652239,
"author": "mdnestor",
"author_id": 10425289,
"author_profile": "https://Stackoverflow.com/users/10425289",
"pm_score": 1,
"selected": true,
"text": "np.apply_along_axis import numpy as np\n\ndef f(x):\n return x[0] + x[1]\n\nX1 = np.array([0, 1, 2])\nX2 = np.array([0, 1, 2])\nX = np.meshgrid(X1, X2)\n\nresult = np.apply_along_axis(f, 0, X)\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10425289/"
] |
74,584,889
|
<p>I will try to explain this as good as possible, because I am unfortunately quiet new to polars. I have a large time series dataset where each separate timeseries is identified with a <code>group_id</code>. Additionally, there is a <code>time_idx</code> column that identifies which of the possible time series step is present and have a corresponding target value if present. As a minimal example, consider the following:</p>
<pre><code>min_df = pl.DataFrame(
{"grop_idx": [0, 1, 2, 3], "time_idx": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]}
)
┌──────────┬───────────────┐
│ grop_idx ┆ time_idx │
│ --- ┆ --- │
│ i64 ┆ list[i64] │
╞══════════╪═══════════════╡
│ 0 ┆ [0, 1, 2, 3] │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ [2, 3] │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ [0, 2, 3] │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ [0, 3] │
└──────────┴───────────────┘
</code></pre>
<p>Here, the time range in the dataset is 4 steps long, but not for all individual series all time steps are present. So while <code>group_idx=0</code> has all present steps, <code>group_idx=0</code> only has step 0 and 3, meaning that for step 1 and 2 no recorded target value is present.</p>
<p>Now, I would like to obtain all possible sub sequences so that we start from each possible time step for a given sequence length and maximally go to the <code>max_time_step</code> (in this case 3). For example, for <code>sequence_length=3</code>, the expected output would be:</p>
<pre><code>result_df = pl.DataFrame(
{
"group_idx": [0, 0, 1, 1, 2, 2, 3, 3],
"time_idx": [[0, 1, 2, 3], [0, 1, 2, 3], [2, 3], [2, 3], [0,2,3], [0,2,3], [0,3], [0,3]],
"sub_sequence": [[0,1,2], [1,2,3], [None, None, 2], [None, 2, 3], [0, None, 2], [None, 2, 3], [0, None, None], [None, None, 3]]
}
)
┌───────────┬───────────────┬─────────────────┐
│ group_idx ┆ time_idx ┆ sub_sequence │
│ --- ┆ --- ┆ --- │
│ i64 ┆ list[i64] ┆ list[i64] │
╞═══════════╪═══════════════╪═════════════════╡
│ 0 ┆ [0, 1, ... 3] ┆ [0, 1, 2] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 0 ┆ [0, 1, ... 3] ┆ [1, 2, 3] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ [2, 3] ┆ [null, null, 2] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ [2, 3] ┆ [null, 2, 3] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ [0, 2, 3] ┆ [0, null, 2] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ [0, 2, 3] ┆ [null, 2, 3] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ [0, 3] ┆ [0, null, null] │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ [0, 3] ┆ [null, null, 3] │
└───────────┴───────────────┴─────────────────┘
</code></pre>
<p>All of this should be computed within <code>polars</code>, because the real dataset is much larger both in terms of the number of time series and time series length.</p>
<p><strong>Edit</strong>:
Based on the suggestion by @ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ I have tried the following on the actual dataset (~200 million rows after <code>.explode()</code>). I forgot to say that we can assume that that <code>group_idx</code>and <code>time_idx</code> are already sorted. However, this gets killed.</p>
<pre><code>(
min_df.lazy()
.with_column(
pl.col("time_idx").alias("time_idx_nulls")
)
.groupby_rolling(
index_column='time_idx',
by='group_idx',
period=str(max_sequence_length) + 'i',
)
.agg(pl.col("time_idx_nulls"))
.filter(pl.col('time_idx_nulls').arr.lengths() == max_sequence_length)
)
</code></pre>
|
[
{
"answer_id": 74586627,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 1,
"selected": false,
"text": ">>> max_time_step = 3\n>>> sequence_length = 3\n>>> (\n... min_df\n... .with_columns([\n... pl.arange(0, max_time_step + 1).list().alias(\"range\"),\n... pl.col(\"time_idx\").arr.eval(\n... pl.arange(0, max_time_step + 1).is_in(pl.element()),\n... parallel=True\n... ).alias(\"mask\")\n... ])\n... )\nshape: (4, 4)\n┌───────────┬───────────────┬───────────────┬──────────────────────────┐\n│ group_idx | time_idx | range | mask │\n│ --- | --- | --- | --- │\n│ i64 | list[i64] | list[i64] | list[bool] │\n╞═══════════╪═══════════════╪═══════════════╪══════════════════════════╡\n│ 0 | [0, 1, ... 3] | [0, 1, ... 3] | [true, true, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 1 | [2, 3] | [0, 1, ... 3] | [false, false, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 2 | [0, 2, 3] | [0, 1, ... 3] | [true, false, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 3 | [0, 3] | [0, 1, ... 3] | [true, false, ... true] │\n└─//────────┴─//────────────┴─//────────────┴─//───────────────────────┘\n .explode() true .groupby_rolling() .groupby() .list().slice() >>> min_df = pl.DataFrame({\n... \"group_idx\": [0, 1, 2, 3], \n... \"time_idx\": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]\n... })\n... max_time_step = 3\n... sequence_length = 2\n... (\n... min_df\n... .with_columns([\n... pl.arange(0, max_time_step + 1).list().alias(\"range\"),\n... pl.col(\"time_idx\").arr.eval(\n... pl.arange(0, max_time_step + 1).is_in(pl.element()),\n... parallel=True\n... ).alias(\"mask\")\n... ])\n... .explode([\"range\", \"mask\"])\n... .with_column(\n... pl.when(pl.col(\"mask\"))\n... .then(pl.col(\"range\"))\n... .alias(\"value\"))\n... .groupby(\"group_idx\", maintain_order=True)\n... .agg([\n... pl.col(\"value\")\n... .list()\n... .slice(length=sequence_length, offset=n)\n... .suffix(f\"{n}\")\n... for n in range(0, max_time_step - (1 if max_time_step % sequence_length == 0 else 0))\n... ])\n... .melt(\"group_idx\", value_name=\"subsequence\")\n... .drop(\"variable\")\n... .sort(\"group_idx\")\n... )\nshape: (12, 2)\n┌───────────┬──────────────┐\n│ group_idx | subsequence │\n│ --- | --- │\n│ i64 | list[i64] │\n╞═══════════╪══════════════╡\n│ 0 | [0, 1] │\n├───────────┼──────────────┤\n│ 0 | [1, 2] │\n├───────────┼──────────────┤\n│ 0 | [2, 3] │\n├───────────┼──────────────┤\n│ 1 | [null, null] │\n├───────────┼──────────────┤\n│ 1 | [null, 2] │\n├───────────┼──────────────┤\n│ ... | ... │\n├───────────┼──────────────┤\n│ 2 | [null, 2] │\n├───────────┼──────────────┤\n│ 2 | [2, 3] │\n├───────────┼──────────────┤\n│ 3 | [0, null] │\n├───────────┼──────────────┤\n│ 3 | [null, null] │\n├───────────┼──────────────┤\n│ 3 | [null, 3] │\n└─//────────┴─//───────────┘\n pl.element() .then() >>> (\n... min_df\n... .with_column(\n... pl.col(\"time_idx\").arr.eval(\n... pl.when(pl.arange(0, max_time_step + 1).is_in(pl.element()))\n... .then(pl.element()),\n... parallel=True)\n... .alias(\"subsequence\")\n... )\n... )\n---------------------------------------------------------------------------\nShapeError Traceback (most recent call last)\n"
},
{
"answer_id": 74586970,
"author": "ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ",
"author_id": 20557510,
"author_profile": "https://Stackoverflow.com/users/20557510",
"pm_score": 3,
"selected": true,
"text": "groupby_rolling period = 3\nmin_df = min_df.explode('time_idx')\n(\n min_df.get_column('group_idx').unique().to_frame()\n .join(\n min_df.get_column('time_idx').unique().to_frame(),\n how='cross'\n )\n .join(\n min_df.with_column(pl.col('time_idx').alias('time_idx_nulls')),\n on=['group_idx', 'time_idx'],\n how='left',\n )\n .groupby_rolling(\n index_column='time_idx',\n by='group_idx',\n period=str(period) + 'i',\n )\n .agg(pl.col(\"time_idx_nulls\"))\n .filter(pl.col('time_idx_nulls').arr.lengths() == period)\n .sort('group_idx')\n)\n shape: (8, 3)\n┌───────────┬──────────┬─────────────────┐\n│ group_idx ┆ time_idx ┆ time_idx_nulls │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ list[i64] │\n╞═══════════╪══════════╪═════════════════╡\n│ 0 ┆ 2 ┆ [0, 1, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 3 ┆ [1, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 2 ┆ [null, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 3 ┆ [null, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 2 ┆ [0, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 3 ┆ [null, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 2 ┆ [0, null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 3 ┆ [null, null, 3] │\n└───────────┴──────────┴─────────────────┘\n shape: (12, 3)\n┌───────────┬──────────┬────────────────┐\n│ group_idx ┆ time_idx ┆ time_idx_nulls │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ list[i64] │\n╞═══════════╪══════════╪════════════════╡\n│ 0 ┆ 1 ┆ [0, 1] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 2 ┆ [1, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 1 ┆ [null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 2 ┆ [null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 1 ┆ [0, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 2 ┆ [null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 1 ┆ [0, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 2 ┆ [null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 3 ┆ [null, 3] │\n└───────────┴──────────┴────────────────┘\n min_time = 0\nmax_time = 1_000\nnbr_groups = 400_000\nmin_df = (\n pl.DataFrame({\"time_idx\": [list(range(min_time, max_time, 2))]})\n .join(\n pl.arange(0, nbr_groups, eager=True).alias(\"group_idx\").to_frame(),\n how=\"cross\"\n )\n)\nmin_df.explode('time_idx')\n shape: (200000000, 2)\n┌──────────┬───────────┐\n│ time_idx ┆ group_idx │\n│ --- ┆ --- │\n│ i64 ┆ i64 │\n╞══════════╪═══════════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 4 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 6 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 992 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 994 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 996 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 998 ┆ 399999 │\n└──────────┴───────────┘\n slice concat slice slice_size time_index_df = (\n pl.arange(min_time, max_time, eager=True, dtype=pl.Int64)\n .alias(\"time_idx\")\n .to_frame()\n .lazy()\n)\n\n\nperiod = 3\nslice_size = 10_000\nresult = pl.concat(\n [\n (\n time_index_df\n .join(\n min_df\n .lazy()\n .slice(next_index, slice_size)\n .select(\"group_idx\"),\n how=\"cross\",\n )\n .join(\n min_df\n .lazy()\n .slice(next_index, slice_size)\n .explode('time_idx')\n .with_column(pl.col(\"time_idx\").alias(\"time_idx_nulls\")),\n on=[\"group_idx\", \"time_idx\"],\n how=\"left\",\n )\n .groupby_rolling(\n index_column='time_idx',\n by='group_idx',\n period=str(period) + 'i',\n )\n .agg(pl.col(\"time_idx_nulls\"))\n .filter(pl.col('time_idx_nulls').arr.lengths() == period)\n .select(['group_idx', 'time_idx_nulls'])\n .collect()\n )\n for next_index in range(0, min_df.height, slice_size)\n ]\n)\n\nresult.sort('group_idx')\n shape: (399200000, 2)\n┌───────────┬───────────────────┐\n│ group_idx ┆ time_idx_nulls │\n│ --- ┆ --- │\n│ i64 ┆ list[i64] │\n╞═══════════╪═══════════════════╡\n│ 0 ┆ [0, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [null, 2, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [2, null, 4] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [null, 4, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [994, null, 996] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [null, 996, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [996, null, 998] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [null, 998, null] │\n└───────────┴───────────────────┘\n null slice"
},
{
"answer_id": 74595020,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 2,
"selected": false,
"text": ".explode(\"subsequence\") .explode() unnest([ ... ] subsequence) explode_table() >>> import duckdb\n... \n... min_df = pl.DataFrame({\n... \"group_idx\": [0, 1, 2, 3], \n... \"time_idx\": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]\n... })\n... max_time_step = 3\n... sequence_length = 2\n... upper_bound = (\n... max_time_step - (\n... 1 if max_time_step % sequence_length == 0 else 0\n... )\n... )\n... tbl = min_df.to_arrow()\n... pl.from_arrow(\n... duckdb.connect().execute(f\"\"\"\n... select \n... group_idx, [ \n... time_idx_nulls[n: n + {sequence_length - 1}] \n... for n in range(1, {upper_bound + 1})\n... ] subsequence\n... from (\n... from tbl select group_idx, list_transform(\n... range(0, {max_time_step + 1}),\n... n -> case when list_has(time_idx, n) then n end\n... ) time_idx_nulls\n... )\n... \"\"\")\n... .arrow()\n... )\nshape: (4, 2)\n┌───────────┬─────────────────────────────────────┐\n│ group_idx | subsequence │\n│ --- | --- │\n│ i64 | list[list[i64]] │\n╞═══════════╪═════════════════════════════════════╡\n│ 0 | [[0, 1], [1, 2], [2, 3]] │\n├───────────┼─────────────────────────────────────┤\n│ 1 | [[null, null], [null, 2], [2, 3]... │\n├───────────┼─────────────────────────────────────┤\n│ 2 | [[0, null], [null, 2], [2, 3]] │\n├───────────┼─────────────────────────────────────┤\n│ 3 | [[0, null], [null, null], [null,... │\n└─//────────┴─//──────────────────────────────────┘\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386797/"
] |
74,584,917
|
<p>I'm trying been more simlicity but i still learn the power of custom hook.
i'm trully not understand whats wrong with my hook.</p>
<pre><code>const UseMessage = (msg: string, delay: number, cb?: () => void): [setCB: () => void] => {
const [message, setMessage] = useState("");
const setCB = () => {
setMessage(() => msg);
setTimeout(() => {
setMessage(() => msg);
if (typeof cb === "function") {
cb();
}
}, delay);
};
return [setCB];
};
export default UseMessage;
</code></pre>
<p>i'm getting error :Error: Invalid hook call. Hooks can only be called inside of the body of a function component.</p>
|
[
{
"answer_id": 74586627,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 1,
"selected": false,
"text": ">>> max_time_step = 3\n>>> sequence_length = 3\n>>> (\n... min_df\n... .with_columns([\n... pl.arange(0, max_time_step + 1).list().alias(\"range\"),\n... pl.col(\"time_idx\").arr.eval(\n... pl.arange(0, max_time_step + 1).is_in(pl.element()),\n... parallel=True\n... ).alias(\"mask\")\n... ])\n... )\nshape: (4, 4)\n┌───────────┬───────────────┬───────────────┬──────────────────────────┐\n│ group_idx | time_idx | range | mask │\n│ --- | --- | --- | --- │\n│ i64 | list[i64] | list[i64] | list[bool] │\n╞═══════════╪═══════════════╪═══════════════╪══════════════════════════╡\n│ 0 | [0, 1, ... 3] | [0, 1, ... 3] | [true, true, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 1 | [2, 3] | [0, 1, ... 3] | [false, false, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 2 | [0, 2, 3] | [0, 1, ... 3] | [true, false, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 3 | [0, 3] | [0, 1, ... 3] | [true, false, ... true] │\n└─//────────┴─//────────────┴─//────────────┴─//───────────────────────┘\n .explode() true .groupby_rolling() .groupby() .list().slice() >>> min_df = pl.DataFrame({\n... \"group_idx\": [0, 1, 2, 3], \n... \"time_idx\": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]\n... })\n... max_time_step = 3\n... sequence_length = 2\n... (\n... min_df\n... .with_columns([\n... pl.arange(0, max_time_step + 1).list().alias(\"range\"),\n... pl.col(\"time_idx\").arr.eval(\n... pl.arange(0, max_time_step + 1).is_in(pl.element()),\n... parallel=True\n... ).alias(\"mask\")\n... ])\n... .explode([\"range\", \"mask\"])\n... .with_column(\n... pl.when(pl.col(\"mask\"))\n... .then(pl.col(\"range\"))\n... .alias(\"value\"))\n... .groupby(\"group_idx\", maintain_order=True)\n... .agg([\n... pl.col(\"value\")\n... .list()\n... .slice(length=sequence_length, offset=n)\n... .suffix(f\"{n}\")\n... for n in range(0, max_time_step - (1 if max_time_step % sequence_length == 0 else 0))\n... ])\n... .melt(\"group_idx\", value_name=\"subsequence\")\n... .drop(\"variable\")\n... .sort(\"group_idx\")\n... )\nshape: (12, 2)\n┌───────────┬──────────────┐\n│ group_idx | subsequence │\n│ --- | --- │\n│ i64 | list[i64] │\n╞═══════════╪══════════════╡\n│ 0 | [0, 1] │\n├───────────┼──────────────┤\n│ 0 | [1, 2] │\n├───────────┼──────────────┤\n│ 0 | [2, 3] │\n├───────────┼──────────────┤\n│ 1 | [null, null] │\n├───────────┼──────────────┤\n│ 1 | [null, 2] │\n├───────────┼──────────────┤\n│ ... | ... │\n├───────────┼──────────────┤\n│ 2 | [null, 2] │\n├───────────┼──────────────┤\n│ 2 | [2, 3] │\n├───────────┼──────────────┤\n│ 3 | [0, null] │\n├───────────┼──────────────┤\n│ 3 | [null, null] │\n├───────────┼──────────────┤\n│ 3 | [null, 3] │\n└─//────────┴─//───────────┘\n pl.element() .then() >>> (\n... min_df\n... .with_column(\n... pl.col(\"time_idx\").arr.eval(\n... pl.when(pl.arange(0, max_time_step + 1).is_in(pl.element()))\n... .then(pl.element()),\n... parallel=True)\n... .alias(\"subsequence\")\n... )\n... )\n---------------------------------------------------------------------------\nShapeError Traceback (most recent call last)\n"
},
{
"answer_id": 74586970,
"author": "ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ",
"author_id": 20557510,
"author_profile": "https://Stackoverflow.com/users/20557510",
"pm_score": 3,
"selected": true,
"text": "groupby_rolling period = 3\nmin_df = min_df.explode('time_idx')\n(\n min_df.get_column('group_idx').unique().to_frame()\n .join(\n min_df.get_column('time_idx').unique().to_frame(),\n how='cross'\n )\n .join(\n min_df.with_column(pl.col('time_idx').alias('time_idx_nulls')),\n on=['group_idx', 'time_idx'],\n how='left',\n )\n .groupby_rolling(\n index_column='time_idx',\n by='group_idx',\n period=str(period) + 'i',\n )\n .agg(pl.col(\"time_idx_nulls\"))\n .filter(pl.col('time_idx_nulls').arr.lengths() == period)\n .sort('group_idx')\n)\n shape: (8, 3)\n┌───────────┬──────────┬─────────────────┐\n│ group_idx ┆ time_idx ┆ time_idx_nulls │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ list[i64] │\n╞═══════════╪══════════╪═════════════════╡\n│ 0 ┆ 2 ┆ [0, 1, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 3 ┆ [1, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 2 ┆ [null, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 3 ┆ [null, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 2 ┆ [0, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 3 ┆ [null, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 2 ┆ [0, null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 3 ┆ [null, null, 3] │\n└───────────┴──────────┴─────────────────┘\n shape: (12, 3)\n┌───────────┬──────────┬────────────────┐\n│ group_idx ┆ time_idx ┆ time_idx_nulls │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ list[i64] │\n╞═══════════╪══════════╪════════════════╡\n│ 0 ┆ 1 ┆ [0, 1] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 2 ┆ [1, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 1 ┆ [null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 2 ┆ [null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 1 ┆ [0, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 2 ┆ [null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 1 ┆ [0, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 2 ┆ [null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 3 ┆ [null, 3] │\n└───────────┴──────────┴────────────────┘\n min_time = 0\nmax_time = 1_000\nnbr_groups = 400_000\nmin_df = (\n pl.DataFrame({\"time_idx\": [list(range(min_time, max_time, 2))]})\n .join(\n pl.arange(0, nbr_groups, eager=True).alias(\"group_idx\").to_frame(),\n how=\"cross\"\n )\n)\nmin_df.explode('time_idx')\n shape: (200000000, 2)\n┌──────────┬───────────┐\n│ time_idx ┆ group_idx │\n│ --- ┆ --- │\n│ i64 ┆ i64 │\n╞══════════╪═══════════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 4 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 6 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 992 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 994 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 996 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 998 ┆ 399999 │\n└──────────┴───────────┘\n slice concat slice slice_size time_index_df = (\n pl.arange(min_time, max_time, eager=True, dtype=pl.Int64)\n .alias(\"time_idx\")\n .to_frame()\n .lazy()\n)\n\n\nperiod = 3\nslice_size = 10_000\nresult = pl.concat(\n [\n (\n time_index_df\n .join(\n min_df\n .lazy()\n .slice(next_index, slice_size)\n .select(\"group_idx\"),\n how=\"cross\",\n )\n .join(\n min_df\n .lazy()\n .slice(next_index, slice_size)\n .explode('time_idx')\n .with_column(pl.col(\"time_idx\").alias(\"time_idx_nulls\")),\n on=[\"group_idx\", \"time_idx\"],\n how=\"left\",\n )\n .groupby_rolling(\n index_column='time_idx',\n by='group_idx',\n period=str(period) + 'i',\n )\n .agg(pl.col(\"time_idx_nulls\"))\n .filter(pl.col('time_idx_nulls').arr.lengths() == period)\n .select(['group_idx', 'time_idx_nulls'])\n .collect()\n )\n for next_index in range(0, min_df.height, slice_size)\n ]\n)\n\nresult.sort('group_idx')\n shape: (399200000, 2)\n┌───────────┬───────────────────┐\n│ group_idx ┆ time_idx_nulls │\n│ --- ┆ --- │\n│ i64 ┆ list[i64] │\n╞═══════════╪═══════════════════╡\n│ 0 ┆ [0, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [null, 2, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [2, null, 4] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [null, 4, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [994, null, 996] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [null, 996, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [996, null, 998] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [null, 998, null] │\n└───────────┴───────────────────┘\n null slice"
},
{
"answer_id": 74595020,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 2,
"selected": false,
"text": ".explode(\"subsequence\") .explode() unnest([ ... ] subsequence) explode_table() >>> import duckdb\n... \n... min_df = pl.DataFrame({\n... \"group_idx\": [0, 1, 2, 3], \n... \"time_idx\": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]\n... })\n... max_time_step = 3\n... sequence_length = 2\n... upper_bound = (\n... max_time_step - (\n... 1 if max_time_step % sequence_length == 0 else 0\n... )\n... )\n... tbl = min_df.to_arrow()\n... pl.from_arrow(\n... duckdb.connect().execute(f\"\"\"\n... select \n... group_idx, [ \n... time_idx_nulls[n: n + {sequence_length - 1}] \n... for n in range(1, {upper_bound + 1})\n... ] subsequence\n... from (\n... from tbl select group_idx, list_transform(\n... range(0, {max_time_step + 1}),\n... n -> case when list_has(time_idx, n) then n end\n... ) time_idx_nulls\n... )\n... \"\"\")\n... .arrow()\n... )\nshape: (4, 2)\n┌───────────┬─────────────────────────────────────┐\n│ group_idx | subsequence │\n│ --- | --- │\n│ i64 | list[list[i64]] │\n╞═══════════╪═════════════════════════════════════╡\n│ 0 | [[0, 1], [1, 2], [2, 3]] │\n├───────────┼─────────────────────────────────────┤\n│ 1 | [[null, null], [null, 2], [2, 3]... │\n├───────────┼─────────────────────────────────────┤\n│ 2 | [[0, null], [null, 2], [2, 3]] │\n├───────────┼─────────────────────────────────────┤\n│ 3 | [[0, null], [null, null], [null,... │\n└─//────────┴─//──────────────────────────────────┘\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19529973/"
] |
74,584,926
|
<p>When I click on the checkboxes, the filter works, but when I click again, the filter does not work and the checkbox flags also seem to work separately. I want to make that when clicked, when the checkbox was worked, filter this. Booleans need to be created for individual checkboxes?</p>
<pre><code>const App = () => {
const [category, setCategory] = useState(["electronics","jewelery","men's clothing","women's clothing"]);
const [products, setProducts] = useState([
{"id":1,"title":"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops","price":109.95,"category":"electronics", "rating":{"rate":3.9,"count":120}},
{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3, "category":"men's clothing","rating":{"rate":4.1,"count":259}},
{"id":3,"title":"Mens Cotton Jacket","price":55.99, "category":"men's clothing","rating":{"rate":4.7,"count":500}},
{"id":4,"title":"Womens Dress","price":15.99, "category":"women's clothing" ,"rating":{"rate":2.1,"count":430}},
{"id":5,"title":"John Hardy Women's Legends Naga Gold & Silver Dragon Station Chain Bracelet","price":695, "category":"jewelery","rating":{"rate":4.6,"count":400}}
])
let [newProducts, setNewProducts] = useState([])
let [toCheck, setToCheck] = useState(true);
const filterProducts = (value) => {
setToCheck(!toCheck);
if (toCheck) {
newProducts = products
setNewProducts([...newProducts.filter((a) => a.category == value)])
}
}
return <div>
<div className='d-flex justify-content-evenly'>
{
category.map((elm, index) => {
return <div className="form-check ms-2" key={index}>
<input className="form-check-input" type="checkbox" value={elm} id="flexCheckDefault" onChange={(e) => filterProducts(e.target.value)}/>
<label className="form-check-label" htmlFor="flexCheckDefault">
{elm}
</label>
</div>
})
}
</div>
<div className='d-flex flex-wrap'>
{
(newProducts.length == 0 ? products : newProducts).map((prod) => {
return <div className='card m-3' style={{ width: "400px" }} key={prod.id}>
<div className='card-body'>
<p className='card-text'>Id: {prod.id}</p>
<h3 className='card-title'>Title: {prod.title}</h3>
<p className='card-text'>Price: {prod.price}</p>
<p className='card-text'>Category: {prod.category}</p>
<p className='card-text'>Rating: {prod.rating.rate}</p>
</div>
</div>
})
}
</div>
</div>
}
</code></pre>
<p>Thank you</p>
|
[
{
"answer_id": 74586627,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 1,
"selected": false,
"text": ">>> max_time_step = 3\n>>> sequence_length = 3\n>>> (\n... min_df\n... .with_columns([\n... pl.arange(0, max_time_step + 1).list().alias(\"range\"),\n... pl.col(\"time_idx\").arr.eval(\n... pl.arange(0, max_time_step + 1).is_in(pl.element()),\n... parallel=True\n... ).alias(\"mask\")\n... ])\n... )\nshape: (4, 4)\n┌───────────┬───────────────┬───────────────┬──────────────────────────┐\n│ group_idx | time_idx | range | mask │\n│ --- | --- | --- | --- │\n│ i64 | list[i64] | list[i64] | list[bool] │\n╞═══════════╪═══════════════╪═══════════════╪══════════════════════════╡\n│ 0 | [0, 1, ... 3] | [0, 1, ... 3] | [true, true, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 1 | [2, 3] | [0, 1, ... 3] | [false, false, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 2 | [0, 2, 3] | [0, 1, ... 3] | [true, false, ... true] │\n├───────────┼───────────────┼───────────────┼──────────────────────────┤\n│ 3 | [0, 3] | [0, 1, ... 3] | [true, false, ... true] │\n└─//────────┴─//────────────┴─//────────────┴─//───────────────────────┘\n .explode() true .groupby_rolling() .groupby() .list().slice() >>> min_df = pl.DataFrame({\n... \"group_idx\": [0, 1, 2, 3], \n... \"time_idx\": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]\n... })\n... max_time_step = 3\n... sequence_length = 2\n... (\n... min_df\n... .with_columns([\n... pl.arange(0, max_time_step + 1).list().alias(\"range\"),\n... pl.col(\"time_idx\").arr.eval(\n... pl.arange(0, max_time_step + 1).is_in(pl.element()),\n... parallel=True\n... ).alias(\"mask\")\n... ])\n... .explode([\"range\", \"mask\"])\n... .with_column(\n... pl.when(pl.col(\"mask\"))\n... .then(pl.col(\"range\"))\n... .alias(\"value\"))\n... .groupby(\"group_idx\", maintain_order=True)\n... .agg([\n... pl.col(\"value\")\n... .list()\n... .slice(length=sequence_length, offset=n)\n... .suffix(f\"{n}\")\n... for n in range(0, max_time_step - (1 if max_time_step % sequence_length == 0 else 0))\n... ])\n... .melt(\"group_idx\", value_name=\"subsequence\")\n... .drop(\"variable\")\n... .sort(\"group_idx\")\n... )\nshape: (12, 2)\n┌───────────┬──────────────┐\n│ group_idx | subsequence │\n│ --- | --- │\n│ i64 | list[i64] │\n╞═══════════╪══════════════╡\n│ 0 | [0, 1] │\n├───────────┼──────────────┤\n│ 0 | [1, 2] │\n├───────────┼──────────────┤\n│ 0 | [2, 3] │\n├───────────┼──────────────┤\n│ 1 | [null, null] │\n├───────────┼──────────────┤\n│ 1 | [null, 2] │\n├───────────┼──────────────┤\n│ ... | ... │\n├───────────┼──────────────┤\n│ 2 | [null, 2] │\n├───────────┼──────────────┤\n│ 2 | [2, 3] │\n├───────────┼──────────────┤\n│ 3 | [0, null] │\n├───────────┼──────────────┤\n│ 3 | [null, null] │\n├───────────┼──────────────┤\n│ 3 | [null, 3] │\n└─//────────┴─//───────────┘\n pl.element() .then() >>> (\n... min_df\n... .with_column(\n... pl.col(\"time_idx\").arr.eval(\n... pl.when(pl.arange(0, max_time_step + 1).is_in(pl.element()))\n... .then(pl.element()),\n... parallel=True)\n... .alias(\"subsequence\")\n... )\n... )\n---------------------------------------------------------------------------\nShapeError Traceback (most recent call last)\n"
},
{
"answer_id": 74586970,
"author": "ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ",
"author_id": 20557510,
"author_profile": "https://Stackoverflow.com/users/20557510",
"pm_score": 3,
"selected": true,
"text": "groupby_rolling period = 3\nmin_df = min_df.explode('time_idx')\n(\n min_df.get_column('group_idx').unique().to_frame()\n .join(\n min_df.get_column('time_idx').unique().to_frame(),\n how='cross'\n )\n .join(\n min_df.with_column(pl.col('time_idx').alias('time_idx_nulls')),\n on=['group_idx', 'time_idx'],\n how='left',\n )\n .groupby_rolling(\n index_column='time_idx',\n by='group_idx',\n period=str(period) + 'i',\n )\n .agg(pl.col(\"time_idx_nulls\"))\n .filter(pl.col('time_idx_nulls').arr.lengths() == period)\n .sort('group_idx')\n)\n shape: (8, 3)\n┌───────────┬──────────┬─────────────────┐\n│ group_idx ┆ time_idx ┆ time_idx_nulls │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ list[i64] │\n╞═══════════╪══════════╪═════════════════╡\n│ 0 ┆ 2 ┆ [0, 1, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 3 ┆ [1, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 2 ┆ [null, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 3 ┆ [null, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 2 ┆ [0, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 3 ┆ [null, 2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 2 ┆ [0, null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 3 ┆ [null, null, 3] │\n└───────────┴──────────┴─────────────────┘\n shape: (12, 3)\n┌───────────┬──────────┬────────────────┐\n│ group_idx ┆ time_idx ┆ time_idx_nulls │\n│ --- ┆ --- ┆ --- │\n│ i64 ┆ i64 ┆ list[i64] │\n╞═══════════╪══════════╪════════════════╡\n│ 0 ┆ 1 ┆ [0, 1] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 2 ┆ [1, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 1 ┆ [null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 2 ┆ [null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 1 ┆ [0, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 2 ┆ [null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 3 ┆ [2, 3] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 1 ┆ [0, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 2 ┆ [null, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 3 ┆ [null, 3] │\n└───────────┴──────────┴────────────────┘\n min_time = 0\nmax_time = 1_000\nnbr_groups = 400_000\nmin_df = (\n pl.DataFrame({\"time_idx\": [list(range(min_time, max_time, 2))]})\n .join(\n pl.arange(0, nbr_groups, eager=True).alias(\"group_idx\").to_frame(),\n how=\"cross\"\n )\n)\nmin_df.explode('time_idx')\n shape: (200000000, 2)\n┌──────────┬───────────┐\n│ time_idx ┆ group_idx │\n│ --- ┆ --- │\n│ i64 ┆ i64 │\n╞══════════╪═══════════╡\n│ 0 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 4 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 6 ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 992 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 994 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 996 ┆ 399999 │\n├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 998 ┆ 399999 │\n└──────────┴───────────┘\n slice concat slice slice_size time_index_df = (\n pl.arange(min_time, max_time, eager=True, dtype=pl.Int64)\n .alias(\"time_idx\")\n .to_frame()\n .lazy()\n)\n\n\nperiod = 3\nslice_size = 10_000\nresult = pl.concat(\n [\n (\n time_index_df\n .join(\n min_df\n .lazy()\n .slice(next_index, slice_size)\n .select(\"group_idx\"),\n how=\"cross\",\n )\n .join(\n min_df\n .lazy()\n .slice(next_index, slice_size)\n .explode('time_idx')\n .with_column(pl.col(\"time_idx\").alias(\"time_idx_nulls\")),\n on=[\"group_idx\", \"time_idx\"],\n how=\"left\",\n )\n .groupby_rolling(\n index_column='time_idx',\n by='group_idx',\n period=str(period) + 'i',\n )\n .agg(pl.col(\"time_idx_nulls\"))\n .filter(pl.col('time_idx_nulls').arr.lengths() == period)\n .select(['group_idx', 'time_idx_nulls'])\n .collect()\n )\n for next_index in range(0, min_df.height, slice_size)\n ]\n)\n\nresult.sort('group_idx')\n shape: (399200000, 2)\n┌───────────┬───────────────────┐\n│ group_idx ┆ time_idx_nulls │\n│ --- ┆ --- │\n│ i64 ┆ list[i64] │\n╞═══════════╪═══════════════════╡\n│ 0 ┆ [0, null, 2] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [null, 2, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [2, null, 4] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 0 ┆ [null, 4, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [994, null, 996] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [null, 996, null] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [996, null, 998] │\n├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤\n│ 399999 ┆ [null, 998, null] │\n└───────────┴───────────────────┘\n null slice"
},
{
"answer_id": 74595020,
"author": "jqurious",
"author_id": 19355181,
"author_profile": "https://Stackoverflow.com/users/19355181",
"pm_score": 2,
"selected": false,
"text": ".explode(\"subsequence\") .explode() unnest([ ... ] subsequence) explode_table() >>> import duckdb\n... \n... min_df = pl.DataFrame({\n... \"group_idx\": [0, 1, 2, 3], \n... \"time_idx\": [[0, 1, 2, 3], [2, 3], [0, 2, 3], [0,3]]\n... })\n... max_time_step = 3\n... sequence_length = 2\n... upper_bound = (\n... max_time_step - (\n... 1 if max_time_step % sequence_length == 0 else 0\n... )\n... )\n... tbl = min_df.to_arrow()\n... pl.from_arrow(\n... duckdb.connect().execute(f\"\"\"\n... select \n... group_idx, [ \n... time_idx_nulls[n: n + {sequence_length - 1}] \n... for n in range(1, {upper_bound + 1})\n... ] subsequence\n... from (\n... from tbl select group_idx, list_transform(\n... range(0, {max_time_step + 1}),\n... n -> case when list_has(time_idx, n) then n end\n... ) time_idx_nulls\n... )\n... \"\"\")\n... .arrow()\n... )\nshape: (4, 2)\n┌───────────┬─────────────────────────────────────┐\n│ group_idx | subsequence │\n│ --- | --- │\n│ i64 | list[list[i64]] │\n╞═══════════╪═════════════════════════════════════╡\n│ 0 | [[0, 1], [1, 2], [2, 3]] │\n├───────────┼─────────────────────────────────────┤\n│ 1 | [[null, null], [null, 2], [2, 3]... │\n├───────────┼─────────────────────────────────────┤\n│ 2 | [[0, null], [null, 2], [2, 3]] │\n├───────────┼─────────────────────────────────────┤\n│ 3 | [[0, null], [null, null], [null,... │\n└─//────────┴─//──────────────────────────────────┘\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20324382/"
] |
74,584,967
|
<p>The senario is that some people apply for some positions.<br />
So there are <code>tApplicant</code>, <code>tPosition</code> and a join table <code>tPreferences</code> for a many-to-many relationship between them.</p>
<p>I need to build a SQL expression where these should happen:</p>
<ol>
<li>get some fields from a join of <code>tApplicant</code> and <code>tPosition</code> into a new table.</li>
<li>create a new field called <code>AM</code> which should be either 1 or 0.<br />
1 = If <code>tApplicant.applicationID</code> is found in a third not relevant table called <code>tInfo</code>.<br />
0 = If <code>tApplicant.applicationID</code> is not found there.</li>
<li><code>ORDER BY AM</code>.</li>
</ol>
<p>It is executed in VBA. This is what I 've got so far:</p>
<pre><code>sSQL = "SELECT tApplicant.applicationID, tApplicant.name, tApplicant.ID, tPreferences.fld3, " & _
"NZ((SELECT 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID), 0) AS AM " _
"INTO " & sTable & " FROM tPreferences INNER JOIN tApplicant " & _
"ON tPreferences.IDapplic = tApplicant.applicationID " & _
"WHERE tPreferences.IDposit = " & rsRos!ID & ";"
CurrentDB.Execute sSQL, dbFailOnError
</code></pre>
<p>It seems like step 3 cannot be done.<br />
Adding <code>ORDER BY AM</code>, throws <code>Run-time error '3061'. Too few parameters. Expected 1.</code>.<br />
While adding <code>ORDER BY NZ((SELECT 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID), 0)</code>, throws <code>Run-Time Error 3075: Syntax Error in Query Expression 'NZ((SELECT 1 FROM tAMEA WHERE tAMEA.aitisiID = tAiton.aitisiID), 0'.</code>.<br />
If omitted, everything works fine but there's no ORDER BY.<br />
How can I achieve this?<br />
PS: If values 1 and 0 for AM make things complicated, and some other values instead could be easier to get with the query, it will be OK, I will deal with this in the rest of the code.</p>
|
[
{
"answer_id": 74585193,
"author": "Erik A",
"author_id": 7296893,
"author_profile": "https://Stackoverflow.com/users/7296893",
"pm_score": 2,
"selected": false,
"text": "Nz Access.Application CurrentDb.Execute Nz IIF((SELECT 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID) IS NOT NULL, 1, 0)\n ORDER BY EXISTS(SELECT 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID) DESC\n DoCmd.RunSQL DoCmd.RunSQL sSQL\n"
},
{
"answer_id": 74588843,
"author": "Gustav",
"author_id": 3527297,
"author_profile": "https://Stackoverflow.com/users/3527297",
"pm_score": 2,
"selected": false,
"text": "Top 1 AM sSQL = \"SELECT tApplicant.applicationID, tApplicant.name, tApplicant.ID, tPreferences.fld3, \" & _\n \"NZ((SELECT Top 1 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID), 0) AS AM \" _\n \"INTO \" & sTable & \" FROM tPreferences INNER JOIN tApplicant \" & _\n \"ON tPreferences.IDapplic = tApplicant.applicationID \" & _\n \"WHERE tPreferences.IDposit = \" & rsRos!ID & \";\"\nCurrentDB.Execute sSQL, dbFailOnError\n Nz Exists sSQL = \"SELECT tApplicant.applicationID, tApplicant.name, tApplicant.ID, tPreferences.fld3, \" & _\n \"EXISTS (SELECT Top 1 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID) AS AM \" _\n \"INTO \" & sTable & \" FROM tPreferences INNER JOIN tApplicant \" & _\n \"ON tPreferences.IDapplic = tApplicant.applicationID \" & _\n \"WHERE tPreferences.IDposit = \" & rsRos!ID & \";\"\nCurrentDB.Execute sSQL, dbFailOnError\n AM -1 0 AM 1 ABS sSQL = \"SELECT tApplicant.applicationID, tApplicant.name, tApplicant.ID, tPreferences.fld3, \" & _\n \"ABS(EXISTS (SELECT Top 1 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID)) AS AM \" _\n \"INTO \" & sTable & \" FROM tPreferences INNER JOIN tApplicant \" & _\n \"ON tPreferences.IDapplic = tApplicant.applicationID \" & _\n \"WHERE tPreferences.IDposit = \" & rsRos!ID & \";\"\nCurrentDB.Execute sSQL, dbFailOnError\n"
},
{
"answer_id": 74589711,
"author": "dimitris",
"author_id": 4037170,
"author_profile": "https://Stackoverflow.com/users/4037170",
"pm_score": 2,
"selected": true,
"text": "SELECT INSERT INTO ORDER BY sSQL = \"SELECT * INTO \" & sTable & \" FROM (\" & _\n \"SELECT tApplicant.applicationID, tApplicant.name, tApplicant.ID, tProtimisi.fld3, \" & _\n \"NZ((SELECT 1 FROM tInfo WHERE tInfo.applicationID = tApplicant.applicationID), 0) AS AM \" & _\n \"FROM tPreferences INNER JOIN tApplicant \" & _\n \"ON tPreferences.IDapplic = tApplicant.applicationID \" & _\n \"WHERE tPreferences.IDposit = \" & rsRos!ID & \") \" & _\n \"ORDER BY AM DESC;\"\nCurrentDb.Execute sSQL, dbFailOnError\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74584967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4037170/"
] |
74,585,082
|
<p>I need to make a textfield that only accepts up to 100 (as string) maximum, if they type 101 or more it should turn red, can you do this in flutter with or without an outside package?</p>
<p>I have no idea where to even start, is the first time i do something this kind.</p>
|
[
{
"answer_id": 74585131,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "limit class CustomInput extends StatefulWidget {\n const CustomInput({Key? key}) : super(key: key);\n\n @override\n State<CustomInput> createState() => _CustomInputState();\n}\n\nclass _CustomInputState extends State<CustomInput> {\n Color textColor = Colors.black;\n int limit = 5;\n @override\n Widget build(BuildContext context) {\n return TextField(\n decoration: InputDecoration(hintText: 'some text'),\n onChanged: (value) {\n if (value.length > limit && textColor == Colors.black) {\n setState(() {\n textColor = Colors.red;\n });\n } else if (value.length <= limit && textColor == Colors.red) {\n setState(() {\n textColor = Colors.black;\n });\n }\n },\n style: TextStyle(\n color: textColor,\n ),\n );\n }\n}\n Scaffold(\n key: _key,\n backgroundColor: Colors.white,\n appBar: AppBar(),\n body: Column(\n children: [\n SizedBox(\n height: 10,\n ),\n CustomInput(),\n ],\n ),\n)\n"
},
{
"answer_id": 74587396,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "TextField TextField style TextStyle() color import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return const MaterialApp(\n home: Scaffold(\n body: CustomTextField(),\n ),\n );\n }\n}\n\nclass CustomTextField extends StatefulWidget {\n const CustomTextField({Key? key}) : super(key: key);\n\n @override\n State<CustomTextField> createState() => _CustomTextFieldState();\n}\n\nclass _CustomTextFieldState extends State<CustomTextField> {\n final TextEditingController _controller = TextEditingController();\n\n @override\n Widget build(BuildContext context) {\n\n return TextField(\n maxLength: 100,\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Enter your text',\n ),\n onChanged: (text) {\n setState(() {\n // update the text color\n _controller.text = text;\n });\n },\n style: TextStyle(\n color: (_controller.text.length > 100) ? Colors.red : Colors.black,\n ),\n );\n }\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19702304/"
] |
74,585,110
|
<p>I have well over 100,000 GPS locations of 35 animals. I have removed the 'NA' and '0' GPS latitude-longitude locations but noticed that there was one latitude and longitude location that was incorrect and that needs to be removed (in this subset of data, the 4th line that has -78.6917357 17.5506138 as LAT and LON). It is likely that there are other incorrect GPS locations and wondered if there is an easy way to identify outliers and remove them.</p>
<p>My sample data looks like this:</p>
<pre><code>COLLAR NAME Animal_ID SEX DATE TIME Year Month Day Hour LATITUDE LONGITUDE HEIGHT
26 Keith CM8 M 2009-05-28 2:00:00 2009 5 28 2 49.7518424 -123.6099396 705.87
26 Keith CM8 M 2009-06-09 7:00:00 2009 6 9 7 49.7518495 -123.4860212 191.61
26 Keith CM8 M 2009-05-31 18:00:002009 5 31 18 49.7518576 -123.5373316 410.96
26 Jack CM6 M 2009-06-01 22:00:002009 6 1 22 -78.6917357 17.5506138 490.23
26 Keith CM8 M 2009-05-28 2:00:00 2009 5 28 2 49.7518424 -123.6099396 705.87
26 Keith CM8 M 2009-06-09 7:00:00 2009 6 9 7 49.7518495 -123.4860212 191.61
26 Keith CM8 M 2009-05-31 18:00:002009 5 31 18 49.7518576 -123.5373316 410.96
27 Keith CM8 M 2009-05-28 3:00:00 2009 5 28 3 49.7518775 -123.6099242 713.05
27 Keith CM8 M 2009-06-09 10:00:002009 6 9 10 49.7519163 -123.486203 108.02
</code></pre>
<p>The code I used is this which works to remove the 0 and NA:</p>
<pre><code> library(dplyr)
data <- data_all %>%
filter(!is.na(LATITUDE), LATITUDE !=0,!is.na(LONGITUDE), LONGITUDE !=0)
</code></pre>
<p>Now, I would like to further remove row 4 here (and any other invalid or incorrect spatial points) using the following line of code but that does not work:</p>
<pre><code>data <- filter(LATITUDE !=-78.69174, LONGITUDE !=17.55061)
</code></pre>
<p>I cannot see a reduction in the number of rows after running this code. Please note that I do not have row numbers so cannot specifically remove row 4 and, ideally, I want to remove all those rows that have odd values in one line of code (or as a pipe function) that does work. Your help would be most appreciated. Thanks!</p>
|
[
{
"answer_id": 74585131,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "limit class CustomInput extends StatefulWidget {\n const CustomInput({Key? key}) : super(key: key);\n\n @override\n State<CustomInput> createState() => _CustomInputState();\n}\n\nclass _CustomInputState extends State<CustomInput> {\n Color textColor = Colors.black;\n int limit = 5;\n @override\n Widget build(BuildContext context) {\n return TextField(\n decoration: InputDecoration(hintText: 'some text'),\n onChanged: (value) {\n if (value.length > limit && textColor == Colors.black) {\n setState(() {\n textColor = Colors.red;\n });\n } else if (value.length <= limit && textColor == Colors.red) {\n setState(() {\n textColor = Colors.black;\n });\n }\n },\n style: TextStyle(\n color: textColor,\n ),\n );\n }\n}\n Scaffold(\n key: _key,\n backgroundColor: Colors.white,\n appBar: AppBar(),\n body: Column(\n children: [\n SizedBox(\n height: 10,\n ),\n CustomInput(),\n ],\n ),\n)\n"
},
{
"answer_id": 74587396,
"author": "MendelG",
"author_id": 12349734,
"author_profile": "https://Stackoverflow.com/users/12349734",
"pm_score": 1,
"selected": false,
"text": "TextField TextField style TextStyle() color import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return const MaterialApp(\n home: Scaffold(\n body: CustomTextField(),\n ),\n );\n }\n}\n\nclass CustomTextField extends StatefulWidget {\n const CustomTextField({Key? key}) : super(key: key);\n\n @override\n State<CustomTextField> createState() => _CustomTextFieldState();\n}\n\nclass _CustomTextFieldState extends State<CustomTextField> {\n final TextEditingController _controller = TextEditingController();\n\n @override\n Widget build(BuildContext context) {\n\n return TextField(\n maxLength: 100,\n decoration: const InputDecoration(\n border: OutlineInputBorder(),\n labelText: 'Enter your text',\n ),\n onChanged: (text) {\n setState(() {\n // update the text color\n _controller.text = text;\n });\n },\n style: TextStyle(\n color: (_controller.text.length > 100) ? Colors.red : Colors.black,\n ),\n );\n }\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11763351/"
] |
74,585,139
|
<p>Problem - I want to keep the 4th box in 2nd row like in the current code, but the width of the 4th box should be similar to 1/2/5/6 box i.e. 100px.</p>
<p>But currently 4th box is taking full width in 2nd row, I want it to take only 100px space and rest empty space in row 2. 5 and 6 ox should come on 3rd row.</p>
<p>Alignment Needed -</p>
<pre><code>1 2 3
4
5 6
7 7 7
</code></pre>
<p>Code -</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.one { background: red; }
.two { background: green; }
.three { background: blue; }
.four { background: pink; }
.five { background: violet; }
.six { background: yellow; }
.seven { background: teal; }
.box { padding: 5px; text-align: center; }
.container {
border: 1px solid;
display: grid;
grid-template-columns: 100px 100px auto;
gap: 20px 10px;
}
.box:nth-child(4) {
grid-column: span 3;
}
.box:last-child {
grid-column-end: span 3;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
<div class="box five">5</div>
<div class="box six">6</div>
<div class="box seven">7</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74585231,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 3,
"selected": true,
"text": ".one { background: red; }\n.two { background: green; }\n.three { background: blue; }\n.four { background: pink; }\n.five { background: violet; }\n.six { background: yellow; }\n.seven { background: teal; }\n.box { padding: 5px; text-align: center; }\n.container {\n border: 1px solid;\n display: grid;\n grid-template-columns: 100px 100px auto;\n gap: 20px 10px;\n}\n\n.box:nth-child(4) {\n /*grid-column: span 1;*/\n grid-column-start: 1;\n grid-column-end: 2;\n}\n.box:nth-child(5) {\n grid-column-start: 1;\n grid-column-end: 2;\n}\n\n.box:last-child {\n grid-column-end: span 3;\n} <div class=\"container\">\n <div class=\"box one\">1</div>\n <div class=\"box two\">2</div>\n <div class=\"box three\">3</div>\n <div class=\"box four\">4</div>\n <div class=\"box five\">5</div>\n <div class=\"box six\">6</div>\n <div class=\"box seven\">7</div>\n</div>"
},
{
"answer_id": 74585337,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 0,
"selected": false,
"text": ".one { background: red; }\n.two { background: green; }\n.three { background: blue; }\n.four { background: pink; }\n.five { background: violet; }\n.six { background: yellow; }\n.seven { background: teal; }\n.box { padding: 5px; text-align: center; }\n.container {\n border: 1px solid;\n display: grid;\n grid-template-columns: 100px 100px auto;\n gap: 20px 10px;\n}\n\n.box:nth-child(5) {\n grid-column: 1;\n}\n\n.box:last-child {\n grid-column: span 3;\n} <div class=\"container\">\n <div class=\"box one\">1</div>\n <div class=\"box two\">2</div>\n <div class=\"box three\">3</div>\n <div class=\"box four\">4</div>\n <div class=\"box five\">5</div>\n <div class=\"box six\">6</div>\n <div class=\"box seven\">7</div>\n</div>"
},
{
"answer_id": 74585354,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": 0,
"selected": false,
"text": ".one { background: red; }\n.two { background: green; }\n.three { background: blue; }\n.four { background: pink; }\n.five { background: violet; }\n.six { background: yellow; }\n.seven { background: teal; }\n.box { padding: 5px; text-align: center; }\n.container {\n border: 1px solid;\n display: grid;\n grid-template-columns: 32% 32% auto;\n gap: 20px 10px;\n}\n\n\n\n.box:nth-child(5) {\n grid-column-start: 1;\n grid-column-end: 2;\n}\n\n.box:last-child {\n grid-column-end: span 3;\n} <div class=\"container\">\n <div class=\"box one\">1</div>\n <div class=\"box two\">2</div>\n <div class=\"box three\">3</div>\n <div class=\"box four\">4</div>\n <div class=\"box five\">5</div>\n <div class=\"box six\">6</div>\n <div class=\"box seven\">7</div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4818458/"
] |
74,585,148
|
<p>First of all, sorry if this was asked before, but I simply could not find anything related to it.</p>
<pre class="lang-cs prettyprint-override"><code>string anElement = "World";
string[] col = new string[2] { "Hello", anElement };
anElement = "Jupiter";
Array.ForEach(col, Console.WriteLine);
// Output:
// Hello
// World
</code></pre>
<p>As can be seen, reassigning a different value to the <code>anElement</code> reference doesn't update the value.</p>
<p>Same also applies in this scenario:</p>
<pre class="lang-cs prettyprint-override"><code>string[] col = new string[2] { "Hello", "World" };
string elementToUpdate = col[1];
elementToUpdate = "Jupiter";
Array.ForEach(col, Console.WriteLine);
</code></pre>
<p>If all the elements are stored as references, why changing <code>col[1]="Jupiter"</code> works while the above does not?</p>
|
[
{
"answer_id": 74585231,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 3,
"selected": true,
"text": ".one { background: red; }\n.two { background: green; }\n.three { background: blue; }\n.four { background: pink; }\n.five { background: violet; }\n.six { background: yellow; }\n.seven { background: teal; }\n.box { padding: 5px; text-align: center; }\n.container {\n border: 1px solid;\n display: grid;\n grid-template-columns: 100px 100px auto;\n gap: 20px 10px;\n}\n\n.box:nth-child(4) {\n /*grid-column: span 1;*/\n grid-column-start: 1;\n grid-column-end: 2;\n}\n.box:nth-child(5) {\n grid-column-start: 1;\n grid-column-end: 2;\n}\n\n.box:last-child {\n grid-column-end: span 3;\n} <div class=\"container\">\n <div class=\"box one\">1</div>\n <div class=\"box two\">2</div>\n <div class=\"box three\">3</div>\n <div class=\"box four\">4</div>\n <div class=\"box five\">5</div>\n <div class=\"box six\">6</div>\n <div class=\"box seven\">7</div>\n</div>"
},
{
"answer_id": 74585337,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 0,
"selected": false,
"text": ".one { background: red; }\n.two { background: green; }\n.three { background: blue; }\n.four { background: pink; }\n.five { background: violet; }\n.six { background: yellow; }\n.seven { background: teal; }\n.box { padding: 5px; text-align: center; }\n.container {\n border: 1px solid;\n display: grid;\n grid-template-columns: 100px 100px auto;\n gap: 20px 10px;\n}\n\n.box:nth-child(5) {\n grid-column: 1;\n}\n\n.box:last-child {\n grid-column: span 3;\n} <div class=\"container\">\n <div class=\"box one\">1</div>\n <div class=\"box two\">2</div>\n <div class=\"box three\">3</div>\n <div class=\"box four\">4</div>\n <div class=\"box five\">5</div>\n <div class=\"box six\">6</div>\n <div class=\"box seven\">7</div>\n</div>"
},
{
"answer_id": 74585354,
"author": "reza hrkeng",
"author_id": 20517507,
"author_profile": "https://Stackoverflow.com/users/20517507",
"pm_score": 0,
"selected": false,
"text": ".one { background: red; }\n.two { background: green; }\n.three { background: blue; }\n.four { background: pink; }\n.five { background: violet; }\n.six { background: yellow; }\n.seven { background: teal; }\n.box { padding: 5px; text-align: center; }\n.container {\n border: 1px solid;\n display: grid;\n grid-template-columns: 32% 32% auto;\n gap: 20px 10px;\n}\n\n\n\n.box:nth-child(5) {\n grid-column-start: 1;\n grid-column-end: 2;\n}\n\n.box:last-child {\n grid-column-end: span 3;\n} <div class=\"container\">\n <div class=\"box one\">1</div>\n <div class=\"box two\">2</div>\n <div class=\"box three\">3</div>\n <div class=\"box four\">4</div>\n <div class=\"box five\">5</div>\n <div class=\"box six\">6</div>\n <div class=\"box seven\">7</div>\n</div>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14040062/"
] |
74,585,157
|
<p>I have the following <code>CodeBehind</code> and <code>XAML</code> which I used to get all data from an <code>SQLite</code> table and populate a <code>CollectionView</code>:</p>
<p><strong>.cs</strong></p>
<pre><code>protected override void OnAppearing()
{
base.OnAppearing();
List<Record> records = App.RecordRepo.GetAllRecords();
recordList.ItemsSource = records;
}
</code></pre>
<p><strong>.xaml</strong></p>
<pre><code><Grid Grid.Row="0">
<VerticalStackLayout>
<Label x:Name="lblHoldingTotal" Text="Total"/>
<Label x:Name="lblAverageBuyPrice" Text="Average Buy Price"/>
<Label x:Name="lblTotalPaid" Text="Total Paid"/>
<Label x:Name="lblTicker" Text="Ticker"/>
<Label x:Name="lblHoldingValue" Text="Holding Value"/>
<Label x:Name="lblProfit" Text="Profit"/>
</VerticalStackLayout>
</Grid>
<Grid Grid.Row="1">
<CollectionView x:Name="recordList">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding Id}" />
<Label Grid.Column="1" Text="{Binding Amount}" />
<Label Grid.Column="2" Text="{Binding Paid}" />
<Label Grid.Column="3" Text="P/L" />
<Label Grid.Column="4" Text="{Binding PurchaseDate}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</code></pre>
<p>How would I update the value in Column 3 (Which currently has <code>P/L</code> as a placeholder for all rows) based on a value from the <code>CollectionView</code> after populating it, and a value from a <code>Label</code> outside the <code>CollectionView</code> without using the MVVM framework?</p>
<p>For example:</p>
<p><code>(Column 3 label text) = (Column 2 Label text value) - lblTicker.text</code></p>
|
[
{
"answer_id": 74609211,
"author": "ToolmakerSteve",
"author_id": 199364,
"author_profile": "https://Stackoverflow.com/users/199364",
"pm_score": 0,
"selected": false,
"text": "<CollectionView.ItemTemplate>\n <DataTemplate>\n <mynamespace:MyItemView ... />\n </DataTemplate>\n</CollectionView.ItemTemplate>\n DataTemplate <Grid xmlns=\"http://xamarin.com/schemas/2014/forms\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\"\n x:Class=\"MyNameSpace.MyItemView\">\n ...\n <... x:Name=\"someElement\" ... />\n</Grid>\n public partial class MyItemView : Grid\n{\n ...\n \n protected override void OnBindingContextChanged()\n {\n base.OnBindingContextChanged();\n\n // The \"model\" that this row is bound to.\n var item = (MyItemClass)BindingContext;\n // The UI element you want to set dynamically.\n someElement.SomeProperty = item....;\n ...\n }\n}\n lblTicker.Text = \"Whatever text is needed\".\n"
},
{
"answer_id": 74634999,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 0,
"selected": false,
"text": "ItemsSource Record Profit public class Record\n{\n public int Id { get; set; }\n public decimal Amount { get; set; }\n public decimal Paid { get; set; }\n public DateTime PurchaseDate { get; set; }\n\n // new property for the calculated value\n public decimal Profit { get; set; }\n}\n\n ItemsSource lblTicker Amount // get the records from the database\nList<Record> records = App.RecordRepo.GetAllRecords();\n\n// modify the records by setting the Profit property\nrecords = records.Select(r => \n{\n r.Profit = r.Amount - decimal.Parse(lblTicker.Text);\n return r;\n}).ToList();\n\n// set the modified records as the items source for the CollectionView\nrecordList.ItemsSource = records;\n\n Profit <DataTemplate>\n <Grid>\n <Grid.ColumnDefinitions>\n \n"
},
{
"answer_id": 74662940,
"author": "Benjamin Woolston",
"author_id": 20188398,
"author_profile": "https://Stackoverflow.com/users/20188398",
"pm_score": 0,
"selected": false,
"text": "public class Record\n{\n // Other properties\n\n public decimal Profit\n {\n get\n {\n return Amount - Paid;\n }\n }\n}\n <Label Grid.Column=\"3\" Text=\"{Binding Profit}\" />\n public class ProfitConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Calculate the profit value here\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n <ContentPage.Resources>\n <ResourceDictionary>\n <local:ProfitConverter x:Key=\"profitConverter\" />\n </ResourceDictionary>\n</ContentPage.Resources>\n <Label Grid.Column=\"3\" Text=\"{Binding Amount, Converter={StaticResource profitConverter}}\" />\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n{\n decimal amount = (decimal)value;\n decimal paid = decimal.Parse(parameter.ToString());\n decimal profit = amount - paid;\n return profit;\n}\n"
},
{
"answer_id": 74677826,
"author": "DotNetRussell",
"author_id": 2051392,
"author_profile": "https://Stackoverflow.com/users/2051392",
"pm_score": 0,
"selected": false,
"text": "private void recordList_ItemAppearing(object sender, ItemVisibilityEventArgs e) \n{ \n var item = e.Item as Record; \n if(item != null) \n { \n //update the value for column 3 \n item.Profit = item.Paid - Convert.ToDouble(lblTicker.Text); \n } \n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364312/"
] |
74,585,167
|
<p>I have a file of recipes</p>
<pre><code>banana pancake
1 cups of flour
2 tablespoons of sugar
1 eggs
1 cups of milk
3 teaspoons of cinnamon
2 teaspoons of baking powder
0 slices of bread
2 bananas
0 apples
0 peaches
</code></pre>
<p>And I need to create a dictionary, where the key is the name of the ingredient and the value is the respective unit.</p>
<pre><code>Example {
'cups of flower': 1
'tablespoons of sugar': 2
...
}
</code></pre>
<p>This is what I tried to do</p>
<pre><code>file = open('recipe.txt', 'r')
alpha = 'abcdefghijklmnopqrstuvwxyz'
d = {}
for line in file:
if line[0] in alpha:#this makes sure that the for loop "ignores" the first line for each recipe, which contains the name of the meal
continue
else:
line1 = line.split(' ') #splits lines into lists
d[line1[1:]] = line1[0] #grabs keys and values
print(d)
</code></pre>
|
[
{
"answer_id": 74609211,
"author": "ToolmakerSteve",
"author_id": 199364,
"author_profile": "https://Stackoverflow.com/users/199364",
"pm_score": 0,
"selected": false,
"text": "<CollectionView.ItemTemplate>\n <DataTemplate>\n <mynamespace:MyItemView ... />\n </DataTemplate>\n</CollectionView.ItemTemplate>\n DataTemplate <Grid xmlns=\"http://xamarin.com/schemas/2014/forms\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\"\n x:Class=\"MyNameSpace.MyItemView\">\n ...\n <... x:Name=\"someElement\" ... />\n</Grid>\n public partial class MyItemView : Grid\n{\n ...\n \n protected override void OnBindingContextChanged()\n {\n base.OnBindingContextChanged();\n\n // The \"model\" that this row is bound to.\n var item = (MyItemClass)BindingContext;\n // The UI element you want to set dynamically.\n someElement.SomeProperty = item....;\n ...\n }\n}\n lblTicker.Text = \"Whatever text is needed\".\n"
},
{
"answer_id": 74634999,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 0,
"selected": false,
"text": "ItemsSource Record Profit public class Record\n{\n public int Id { get; set; }\n public decimal Amount { get; set; }\n public decimal Paid { get; set; }\n public DateTime PurchaseDate { get; set; }\n\n // new property for the calculated value\n public decimal Profit { get; set; }\n}\n\n ItemsSource lblTicker Amount // get the records from the database\nList<Record> records = App.RecordRepo.GetAllRecords();\n\n// modify the records by setting the Profit property\nrecords = records.Select(r => \n{\n r.Profit = r.Amount - decimal.Parse(lblTicker.Text);\n return r;\n}).ToList();\n\n// set the modified records as the items source for the CollectionView\nrecordList.ItemsSource = records;\n\n Profit <DataTemplate>\n <Grid>\n <Grid.ColumnDefinitions>\n \n"
},
{
"answer_id": 74662940,
"author": "Benjamin Woolston",
"author_id": 20188398,
"author_profile": "https://Stackoverflow.com/users/20188398",
"pm_score": 0,
"selected": false,
"text": "public class Record\n{\n // Other properties\n\n public decimal Profit\n {\n get\n {\n return Amount - Paid;\n }\n }\n}\n <Label Grid.Column=\"3\" Text=\"{Binding Profit}\" />\n public class ProfitConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n // Calculate the profit value here\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n <ContentPage.Resources>\n <ResourceDictionary>\n <local:ProfitConverter x:Key=\"profitConverter\" />\n </ResourceDictionary>\n</ContentPage.Resources>\n <Label Grid.Column=\"3\" Text=\"{Binding Amount, Converter={StaticResource profitConverter}}\" />\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n{\n decimal amount = (decimal)value;\n decimal paid = decimal.Parse(parameter.ToString());\n decimal profit = amount - paid;\n return profit;\n}\n"
},
{
"answer_id": 74677826,
"author": "DotNetRussell",
"author_id": 2051392,
"author_profile": "https://Stackoverflow.com/users/2051392",
"pm_score": 0,
"selected": false,
"text": "private void recordList_ItemAppearing(object sender, ItemVisibilityEventArgs e) \n{ \n var item = e.Item as Record; \n if(item != null) \n { \n //update the value for column 3 \n item.Profit = item.Paid - Convert.ToDouble(lblTicker.Text); \n } \n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609183/"
] |
74,585,200
|
<p>I have an array of objects.
I need to:</p>
<ul>
<li>check if the object has a specific key:value combination</li>
<li>if yes, replace a different value of this object</li>
<li>return both the objects</li>
</ul>
<p>This is how I am trying to achieve it:</p>
<pre><code>list.map(item => {
return {
...item,
...(item["orderId"] === 'xyz' && { transactionNumber: 'sadfdas gasdgas' }),
}
</code></pre>
<p>I also tried this condition instead:</p>
<pre><code>...(orderId === 'xyz' && { transactionNumber: 'sadfdas gasdgas' })
</code></pre>
<p>and this:</p>
<pre><code>...(item.orderId === 'xyz' && { transactionNumber: 'sadfdas gasdgas' })
</code></pre>
<p>and this:</p>
<pre><code>...(item.orderId === 'xyz' ? { transactionNumber: 'sadfdas gasdgas' } : {})
</code></pre>
<p>However they all return the two objects in the list unchanged.</p>
<p>If I instead use this code:</p>
<pre><code>.map(item => {
return {
...item,
transactionNumber: 'sadfdasgasdgas'
}
})
</code></pre>
<p>it replaces the <code>transactionNumber</code> for each object.</p>
<p>What am I doing wrong that the condition is not working?</p>
<p>Example of what should happen:</p>
<pre><code>const list = [{
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:999
]
</code></pre>
<p>If we process the variable above, the result would be:</p>
<pre><code>[{
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:999
]
</code></pre>
<p>But if we process the following array:</p>
<pre><code>[{
aaa: 123,
bbb: 222,
orderId: "xyz",
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:"sadfdasgasdgas"
]
</code></pre>
<p>the result should be:</p>
<pre><code>[{
aaa: 123,
bbb: 222,
orderId: "xyz",
transactionNumber: 888
},
aaa: 123,
bbb: 222,
orderId: 555,
transactionNumber:999
]
</code></pre>
|
[
{
"answer_id": 74585232,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 1,
"selected": true,
"text": "const list = [ { orderId: \"xyz\", transactionNumber: \"1\" }, { orderId: \"abc\", transactionNumber: \"2\" } ];\n\nconst res = list.map(item => ({\n ...item,\n transactionNumber: item[\"orderId\"] === 'xyz' ? 'sadfdas gasdgas' : item[\"transactionNumber\"]\n}));\n\nconsole.log(res);"
},
{
"answer_id": 74585272,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 1,
"selected": false,
"text": "const list = [\n { name: 1, orderId: 'abc', transactionNumber: 1 },\n { name: 2, orderId: 'xyz', transactionNumber: 2 },\n { name: 3, orderId: 'efg', transactionNumber: 3 }\n];\n\n// Make a copy of the object \"in transit\"\nconst out = list.map(({ ...item }) => {\n\n // Update the number of the object if\n // the condition is true\n if (item.orderId === 'xyz') {\n item.transactionNumber = 'test';\n }\n \n // Return the item\n return item;\n\n});\n\nconsole.log(out);"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1580094/"
] |
74,585,203
|
<p>Using <code>SendMessage</code> I can pass a <code>CString</code> up to the parent easily enough (simplified):</p>
<pre><code>CString strText = L"The text";
GetParent()->SendMessage(theApp.UWM_LOADED_SRR_FILE_MSG,
reinterpret_cast<WPARAM>(strText.GetString()));
</code></pre>
<p>Parent handler:</p>
<pre><code>afx_msg LRESULT CMyDialog::OnSetSRRFilename(WPARAM wParam, LPARAM lParam)
{
LPCTSTR szFilename = reinterpret_cast<LPCTSTR>(wParam);
// Do something.
return 0;
}
</code></pre>
<p>That works, but what about the other way? How can I use messaging to get the current CString value from the parent? I know I can just cast to the parent object type and call the public method. But I want to use messaging. The way I understand it is that SendMessage is passing to a location to receive text.</p>
<p>Am I supposed to post a message to parent that says "i want the string" passing the handle of my window. And then in that handler it sends a message to that handle with the string value?</p>
<p>Am I overcomplicating this?</p>
<p>The string value is not a control, just a private variable.</p>
|
[
{
"answer_id": 74585445,
"author": "Constantine Georgiou",
"author_id": 1372577,
"author_profile": "https://Stackoverflow.com/users/1372577",
"pm_score": 3,
"selected": true,
"text": "wParam lParam WM_GETTEXT GetClipboardData() CString* new delete CString GetString()"
},
{
"answer_id": 74590099,
"author": "Andrew Truckle",
"author_id": 2287576,
"author_profile": "https://Stackoverflow.com/users/2287576",
"pm_score": 1,
"selected": false,
"text": "afx_msg LRESULT CMyDialog::OnGetSRRFilename(WPARAM wParam, LPARAM lParam)\n{\n return reinterpret_cast<LRESULT>(GetLastEditedSRRFile().GetString());\n}\n const auto szFileName = reinterpret_cast<LPCTSTR>(GetParent()->SendMessage(theApp.UWM_GET_SRR_FILENAME_MSG));\n"
},
{
"answer_id": 74595616,
"author": "Barmak Shemirani",
"author_id": 4603670,
"author_profile": "https://Stackoverflow.com/users/4603670",
"pm_score": 2,
"selected": false,
"text": "SendMessage WM_COPYDATA auto ptr = dynamic_cast<CMyParent*>(GetParent());\nif (ptr)\n{\n CString str;\n ptr->GetSRRFilename(str);\n ptr->SetSRRFilename(str);\n ...\n}\nelse\n{\n MessageBox(\"cast failed, \\\n parent is not CMyParent class. We are not interested.\");\n}\n static_cast GetParent() CMyParent CMyParent1 CMyParent2 SendMessage"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287576/"
] |
74,585,212
|
<p>During installation of a Nest Application node modules, I have the following error:</p>
<pre><code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ticket-be@0.1.3
npm ERR! Found: typeorm@0.2.45
npm ERR! node_modules/typeorm
npm ERR! typeorm@"^0.2.45" from the root project
npm ERR! peer typeorm@"^0.2.25" from @nestjs-query/query-typeorm@0.30.0
npm ERR! node_modules/@nestjs-query/query-typeorm
npm ERR! @nestjs-query/query-typeorm@"^0.30.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer typeorm@"^0.3.0" from @nestjs/typeorm@8.1.4
npm ERR! node_modules/@nestjs/typeorm
npm ERR! @nestjs/typeorm@"^8.0.3" from the root project
npm ERR! peer @nestjs/typeorm@"^8.0.0" from @nestjs-query/query-typeorm@0.30.0
npm ERR! node_modules/@nestjs-query/query-typeorm
npm ERR! @nestjs-query/query-typeorm@"^0.30.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
</code></pre>
<p>Can you give me suggestions to resolve dependency? Or is better to use --force or --legacy-peer-deps?
Thank you in advance.</p>
<p>Here dependencies section of my package.json</p>
<pre><code>"dependencies": {
"@nestjs-modules/mailer": "^1.6.1",
"@nestjs-query/query-typeorm": "^0.30.0",
"@nestjs/common": "^8.4.4",
"@nestjs/config": "^2.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/jwt": "^8.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^8.2.1",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/swagger": "^5.2.1",
"@nestjs/typeorm": "^8.0.3",
"@types/bcrypt": "^5.0.0",
"@types/cookie-parser": "^1.4.2",
"bcrypt": "^5.0.1",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.2",
"cookie-parser": "^1.4.6",
"fastify-swagger": "^5.1.0",
"handlebars": "^4.7.7",
"joi": "^17.6.0",
"passport": "^0.5.2",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"pdfmake": "^0.2.5",
"pg": "^8.7.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"swagger-themes": "^1.2.22",
"swagger-ui-express": "^4.3.0",
"typeorm": "^0.2.45",
"uuid": "^8.3.2",
"webpack": "^5.72.1"
}
</code></pre>
<p>I tried to remove "typeorm": "^0.2.45" from package.json, but I have same type error:</p>
<pre><code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ticket-be@0.1.3
npm ERR! Found: typeorm@0.3.10
npm ERR! node_modules/typeorm
npm ERR! peer typeorm@"^0.3.0" from @nestjs/typeorm@8.1.4
npm ERR! node_modules/@nestjs/typeorm
npm ERR! @nestjs/typeorm@"^8.0.3" from the root project
npm ERR! peer @nestjs/typeorm@"^8.0.0" from @nestjs-query/query-typeorm@0.30.0
npm ERR! node_modules/@nestjs-query/query-typeorm
npm ERR! @nestjs-query/query-typeorm@"^0.30.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer typeorm@"^0.2.25" from @nestjs-query/query-typeorm@0.30.0
npm ERR! node_modules/@nestjs-query/query-typeorm
npm ERR! @nestjs-query/query-typeorm@"^0.30.0" from the root project
</code></pre>
|
[
{
"answer_id": 74585445,
"author": "Constantine Georgiou",
"author_id": 1372577,
"author_profile": "https://Stackoverflow.com/users/1372577",
"pm_score": 3,
"selected": true,
"text": "wParam lParam WM_GETTEXT GetClipboardData() CString* new delete CString GetString()"
},
{
"answer_id": 74590099,
"author": "Andrew Truckle",
"author_id": 2287576,
"author_profile": "https://Stackoverflow.com/users/2287576",
"pm_score": 1,
"selected": false,
"text": "afx_msg LRESULT CMyDialog::OnGetSRRFilename(WPARAM wParam, LPARAM lParam)\n{\n return reinterpret_cast<LRESULT>(GetLastEditedSRRFile().GetString());\n}\n const auto szFileName = reinterpret_cast<LPCTSTR>(GetParent()->SendMessage(theApp.UWM_GET_SRR_FILENAME_MSG));\n"
},
{
"answer_id": 74595616,
"author": "Barmak Shemirani",
"author_id": 4603670,
"author_profile": "https://Stackoverflow.com/users/4603670",
"pm_score": 2,
"selected": false,
"text": "SendMessage WM_COPYDATA auto ptr = dynamic_cast<CMyParent*>(GetParent());\nif (ptr)\n{\n CString str;\n ptr->GetSRRFilename(str);\n ptr->SetSRRFilename(str);\n ...\n}\nelse\n{\n MessageBox(\"cast failed, \\\n parent is not CMyParent class. We are not interested.\");\n}\n static_cast GetParent() CMyParent CMyParent1 CMyParent2 SendMessage"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5665574/"
] |
74,585,233
|
<p>I am a backend developer so I need help with this front end part.</p>
<pre><code><input id="entered_value" type="number" name="entered_value">
<input id="entered_valuetwo" type="text" name="entered_valuetwo">
<select id="selected_value" name="selected_value"> <option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button type="button" id="send-data">Click me</button>
</code></pre>
<p>when the button is clicked its already triggering something I have in JS. But what is the best way to pass "entered_value" & "entered_valuetwo" & "selected_value" all 3 at the same time to the button and they get passed to the js function thereafter.</p>
|
[
{
"answer_id": 74585297,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 2,
"selected": true,
"text": "document.getElementById('send-data').addEventListener('click',buttonFunction)\nfunction buttonFunction(){\n\nlet enteredValue = document.getElementById('entered_value').value\nlet enteredValue2 = document.getElementById('entered_valuetwo').value\nlet selectValue = document.getElementById('selected_value').value\n\nconsole.log(enteredValue,enteredValue2,selectValue)\n\n} <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n<input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n<select id=\"selected_value\" name=\"selected_value\"> <option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>\n</select>\n<button type=\"button\" id=\"send-data\">Click me</button>"
},
{
"answer_id": 74585348,
"author": "Jannik Stach",
"author_id": 20469384,
"author_profile": "https://Stackoverflow.com/users/20469384",
"pm_score": 0,
"selected": false,
"text": "<form action=\"your url\" method=\"Post\">\n <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n <input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n <select id=\"selected_value\" name=\"selected_value\"> \n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n </select>\n <button type=\"button\" id=\"send-data\">Click me</button>\n</form>\n document.getElementby() document.querySelector(#)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19222846/"
] |
74,585,238
|
<p>I am trying to replicate the following graph from the paper, <a href="https://pubmed.ncbi.nlm.nih.gov/32834653/" rel="nofollow noreferrer">https://pubmed.ncbi.nlm.nih.gov/32834653/</a>.</p>
<p><a href="https://i.stack.imgur.com/Jdp0e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jdp0e.png" alt="enter image description here" /></a></p>
<p>Given below are the parameter values and the formula for the basic reproductive number.</p>
<pre><code>beta_s = 0.274
alpha_a = 0.4775
alpha_u = 0.695
mu = 0.062
gamma_a = 0.29
q_i = 0.078
1/eta_i = 0.009
1/eta_u = 0.05
R_0 = (beta_s*alpha_a)/(gamma_a+mu) + (beta_s*alpha_u*gamma_a*(1-q_i))/((gamma_a+mu)
(eta_u+mu))
</code></pre>
<p>I would be very much thankful, if someone could help me draw the graph using R or MATLAB. Thanks a lot in advance!</p>
|
[
{
"answer_id": 74585297,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 2,
"selected": true,
"text": "document.getElementById('send-data').addEventListener('click',buttonFunction)\nfunction buttonFunction(){\n\nlet enteredValue = document.getElementById('entered_value').value\nlet enteredValue2 = document.getElementById('entered_valuetwo').value\nlet selectValue = document.getElementById('selected_value').value\n\nconsole.log(enteredValue,enteredValue2,selectValue)\n\n} <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n<input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n<select id=\"selected_value\" name=\"selected_value\"> <option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>\n</select>\n<button type=\"button\" id=\"send-data\">Click me</button>"
},
{
"answer_id": 74585348,
"author": "Jannik Stach",
"author_id": 20469384,
"author_profile": "https://Stackoverflow.com/users/20469384",
"pm_score": 0,
"selected": false,
"text": "<form action=\"your url\" method=\"Post\">\n <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n <input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n <select id=\"selected_value\" name=\"selected_value\"> \n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n </select>\n <button type=\"button\" id=\"send-data\">Click me</button>\n</form>\n document.getElementby() document.querySelector(#)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557703/"
] |
74,585,257
|
<p>I am exporting a MySQL database on a windows machine (running XAMPP) to then import into a Linux server (using cmdline or phpMyAdmin IMPORT "filename.sql")
The dbdump file has mixed LF/CRLF line endings, and I know Linux uses LF for line endings.
Will this cause a problem?
Thanks</p>
|
[
{
"answer_id": 74585297,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 2,
"selected": true,
"text": "document.getElementById('send-data').addEventListener('click',buttonFunction)\nfunction buttonFunction(){\n\nlet enteredValue = document.getElementById('entered_value').value\nlet enteredValue2 = document.getElementById('entered_valuetwo').value\nlet selectValue = document.getElementById('selected_value').value\n\nconsole.log(enteredValue,enteredValue2,selectValue)\n\n} <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n<input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n<select id=\"selected_value\" name=\"selected_value\"> <option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>\n</select>\n<button type=\"button\" id=\"send-data\">Click me</button>"
},
{
"answer_id": 74585348,
"author": "Jannik Stach",
"author_id": 20469384,
"author_profile": "https://Stackoverflow.com/users/20469384",
"pm_score": 0,
"selected": false,
"text": "<form action=\"your url\" method=\"Post\">\n <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n <input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n <select id=\"selected_value\" name=\"selected_value\"> \n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n </select>\n <button type=\"button\" id=\"send-data\">Click me</button>\n</form>\n document.getElementby() document.querySelector(#)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210149/"
] |
74,585,284
|
<p>Given a dataframe of types and values like so:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>topic</th>
<th>keyword</th>
</tr>
</thead>
<tbody>
<tr>
<td>cheese</td>
<td>cheddar</td>
</tr>
<tr>
<td>meat</td>
<td>beef</td>
</tr>
<tr>
<td>meat</td>
<td>chicken</td>
</tr>
<tr>
<td>cheese</td>
<td>swiss</td>
</tr>
<tr>
<td>bread</td>
<td>focaccia</td>
</tr>
<tr>
<td>bread</td>
<td>sourdough</td>
</tr>
<tr>
<td>cheese</td>
<td>gouda</td>
</tr>
</tbody>
</table>
</div>
<p>My aim is to make a set of dynamic regexs based on the type, but I don't know how to make the variable names from the types. I can do this individually like so:</p>
<pre><code>fn_get_topic_regex <- function(targettopic,df)
{
filter_df <- df |>
filter(topic == targettopic)
regex <- paste(filter_df$keyword, collapse = "|")
}
</code></pre>
<p>and do things like:</p>
<p><code>cheese_regex <- fn_get_topic_regex("cheese",df)</code></p>
<p>But what I'd like to be able to do is build all these regexes automatically without having to define each one.</p>
<p>The intended output would be something like:</p>
<pre><code>cheese_regex: "cheddar|swiss|gouda"
bread_regex: "focaccia|sourdough"
meat_regex: "beef|chicken"
</code></pre>
<p>Where the start of the variable name is the distinct topic.</p>
<p>What's the best way to do that without defining each regex individually by hand?</p>
|
[
{
"answer_id": 74585297,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 2,
"selected": true,
"text": "document.getElementById('send-data').addEventListener('click',buttonFunction)\nfunction buttonFunction(){\n\nlet enteredValue = document.getElementById('entered_value').value\nlet enteredValue2 = document.getElementById('entered_valuetwo').value\nlet selectValue = document.getElementById('selected_value').value\n\nconsole.log(enteredValue,enteredValue2,selectValue)\n\n} <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n<input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n<select id=\"selected_value\" name=\"selected_value\"> <option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>\n</select>\n<button type=\"button\" id=\"send-data\">Click me</button>"
},
{
"answer_id": 74585348,
"author": "Jannik Stach",
"author_id": 20469384,
"author_profile": "https://Stackoverflow.com/users/20469384",
"pm_score": 0,
"selected": false,
"text": "<form action=\"your url\" method=\"Post\">\n <input id=\"entered_value\" type=\"number\" name=\"entered_value\">\n <input id=\"entered_valuetwo\" type=\"text\" name=\"entered_valuetwo\">\n <select id=\"selected_value\" name=\"selected_value\"> \n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n </select>\n <button type=\"button\" id=\"send-data\">Click me</button>\n</form>\n document.getElementby() document.querySelector(#)"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4337654/"
] |
74,585,292
|
<p>thanks ahead of time for your help... I'm relatively new to coding (especially JSON/JavaScript/jQuery) so forgive my imprecise terminologies and references.</p>
<p>I have a JSON/JavaScript enabled footer with the relevant JSON code below:</p>
<pre><code> footerOptions : {
'Old Website' : 'http://Link1.com',
'Illustration Site' : 'https://Link2.com',
'Blog Site' : '/'
</code></pre>
<p>The footerOptions variable is referenced in this backend JS code:</p>
<pre><code> var footerOptions = $('<div>', { id : 'ctd-footer-options' });
footerOptions.css({
position : 'relative',
zIndex : 100,
padding : '30px 10px 30px 0'
});
footerOptions.css(config.footerMenuOptionsStyle);
footerOptions.css({ backGroundColor : 'transparent' });
var footerOptionsHtml = '';
config.footerOptions[''] = '';
Object.keys(config.footerOptions).forEach((key, i) => {
var target = "window.location.href=\'"+config.footerOptions[key]+"\'";
if (key.substring(1,4) == 'svg' || key.substring(1,4) == 'SVG') {
target = "window.open(\'"+config.footerOptions[key]+"\', \'_blank\')";
}
footerOptionsHtml = footerOptionsHtml+'<div class="ctd-footer-option" onclick="'+target+'" style="cursor:pointer; float:left; margin-right:30px;">'+key+'</div>';
});
footerOptions.html(footerOptionsHtml);
footerContent.append(footerOptions);
</code></pre>
<p>...
My goal is to have the JSON links ('Old Website', 'Illustration Site', etc.) open themselves in new browser tabs. What would be the most efficient way to tweak the above code towards that goal?</p>
<p>Again, thanks very much to any and all contributors!</p>
<p>Charles</p>
<p>I tried plugging in the below code around the '+target+':</p>
<pre><code>onclick="window.open(this.href); return false;" onkeypress="window.open(this.href); return false;"
</code></pre>
<p>...to no avail. The links opens in the same tab alongside a blank tab.</p>
|
[
{
"answer_id": 74585451,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 1,
"selected": false,
"text": "footerOptionsHtml += \"<a href='\"+config.footerOptions[key]+\"' target='_blank'>\"+key+\"</a>\"\n"
},
{
"answer_id": 74587513,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 0,
"selected": false,
"text": "footerOptionsHtml += \"<a class='ctd-footer-option' href='\"+config.footerOptions[key]+\"' target='_blank'>\"+key+\"</a>\"\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20213961/"
] |
74,585,321
|
<p>For the commands:</p>
<pre><code>z=bye
z=hello echo $z
echo $z
</code></pre>
<p>I'm expecting to see:</p>
<pre><code>hello
bye
</code></pre>
<p>Instead, I'm seeing:</p>
<pre><code>bye
bye
</code></pre>
<p>According to the <a href="https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Simple-Command-Expansion" rel="nofollow noreferrer">man page</a> (emphasis mine):</p>
<blockquote>
<h3>3.7.1 Simple Command Expansion</h3>
<p>When a simple command is executed, the shell performs the following
expansions, assignments, and redirections, from left to right, in the
following order.</p>
<ol>
<li>The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later
processing.</li>
<li>The words that are not variable assignments or redirections are expanded (see Shell Expansions). If any words remain after expansion,
the first word is taken to be the name of the command and the
remaining words are the arguments.</li>
<li>Redirections are performed as described above (see Redirections).</li>
<li>The text after the ‘=’ in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic
expansion, and quote removal before being assigned to the variable.</li>
</ol>
<p>If no command name results, the variable assignments affect the
current shell environment. In the case of such a command (one that
consists only of assignment statements and redirections), assignment
statements are performed before redirections. <em><strong>Otherwise, the variables
are added to the environment of the executed command and do not affect
the current shell environment.</strong></em> If any of the assignments attempts to
assign a value to a readonly variable, an error occurs, and the
command exits with a non-zero status.</p>
</blockquote>
<p>So what am I doing wrong?</p>
|
[
{
"answer_id": 74585345,
"author": "Adrian",
"author_id": 1366368,
"author_profile": "https://Stackoverflow.com/users/1366368",
"pm_score": 1,
"selected": false,
"text": "fn() { echo $z; }\nz=bye\nz=hello fn\necho $z\n"
},
{
"answer_id": 74585491,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 3,
"selected": true,
"text": "z=hello echo $z z=hello echo bye z=hello echo bye bye z"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366368/"
] |
74,585,386
|
<p>Im doing a project in javascript with API from restCountries <a href="https://restcountries.com/#rest-countries-v3-vs-v31" rel="nofollow noreferrer">https://restcountries.com/#rest-countries-v3-vs-v31</a>
I want to create a forEach loop where I can loop through the result and create whats in the function showCountry() But I dont know what I should put before in the forEach loop? What can be relevant? Thanks in Advance!</p>
<pre><code>const countries = document.querySelector('.countries')
const lang = document.getElementById('search').value
const btn = document.getElementById('btn')
function getCountries(){
const search = document.querySelector('.search').value
fetch(`https://restcountries.com/v3.1/lang/${search}`,{
method: "GET",
})
.then((response) => response.json())
.then((data) => console.log(data));
??.forEach(api=> {
showCountry(api)
})
}
function showCountry(data){
const country = document.createElement('div')
country.classList.add('country')
country.innerHTML =
`<div class="country-img">
<img src="${data.flag}" alt="">
</div>
<div class="country-details">
<h5 class="countryName">${data.name}</h5>
<p><strong>Population:</strong>${data.population}</p>
<p><strong>SubRegion:</strong>${data.subregion}</p>
<p><strong>Capital:</strong>${data.capital}</p>
<p class="languageName"><strong>Language:</strong>${data.lang}</p>
</div>`
countries.appendChild(country)
}
</code></pre>
<p>Html;</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Countries</title>
</head>
<body>
<div class="container">
<h1>Search country by language!</h1>
</div>
<div class="container">
<div class="controls">
<i class="bx bx-search"></i>
<input type="text" placeholder="search by language.." id="search" class="search">
</div>
<button id="btn" onclick="getCountries()">Search Country</button>
</div>
<div class="countries">
</div>
<script src="script.js"></script>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74585407,
"author": "codinn.dev",
"author_id": 15755662,
"author_profile": "https://Stackoverflow.com/users/15755662",
"pm_score": 2,
"selected": true,
"text": "async function getCountries(){\n const search = document.querySelector('.search').value;\n const response = await fetch(`https://restcountries.com/v3.1/lang/${search}`,{\n method: \"GET\",\n });\n\n const data = await response.json();\n\n data.forEach(api=> {\n showCountry(api)\n })\n\n}\n then function getCountries(){\n const search = document.querySelector('.search').value\n fetch(`https://restcountries.com/v3.1/lang/${search}`,{\n method: \"GET\",\n })\n .then((response) => response.json())\n .then((data) => \n data.forEach(api=> {\n showCountry(api)\n })\n ); \n}\n data \nfunction showCountry(data){\n const country = document.createElement('div')\n country.classList.add('country')\n country.innerHTML =\n `<div class=\"country-img\">\n <img src=\"${data?.flags?.png}\" alt=\"\">\n </div>\n <div class=\"country-details\">\n <h5 class=\"countryName\">${data?.name?.common}</h5>\n <p><strong>Population:</strong>${data?.population}</p>\n <p><strong>SubRegion:</strong>${data?.subregion}</p>\n <p><strong>Capital:</strong>${data?.capital}</p>\n <p class=\"languageName\"><strong>Language:</strong>${data?.languages?.eng}</p>\n </div>`\n\n countries.appendChild(country)\n}\n"
},
{
"answer_id": 74585432,
"author": "Zidane Zine eddine",
"author_id": 20574632,
"author_profile": "https://Stackoverflow.com/users/20574632",
"pm_score": 0,
"selected": false,
"text": " fetch(`https://restcountries.com/v3.1/lang/${search}`,{\n method: \"GET\",\n })\n .then((response) => response.json())\n .then(data => {\n data.forEach(api => {\n showCountry(api)\n }\n });\n"
},
{
"answer_id": 74585918,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "for/loop map data.name name common official async/await flag common population // Cache the countries element\nconst countries = document.querySelector('.countries');\n\n// Fetch the data. If there's an error in the response throw it,\n// otherwise return the parsed JSON\nasync function getData() {\n const res = await fetch('https://restcountries.com/v3.1/all');\n if (!res.ok) throw new Error(`${res.status}: ${res.statusText}`);\n return res.json();\n}\n\n// Accepts the parsed JSON it `map` over that array\n// of objects, destructures the properties that will be\n// used in the HTML, and returns the HTML for that\n// object using a template string. Once the iteration is\n// complete join the array of strings `map` returns\n// into one single string\nfunction buildCountries(data) {\n return data.map(obj => {\n\n const {\n name: { common },\n population,\n flag\n } = obj;\n\n return `\n <section class=\"country\">\n <h4>${flag} ${common}</h4>\n <p>${population}</p>\n </section>\n `;\n\n }).join('');\n}\n\n// Get the data, get the HTML, and then add the HTML\nasync function main() {\n try {\n const data = await getData();\n const html = buildCountries(data);\n countries.insertAdjacentHTML('beforeend', html);\n } catch (err) {\n console.error(err.message);\n }\n}\n\nmain(); .country { background-color: #efefef; padding: 0.25em; border: 1px solid #dfdfdf; }\n.country:not(:last-child) { margin-bottom: 0.25em; }\nh4 { padding: 0; margin: 0; } <div class=\"countries\"></div> map insertAdjacentHTML"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224482/"
] |
74,585,390
|
<p>I have three tables:</p>
<ul>
<li><code>customer</code> (id, name, email)</li>
<li><code>product</code> (id, product_category, material, price, purchase_id)</li>
<li><code>purchase</code> (id, purchase_date, customer_id)</li>
</ul>
<p><strong>My task</strong>: show the name of the customer and the number of purchases they made - this column should be called purchase_count. Sort the results by number of purchases, starting with the customer with the most purchases.</p>
<p>Please note that some customers may not have made any purchases yet. In such a situation, you should display 0 for the number of purchases.</p>
<p>I am trying to create a view such as:</p>
<pre><code>name, purchase_count
</code></pre>
<p>This is my code so far. I don't think its correct:</p>
<pre><code>WITH CLIENTS_BUYS AS
(
SELECT -- (NULL FOR THE CLIENTS WHO HAVE NOT MADE PURCHASE SHOW AS '0' HAVE NOT BEEN SHOWN IN THIS QUERY)
CU.name, -- SO I TRIED TO USE 'CTE'
CU.id,
COUNT(CASE WHEN PU.id IS NOT NULL THEN PU.id ELSE CU.id END) AS PURCHASE_COUNT
FROM
purchase PU
JOIN
customer CU ON CU.id = PU.customer_id
JOIN
product PR ON PR.purchase_id = PU.id
WHERE
customer_id IS NOT NULL
OR customer_id IS NULL
GROUP BY
CU.name, CU.id
),
CLIENTS_NOT_BUYS AS
(
SELECT
CU.name,
CU.id,
COUNT(CASE WHEN PU.id IS NULL THEN PU.id ELSE CU.id END) AS PURCHASE_COUNT
FROM
purchase PU
JOIN
customer CU ON CU.id = PU.customer_id
JOIN
product PR ON PR.purchase_id = PU.id
WHERE
CU.id IN (SELECT customer_id
WHERE CU.id != PU.customer_id)
GROUP BY
CU.name, CU.id
)
SELECT
name,
PURCHASE_COUNT
FROM
CLIENTS_NOT_BUYS
JOIN
CLIENTS_BUYS ON CLIENTS_BUYS.id = CLIENTS_NOT_BUYS.id
GROUP BY
name
ORDER BY
PURCHASE_COUNT DESC
</code></pre>
<p>One issue is <code>purchase_id</code> in the <code>product</code> has <code>NULL</code> for one or some customers. But via join the customers who has NULL in <code>purchase_id</code> have not been presented in the first query.</p>
<p>So, I tried to use CTE but it seems not a working query and I think that I am doing it too difficult because there should be an easier way than I do. Also tried <code>LEFT JOIN</code> but it didn't work.</p>
<p>In the last part select. where I a, trying to join <code>CLIENTS_NOT_BUYS</code> and <code>CLIENTS_BUYS</code> => I get an error</p>
<blockquote>
<p>Errors near name and PURCHASE_COUNT<br />
Ambiguous column name</p>
</blockquote>
<p>I don't know how to make it work...</p>
<p>This is the result of first select inside the CTE <code>CLIENTS_BUYS</code> without <code>ORDER BY</code>:</p>
<pre><code>name id PURCHASE_COUNT
-----------------------------------
Alba Gomez 5 1
Amira Palmer 3 2
Anna Smith 7 2
Charlee Freeman 1 5
Christina Rivas 2 1
Michael Doe 6 2
</code></pre>
<p>But I don't know how to show others with NULL in purchase_id and add them at the bottom with '0' in PURCHASE_COUNT to continue the table</p>
|
[
{
"answer_id": 74585407,
"author": "codinn.dev",
"author_id": 15755662,
"author_profile": "https://Stackoverflow.com/users/15755662",
"pm_score": 2,
"selected": true,
"text": "async function getCountries(){\n const search = document.querySelector('.search').value;\n const response = await fetch(`https://restcountries.com/v3.1/lang/${search}`,{\n method: \"GET\",\n });\n\n const data = await response.json();\n\n data.forEach(api=> {\n showCountry(api)\n })\n\n}\n then function getCountries(){\n const search = document.querySelector('.search').value\n fetch(`https://restcountries.com/v3.1/lang/${search}`,{\n method: \"GET\",\n })\n .then((response) => response.json())\n .then((data) => \n data.forEach(api=> {\n showCountry(api)\n })\n ); \n}\n data \nfunction showCountry(data){\n const country = document.createElement('div')\n country.classList.add('country')\n country.innerHTML =\n `<div class=\"country-img\">\n <img src=\"${data?.flags?.png}\" alt=\"\">\n </div>\n <div class=\"country-details\">\n <h5 class=\"countryName\">${data?.name?.common}</h5>\n <p><strong>Population:</strong>${data?.population}</p>\n <p><strong>SubRegion:</strong>${data?.subregion}</p>\n <p><strong>Capital:</strong>${data?.capital}</p>\n <p class=\"languageName\"><strong>Language:</strong>${data?.languages?.eng}</p>\n </div>`\n\n countries.appendChild(country)\n}\n"
},
{
"answer_id": 74585432,
"author": "Zidane Zine eddine",
"author_id": 20574632,
"author_profile": "https://Stackoverflow.com/users/20574632",
"pm_score": 0,
"selected": false,
"text": " fetch(`https://restcountries.com/v3.1/lang/${search}`,{\n method: \"GET\",\n })\n .then((response) => response.json())\n .then(data => {\n data.forEach(api => {\n showCountry(api)\n }\n });\n"
},
{
"answer_id": 74585918,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "for/loop map data.name name common official async/await flag common population // Cache the countries element\nconst countries = document.querySelector('.countries');\n\n// Fetch the data. If there's an error in the response throw it,\n// otherwise return the parsed JSON\nasync function getData() {\n const res = await fetch('https://restcountries.com/v3.1/all');\n if (!res.ok) throw new Error(`${res.status}: ${res.statusText}`);\n return res.json();\n}\n\n// Accepts the parsed JSON it `map` over that array\n// of objects, destructures the properties that will be\n// used in the HTML, and returns the HTML for that\n// object using a template string. Once the iteration is\n// complete join the array of strings `map` returns\n// into one single string\nfunction buildCountries(data) {\n return data.map(obj => {\n\n const {\n name: { common },\n population,\n flag\n } = obj;\n\n return `\n <section class=\"country\">\n <h4>${flag} ${common}</h4>\n <p>${population}</p>\n </section>\n `;\n\n }).join('');\n}\n\n// Get the data, get the HTML, and then add the HTML\nasync function main() {\n try {\n const data = await getData();\n const html = buildCountries(data);\n countries.insertAdjacentHTML('beforeend', html);\n } catch (err) {\n console.error(err.message);\n }\n}\n\nmain(); .country { background-color: #efefef; padding: 0.25em; border: 1px solid #dfdfdf; }\n.country:not(:last-child) { margin-bottom: 0.25em; }\nh4 { padding: 0; margin: 0; } <div class=\"countries\"></div> map insertAdjacentHTML"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609076/"
] |
74,585,414
|
<p>I am getting this problem, any help will be appreciated, Im getting an arror trying to sign-in or sign-up.Error bellow.
AttributeError at /sign-up
'WSGIRequest' object has no attribute 'is_ajax' I know that function is depreciated now, but i can't seem to fix the issue.</p>
<p>mixins.py</p>
<pre><code>class AjaxFormMixin(object):
'''
Mixin to ajaxify django form - can be over written in view by calling form_valid method
'''
def form_invalid(self, form):
response = super(AjaxFormMixin, self).form_invalid(form)
if self.request.is_ajax():
message = FormErrors(form)
return JsonResponse({'result': 'Error', 'message': message})
return response
def form_valid(self, form):
response = super(AjaxFormMixin, self).form_valid(form)
if self.request.is_ajax():
form.save()
return JsonResponse({'result': 'Success', 'message': ""})
return response
</code></pre>
<p>views.py</p>
<pre><code>def profile_view(request):
'''
function view to allow users to update their profile
'''
user = request.user
up = user.userprofile
form = UserProfileForm(instance=up)
if request.is_ajax():
form = UserProfileForm(data=request.POST, instance=up)
if form.is_valid():
obj = form.save()
obj.has_profile = True
obj.save()
result = "Success"
message = "Your profile has been updated"
else:
message = FormErrors(form)
data = {'result': result, 'message': message}
return JsonResponse(data)
else:
context = {'form': form}
context['google_api_key'] = settings.GOOGLE_API_KEY
context['base_country'] = settings.BASE_COUNTRY
return render(request, 'users/profile.html', context)
class SignUpView(AjaxFormMixin, FormView):
'''
Generic FormView with our mixin for user sign-up with reCAPTURE security
'''
template_name = "users/sign_up.html"
form_class = UserForm
success_url = "/"
# reCAPTURE key required in context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["recaptcha_site_key"] = settings.RECAPTCHA_PUBLIC_KEY
return context
# over write the mixin logic to get, check and save reCAPTURE score
def form_valid(self, form):
response = super(AjaxFormMixin, self).form_valid(form)
if self.request.is_ajax():
token = form.cleaned_data.get('token')
captcha = reCAPTCHAValidation(token)
if captcha["success"]:
obj = form.save()
obj.email = obj.username
obj.save()
up = obj.userprofile
up.captcha_score = float(captcha["score"])
up.save()
login(self.request, obj,
backend='django.contrib.auth.backends.ModelBackend')
# change result & message on success
result = "Success"
message = "Thank you for signing up"
data = {'result': result, 'message': message}
return JsonResponse(data)
return response
class SignInView(AjaxFormMixin, FormView):
'''
Generic FormView with our mixin for user sign-in
'''
template_name = "users/sign_in.html"
form_class = AuthForm
success_url = "/"
def form_valid(self, form):
response = super(AjaxFormMixin, self).form_valid(form)
if self.request.is_ajax():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
# attempt to authenticate user
user = authenticate(
self.request, username=username, password=password)
if user is not None:
login(self.request, user,
backend='django.contrib.auth.backends.ModelBackend')
result = "Success"
message = 'You are now logged in'
else:
message = FormErrors(form)
data = {'result': result, 'message': message}
return JsonResponse(data)
return response
</code></pre>
<p>I know there's a <a href="https://stackoverflow.com/questions/70419441/attributeerror-wsgirequest-object-has-no-attribute-is-ajax">post with similar issue</a>, but I'm kinda struggling to fix it on my end.
<a href="https://i.stack.imgur.com/WxQQg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxQQg.png" alt="screenshot" /></a></p>
|
[
{
"answer_id": 74585495,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 1,
"selected": false,
"text": ".is_ajax() HttpRequest.is_ajax() HttpRequest.accepts() def is_ajax():\n return request.headers.get('x-requested-with') == 'XMLHttpRequest'\n .accepts(…) self.request.accepts('application/json')\n self.request.accepts('application/xml')\n"
},
{
"answer_id": 74585509,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 2,
"selected": false,
"text": "if request.headers.get('x-requested-with') == 'XMLHttpRequest': def profile_view(request):\n '''\n function view to allow users to update their profile\n '''\n user = request.user\n up = user.userprofile\n\n form = UserProfileForm(instance=up)\n\n if request.headers.get('x-requested-with') == 'XMLHttpRequest':\n form = UserProfileForm(data=request.POST, instance=up)\n if form.is_valid():\n obj = form.save()\n obj.has_profile = True\n obj.save()\n result = \"Success\"\n message = \"Your profile has been updated\"\n else:\n message = FormErrors(form)\n data = {'result': result, 'message': message}\n return JsonResponse(data)\n\n else:\n\n context = {'form': form}\n context['google_api_key'] = settings.GOOGLE_API_KEY\n context['base_country'] = settings.BASE_COUNTRY\n\n return render(request, 'users/profile.html', context)\n if self.request.headers.get('x-requested-with') == 'XMLHttpRequest':"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18923388/"
] |
74,585,438
|
<p>Hello and thank you for reading. I have written a program to reverse the words in a string using a stack. I am to use 3 sentences and reverse each sentence separately. I have been able to reverse the entire string, which wasn't an issue. Then I changed my program so I am reading to the period and reversing the first sentence. However, I can't get it to read the next sentence. I believe I need a second loop but this is where I struggle. There are several questions/answers on this site that address this assignment, but none that have really taken the approach I have so they aren't relevant. At least, not from what I can tell. This is what I have:</p>
<pre><code>for (String word : wordArray) {
if (word.endsWith(".") {
Stack.push(word.substring(0, word.length()-1));
break;
}
else {
Stack.push(word);
}
}
</code></pre>
<p>So my sentences are: "Cats are cool. Dogs are cool. So are turtles." My program will print:
"cool are Cats"
I know I need to append a period and I can figure that out later. I'm just struggling with how to create a second loop to continue reading the rest of the string.
What I need is: "cool are Cats. cool are Dogs. turtles are So."</p>
|
[
{
"answer_id": 74585464,
"author": "S. Miller",
"author_id": 3681614,
"author_profile": "https://Stackoverflow.com/users/3681614",
"pm_score": 0,
"selected": false,
"text": "Stack<String> wordStack = new Stack<String>(); wordStack,"
},
{
"answer_id": 74585595,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 3,
"selected": true,
"text": "ArrayList StringBuilder StringBuilder while StringJoiner StringJoiner StringJoiner StringBuilder public static String reverseSentences(String[] wordArray) {\n Stack<String> stack = new Stack<>();\n StringBuilder reversedSentences = new StringBuilder();\n \n for (String word : wordArray) {\n if (word.endsWith(\".\")) {\n \n stack.push(word.substring(0, word.length() - 1));\n \n reversedSentences\n .append(createSentence(stack)) // appending the reversed sentence\n .append(\". \"); // adding a period and a white space at the end of the sentence\n\n } else {\n stack.push(word);\n }\n }\n return reversedSentences.toString();\n}\n\npublic static String createSentence(Stack<String> stack) {\n StringJoiner sentence = new StringJoiner(\" \"); // white space would be used a delimiter between the words\n while (!stack.isEmpty()) {\n sentence.add(stack.pop());\n }\n return sentence.toString();\n}\n main() public static void main(String[] args) {\n System.out.println(reverseSentences(\"Cats are cool. Dogs are cool. So are turtles.\".split(\" \")));\n}\n cool are Cats. cool are Dogs. turtles are So.\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400438/"
] |
74,585,441
|
<pre class="lang-none prettyprint-override"><code>ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.
01:16:25.288 [Client thread] ERROR net.minecraft.client.resources.ResourceIndex - Can't find the resource index file: assets\indexes\1.12.json
Exception in thread "Client thread"
Process finished with exit code 1
</code></pre>
<p>I do not know what to do</p>
|
[
{
"answer_id": 74585457,
"author": "SwagiWagi",
"author_id": 9545837,
"author_profile": "https://Stackoverflow.com/users/9545837",
"pm_score": 1,
"selected": false,
"text": "StatusLogger.level Trace"
},
{
"answer_id": 74585532,
"author": "Hiran Chaudhuri",
"author_id": 4222206,
"author_profile": "https://Stackoverflow.com/users/4222206",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Configuration status=\"WARN\">\n <Appenders>\n <Console name=\"Console\" target=\"SYSTEM_OUT\">\n <PatternLayout pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger - %msg%n\"/>\n </Console>\n </Appenders>\n <Loggers>\n <Root level=\"trace\">\n <AppenderRef ref=\"Console\"/>\n </Root>\n </Loggers>\n</Configuration>\n"
},
{
"answer_id": 74606062,
"author": "NoDataFound",
"author_id": 1023553,
"author_profile": "https://Stackoverflow.com/users/1023553",
"pm_score": 0,
"selected": false,
"text": "Can't find the resource index file: assets\\indexes\\1.12.json\nException in thread \"Client thread\" \nProcess finished with exit code 1\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609472/"
] |
74,585,481
|
<p>I'm making exploding barrels in Unity and using Physics.OverlapSphere to detect nearby rigidbodies and other exploding barrels. This is to move and trigger other exploding barrels to explode. The issue is when I'm using OverlapSphere in the triggered barrels it's accessing the previous barrel that triggered it which is destroyed, and I'm not entirely sure how.</p>
<p><a href="https://i.stack.imgur.com/6HOmJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6HOmJ.png" alt="enter image description here" /></a></p>
<p>This is error it gives me on line 67, where it says. <code>colliders = Physics.OverlapSphere(transform.position ,explosionRadius);</code></p>
<pre><code>IEnumerator explode(bool exploLag)
{
alreadyExploded = true;
//moved the yield to the beginning
//overlapsphere was finding barrels which were destroyed on the previous frame and then trying to access them causing errors
if (exploLag == true)
{
yield return new WaitForSeconds(explodeLag);
Debug.Log("exploding later on due to explosion lag");
}
Debug.Log("explode was called");
List<GameObject> existingBarrels = new List<GameObject>();
Debug.Log("calm1");
Collider[] colliders;
colliders = Physics.OverlapSphere(transform.position ,explosionRadius);
Debug.Log("Calm2");
Rigidbody exploRB;
foreach (Collider hit in colliders)
{
Debug.Log(hit);
if (hit.GetComponent<Rigidbody>() == null)
{
Debug.Log("no rigidbody - cringe");
}
else if (hit.GetComponent<explosiveBarrel>() != null)
{
if (hit.GetComponent<explosiveBarrel>().alreadyExploded == true)
{
Debug.Log("Exploding barrel has already been made to explode");
//so it doesnt try to explode it again and remove it
//will add an explosion force though so that its effected by the blast of this explosion also.
//exploRB = hit.GetComponent<Rigidbody>();
//exploRB.AddExplosionForce(explosionForce, explosionPos, explosionRadius, 1f, ForceMode.Impulse);
}
else
{
Debug.Log("ooo an existing barrel - ill save you later hehe uwu");
//another barrel has been detected will be exploded on the next frame
//this is too avoid it referencing this barrel aswell
existingBarrels.Add(hit.gameObject);
exploRB = hit.GetComponent<Rigidbody>();
exploRB.AddExplosionForce(explosionForce, transform.position, explosionRadius, 1f, ForceMode.Impulse);
}
}
else if (hit == null)
{
Debug.Log("Object doesnt exist anymore");
}
else
{
exploRB = hit.GetComponent<Rigidbody>();
exploRB.AddExplosionForce(explosionForce, transform.position, explosionRadius, 1f, ForceMode.Impulse);
Debug.Log("I moved a non exploding object");
}
}
foreach (GameObject explosiveB in existingBarrels)
{
explosiveB.GetComponent<explosiveBarrel>().StartCoroutine(explode(true));
}
ps.Play();
Destroy(gameObject);
Debug.Log("explode pog");
yield return null;
}
</code></pre>
<p>My apologies for just flooding my question with my code but I have no idea what's really wrong.</p>
|
[
{
"answer_id": 74586169,
"author": "Deleted",
"author_id": 585968,
"author_profile": "https://Stackoverflow.com/users/585968",
"pm_score": 1,
"selected": false,
"text": "explode alreadyExploded existingBarrels if (hit.GetComponent<explosiveBarrel>().alreadyExploded == true) \n{\n .\n .\n .\n}\nelse\n{\n .\n .\n .\n existingBarrels.Add(hit.gameObject);\n .\n .\n .\n}\n BarrelStates // alreadyExploded is insufficent to protect against duplicate explosions \nenum BarrelStates\n{\n Idle,\n Exploding,\n Exploded\n}\n\nIEnumerator explode(bool exploLag)\n{\n if (State != Exploding) // <-------- new guard to prevent duplicate destruction\n yield break;\n\n \n foreach (Collider hit in colliders)\n {\n var barrel = hit.GetComponent<explosiveBarrel>();\n\n // Don't explode a barrel already in the process of exploding\n if (barrel != null && !barrel.State == States.Idle ) \n { \n barrel.State = States.Exploding; // <---- new\n exploRB = hit.GetComponent<Rigidbody>();\n exploRB.AddExplosionForce(explosionForce, transform.position, explosionRadius, 1f, ForceMode.Impulse);\n\n }\n }\n\n State = States.Exploded; // Finally, set exploded state\n\n ps.Play();\n Destroy(gameObject); \n Debug.Log(\"explode pog\");\n yield return null;\n}\n static Pen Brush Font Disposed"
},
{
"answer_id": 74587618,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 0,
"selected": false,
"text": "OverlapSphere explode Destroy foreach (GameObject explosiveB in existingBarrels)\n{\n // This next line is telling the OTHER component/class to use THIS instance of 'explode'.\n explosiveB.GetComponent<explosiveBarrel>().StartCoroutine(explode(true));\n}\n public class explosiveBarrel : MonoBehaviour\n{\n [SerializeField] private float explosionRadius;\n [SerializeField] private float explodeLag = 0.5f;\n [SerializeField] private float explosionForce;\n [SerializeField] private float explodedSnuffLife = 2;\n\n public bool alreadyExploded { get; private set; }\n\n\n // A public facing method to start the 'explode' coroutine on this object.\n public void Explode ( )\n {\n StartCoroutine ( explode ( true ) );\n }\n\n // The internal 'coroutine' to delay the explosion.\n private IEnumerator explode ( bool lag )\n {\n alreadyExploded = true;\n\n if ( lag )\n {\n Debug.Log ( \"exploding later on due to explosion lag\" );\n yield return new WaitForSeconds ( explodeLag );\n }\n\n foreach ( var hit in Physics.OverlapSphere ( transform.position, explosionRadius ) )\n {\n Debug.Log ( hit );\n\n if ( !hit.TryGetComponent<Rigidbody> ( out var rb ) )\n {\n Debug.Log ( $\"Item didn't have an RB. [{hit.gameObject.name}]\" );\n continue;\n }\n\n if ( hit.TryGetComponent<explosiveBarrel> ( out var eb ) )\n {\n // The hit target is a 'explosiveBarrel'. If not already exploded, call the public Explode method on that object.\n if ( !eb.alreadyExploded )\n eb.Explode ( );\n }\n\n // Add the explosion force to the object, regardless of whether or not it's an 'explosiveBarrel'\n ps.Play ( );\n rb.AddExplosionForce ( explosionForce, transform.position, explosionRadius, 1f, ForceMode.Impulse );\n }\n\n // wait 'explodedSnuffLife' seconds, then destroy this object.\n yield return new WaitForSeconds ( explodedSnuffLife );\n Destroy ( gameObject );\n }\n}\n Explode explosiveBarrel IExplodeable"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8264461/"
] |
74,585,507
|
<p>I've started using react native with expo not long ago so I am a bit lost.</p>
<p>When trying to build the application with the command:</p>
<pre><code>eas build --profile development --platform android
</code></pre>
<p>The build fails when it reaches the install dependencies part</p>
<pre><code>Running "npm install" in the root dir of your repository 2[stderr] npm ERR! code ERESOLVE3[stderr] npm ERR!4[stderr] ERESOLVE could not resolve5[stderr] npm ERR! 6[stderr] npm ERR!7[stderr] While resolving: @react-native-firebase/auth@16.2.08[stderr] npm ERR! Found: @react-native-firebase/app@15.4.09[stderr] npm ERR! node_modules/@react-native-firebase/app10[stderr] npm ERR! @react-native-firebase/app@"~15.4.0" from the root project11[stderr] npm ERR! 12[stderr] npm ERR! Could not resolve dependency:13[stderr] npm ERR! peer @react-native-firebase/app@"16.2.0" from @react-native-firebase/auth@16.2.014[stderr] npm ERR! node_modules/@react-native-firebase/auth15[stderr] npm ERR! @react-native-firebase/auth@"^16.2.0" from the root project16[stderr] npm17[stderr] ERR! 18[stderr] npm ERR! Conflicting peer dependency: @react-native-firebase/app@16.2.019[stderr] npm ERR! node_modules/@react-native-firebase/app20[stderr] npm ERR! peer @react-native-firebase/app@"16.2.0" from @react-native-firebase/auth@16.2.021[stderr] npm ERR! node_modules/@react-native-firebase/auth22[stderr] npm ERR! @react-native-firebase/auth@"^16.2.0" from the root project23[stderr] npm ERR! 24[stderr] npm ERR! Fix the upstream dependency conflict, or retry25[stderr] npm ERR! this command with --force, or --legacy-peer-deps26[stderr] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.27[stderr] npm ERR! 28[stderr] npm ERR! See /home/expo/.npm/eresolve-report.txt for a full report.29[stderr] 30[stderr] npm ERR! A complete log of this run can be found in:31[stderr] npm ERR! /home/expo/.npm/_logs/2022-11-26T18_50_07_398Z-debug-0.log32npm exited with non-zero code: 1
</code></pre>
<p>I have tried clearing the cache and rebuilding the app. When I try <code>npx expo start --dev-client</code> the app works fine.</p>
<p>This is my <code>package.json</code>:</p>
<pre><code>{
"name": "wallet",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web"
},
"dependencies": {
"@react-native-firebase/app": "~15.4.0",
"@react-native-firebase/auth": "^16.2.0",
"@react-native-google-signin/google-signin": "^8.0.1",
"@react-navigation/bottom-tabs": "^6.4.0",
"@react-navigation/drawer": "^6.5.0",
"@react-navigation/material-top-tabs": "^6.3.0",
"@react-navigation/native": "^6.0.13",
"@react-navigation/native-stack": "^6.9.1",
"@rneui/base": "^4.0.0-rc.7",
"@rneui/themed": "^4.0.0-rc.7",
"expo": "~46.0.16",
"expo-dev-client": "~1.3.1",
"expo-font": "~10.2.0",
"expo-linear-gradient": "~11.4.0",
"expo-local-authentication": "~12.3.0",
"expo-status-bar": "~1.4.0",
"formik": "^2.2.9",
"moment": "^2.29.4",
"react": "18.0.0",
"react-native": "0.69.6",
"react-native-gesture-handler": "~2.5.0",
"react-native-icon-badge": "^1.1.3",
"react-native-linear-gradient": "^2.6.2",
"react-native-pager-view": "^5.4.24",
"react-native-reanimated": "~2.9.1",
"react-native-recaptcha-that-works": "^1.3.2",
"react-native-safe-area-context": "^4.3.1",
"react-native-screens": "~3.15.0",
"react-native-tab-view": "^3.3.0",
"react-native-webview": "11.23.0",
"styled-components": "^5.3.6"
},
"devDependencies": {
"@babel/core": "^7.12.9"
},
"private": true
}
</code></pre>
|
[
{
"answer_id": 74590302,
"author": "Kaosc",
"author_id": 14104131,
"author_profile": "https://Stackoverflow.com/users/14104131",
"pm_score": 1,
"selected": false,
"text": "yarn install"
},
{
"answer_id": 74603893,
"author": "Sapir",
"author_id": 19353780,
"author_profile": "https://Stackoverflow.com/users/19353780",
"pm_score": 1,
"selected": true,
"text": "node_modules rm -rf node_modules. expo doctor --fix dependencies."
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19353780/"
] |
74,585,512
|
<p>I am trying to solve the following problem using Scipy. However, it doesn't produce the correct result.</p>
<p><a href="https://i.stack.imgur.com/Wjdy0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wjdy0.png" alt="Problem formulation" /></a></p>
<p><code>r</code> is the only decision variable that we have. Since the equation (2) doesn't follow the Scipy's required format of <code>Ab <= ub</code> I modified to the following form.</p>
<p><a href="https://i.stack.imgur.com/sLvIw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sLvIw.png" alt="enter image description here" /></a></p>
<p>Following is my implemented code:</p>
<pre><code># Objective function
def objective():
return [time[e] for e in edge]
# setting the bounds for the decision variables
def bounds():
return [(0, V[e[0]]) for e in edge]
# generating the constraints
def constraints():
b = []
A = []
const = []
const_2 = []
for i in region:
for e in edge:
if e[0] != e[1] and (e[0]==i or e[1]==i):
if (e[0]==i):
const.append(1)
const_2.append(1)
else:
const.append(-1)
const_2.append(0)
else:
const.append(0)
const_2.append(0)
# const 1 \sum (r_{ij} - r_{ji}) \leq V_i - D_i
A.append(const)
b.append(V[i] - D[i])
# const 2 \sum r_{ij} <= V_i
A.append(const_2)
b.append(V[i])
const = []
const_2 = []
return A, b
obj_fn = objective()
a_up, b_up = constraints()
res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())
</code></pre>
<p>When I run the code it prodeces the following result for each edge i.e., <code>r_e</code>:</p>
<pre><code>{(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}
</code></pre>
<p>However, it is not equal to the result produced by CPLEX (The cplex result is the correct one which I use to compare my results to):</p>
<pre><code>{(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}
</code></pre>
<p>I am not sure, but I think the problem is with the constraints. Can someone help me to find out what my mistake is here please?</p>
<hr />
<p>The minimum required data to run the code:</p>
<pre><code>V = {0: 1, 1: 71, 2: 6, 3: 0, 4: 34, 5: 51, 6: 88, 7: 61, 8: 0, 9: 0, 10: 43, 11: 62, 12: 144, 13: 36, 14: 0, 15: 12}
D = {0: 94, 1: 16, 2: 38, 3: 6, 4: 66, 5: 22, 6: 134, 7: 8, 8: 46, 9: 6, 10: 3, 11: 36, 12: 39, 13: 26, 14: 40, 15: 22}
edge = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15), (1, 0), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (3, 0), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (3, 14), (3, 15), (4, 0), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (5, 13), (5, 14), (5, 15), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 8), (7, 9), (7, 10), (7, 11), (7, 12), (7, 13), (7, 14), (7, 15), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 9), (8, 10), (8, 11), (8, 12), (8, 13), (8, 14), (8, 15), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 10), (9, 11), (9, 12), (9, 13), (9, 14), (9, 15), (10, 0), (10, 1), (10, 2), (10, 3), (10, 4), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 11), (10, 12), (10, 13), (10, 14), (10, 15), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10), (11, 12), (11, 13), (11, 14), (11, 15), (12, 0), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5), (12, 6), (12, 7), (12, 8), (12, 9), (12, 10), (12, 11), (12, 13), (12, 14), (12, 15), (13, 0), (13, 1), (13, 2), (13, 3), (13, 4), (13, 5), (13, 6), (13, 7), (13, 8), (13, 9), (13, 10), (13, 11), (13, 12), (13, 14), (13, 15), (14, 0), (14, 1), (14, 2), (14, 3), (14, 4), (14, 5), (14, 6), (14, 7), (14, 8), (14, 9), (14, 10), (14, 11), (14, 12), (14, 13), (14, 15), (15, 0), (15, 1), (15, 2), (15, 3), (15, 4), (15, 5), (15, 6), (15, 7), (15, 8), (15, 9), (15, 10), (15, 11), (15, 12), (15, 13), (15, 14)]
region = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
time = {(0, 1): 1, (0, 2): 1, (0, 3): 2, (0, 4): 2, (0, 5): 2, (0, 6): 2, (0, 7): 3, (0, 8): 3, (0, 9): 3, (0, 10): 3, (0, 11): 4, (0, 12): 4, (0, 13): 3, (0, 14): 4, (0, 15): 5, (1, 0): 1, (1, 2): 1, (1, 3): 1, (1, 4): 2, (1, 5): 2, (1, 6): 2, (1, 7): 3, (1, 8): 3, (1, 9): 3, (1, 10): 3, (1, 11): 4, (1, 12): 4, (1, 13): 3, (1, 14): 4, (1, 15): 4, (2, 0): 2, (2, 1): 1, (2, 3): 1, (2, 4): 3, (2, 5): 2, (2, 6): 2, (2, 7): 2, (2, 8): 4, (2, 9): 3, (2, 10): 3, (2, 11): 3, (2, 12): 5, (2, 13): 4, (2, 14): 4, (2, 15): 4, (3, 0): 2, (3, 1): 2, (3, 2): 1, (3, 4): 3, (3, 5): 3, (3, 6): 2, (3, 7): 2, (3, 8): 4, (3, 9): 4, (3, 10): 3, (3, 11): 3, (3, 12): 5, (3, 13): 5, (3, 14): 5, (3, 15): 4, (4, 0): 2, (4, 1): 2, (4, 2): 2, (4, 3): 3, (4, 5): 1, (4, 6): 2, (4, 7): 2, (4, 8): 2, (4, 9): 2, (4, 10): 2, (4, 11): 3, (4, 12): 2, (4, 13): 3, (4, 14): 3, (4, 15): 4, (5, 0): 2, (5, 1): 2, (5, 2): 2, (5, 3): 2, (5, 4): 1, (5, 6): 2, (5, 7): 2, (5, 8): 2, (5, 9): 2, (5, 10): 2, (5, 11): 3, (5, 12): 3, (5, 13): 2, (5, 14): 3, (5, 15): 3, (6, 0): 2, (6, 1): 2, (6, 2): 2, (6, 3): 2, (6, 4): 2, (6, 5): 1, (6, 7): 1, (6, 8): 3, (6, 9): 2, (6, 10): 2, (6, 11): 2, (6, 12): 3, (6, 13): 3, (6, 14): 3, (6, 15): 3, (7, 0): 3, (7, 1): 3, (7, 2): 2, (7, 3): 2, (7, 4): 2, (7, 5): 2, (7, 6): 2, (7, 8): 3, (7, 9): 3, (7, 10): 2, (7, 11): 2, (7, 12): 4, (7, 13): 4, (7, 14): 3, (7, 15): 3, (8, 0): 3, (8, 1): 3, (8, 2): 3, (8, 3): 3, (8, 4): 1, (8, 5): 2, (8, 6): 3, (8, 7): 3, (8, 9): 2, (8, 10): 2, (8, 11): 2, (8, 12): 1, (8, 13): 2, (8, 14): 2, (8, 15): 3, (9, 0): 3, (9, 1): 3, (9, 2): 3, (9, 3): 4, (9, 4): 2, (9, 5): 2, (9, 6): 2, (9, 7): 3, (9, 8): 2, (9, 10): 2, (9, 11): 2, (9, 12): 2, (9, 13): 1, (9, 14): 2, (9, 15): 2, (10, 0): 4, (10, 1): 3, (10, 2): 3, (10, 3): 3, (10, 4): 3, (10, 5): 2, (10, 6): 2, (10, 7): 2, (10, 8): 2, (10, 9): 2, (10, 11): 2, (10, 12): 2, (10, 13): 2, (10, 14): 2, (10, 15): 2, (11, 0): 4, (11, 1): 4, (11, 2): 3, (11, 3): 2, (11, 4): 3, (11, 5): 3, (11, 6): 2, (11, 7): 2, (11, 8): 2, (11, 9): 2, (11, 10): 2, (11, 12): 2, (11, 13): 3, (11, 14): 2, (11, 15): 1, (12, 0): 3, (12, 1): 4, (12, 2): 4, (12, 3): 4, (12, 4): 2, (12, 5): 3, (12, 6): 3, (12, 7): 4, (12, 8): 1, (12, 9): 2, (12, 10): 2, (12, 11): 3, (12, 13): 1, (12, 14): 2, (12, 15): 2, (13, 0): 5, (13, 1): 3, (13, 2): 4, (13, 3): 5, (13, 4): 3, (13, 5): 3, (13, 6): 3, (13, 7): 3, (13, 8): 2, (13, 9): 2, (13, 10): 2, (13, 11): 2, (13, 12): 2, (13, 14): 1, (13, 15): 2, (14, 0): 5, (14, 1): 4, (14, 2): 4, (14, 3): 4, (14, 4): 3, (14, 5): 3, (14, 6): 3, (14, 7): 3, (14, 8): 2, (14, 9): 2, (14, 10): 2, (14, 11): 2, (14, 12): 2, (14, 13): 1, (14, 15): 1, (15, 0): 5, (15, 1): 5, (15, 2): 4, (15, 3): 4, (15, 4): 4, (15, 5): 3, (15, 6): 3, (15, 7): 3, (15, 8): 3, (15, 9): 2, (15, 10): 2, (15, 11): 2, (15, 12): 2, (15, 13): 2, (15, 14): 2}
</code></pre>
|
[
{
"answer_id": 74585934,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())\n obj_fn Objetc()"
},
{
"answer_id": 74590796,
"author": "foglerit",
"author_id": 189418,
"author_profile": "https://Stackoverflow.com/users/189418",
"pm_score": 2,
"selected": true,
"text": "S_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nS_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nsum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex])\n\n> True\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15816775/"
] |
74,585,521
|
<pre><code>const myElement = document.createElement("div");
let selectItems = data.map((select, i) => (
`<div class="select">
<div aria-required="true" class="selectBtn" data-type="">${select.placeholder}</div>
<div class="selectDropdown">${select.option.map(el =>
`<div class="option" data-type="firstOption">${el}</div>`
).join('')}
</div>
</div>`)
)
const eles = document.getElementsByClassName("select");
for (let i = 0; i < eles.length; i++) {
myElement.innerHTML = selectItems[i]; ///loop
eles[i].appendChild(myElement.cloneNode(true));
}
</code></pre>
<p>I'm trying to add elements through a loop but an infinite loop occurs</p>
|
[
{
"answer_id": 74585934,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())\n obj_fn Objetc()"
},
{
"answer_id": 74590796,
"author": "foglerit",
"author_id": 189418,
"author_profile": "https://Stackoverflow.com/users/189418",
"pm_score": 2,
"selected": true,
"text": "S_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nS_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nsum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex])\n\n> True\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20606965/"
] |
74,585,524
|
<p>I have a long array and a long string</p>
<p>I want to find out if part of that string exists in that array</p>
<p>ex:-</p>
<pre><code>String[] array = [.....];
String url="https://stackoverflow.com/ques........ ";
//find if url contain any string elements of array
</code></pre>
<p>tried bunch of things but cant figure out how to do it</p>
|
[
{
"answer_id": 74585934,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())\n obj_fn Objetc()"
},
{
"answer_id": 74590796,
"author": "foglerit",
"author_id": 189418,
"author_profile": "https://Stackoverflow.com/users/189418",
"pm_score": 2,
"selected": true,
"text": "S_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nS_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nsum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex])\n\n> True\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578525/"
] |
74,585,534
|
<p>I'm trying to get the result below running 2 threads alternately. *Thread <code>A</code> prints <code>Step 1</code> and <code>Step 3</code> and thread <code>B</code> prints <code>Step 2</code> and <code>Step 4</code> (I use <strong>Python 3.8.5</strong>):</p>
<pre class="lang-none prettyprint-override"><code>Step 1
Step 2
Step 3
Step 4
</code></pre>
<p>So, with global variables, locks and while statements, I created the code below to try to get the result above:</p>
<pre class="lang-py prettyprint-override"><code>import threading
lock = threading.Lock()
flow = "Step 1"
def test1():
global flow
while True:
while True:
if flow == "Step 1":
lock.acquire()
print(flow)
flow = "Step 2"
lock.release()
break
while True:
if flow == "Step 3":
lock.acquire()
print(flow)
flow = "Step 4"
lock.release()
break
break
def test2():
global flow
while True:
while True:
if flow == "Step 2":
lock.acquire()
print(flow)
flow = "Step 3"
lock.release()
break
while True:
if flow == "Step 4":
lock.acquire()
print(flow)
lock.release()
break
break
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()
</code></pre>
<p>But, the code above got the result below without <code>Step 3</code> and <code>Step 4</code>, then the program kept running without completed. *Thread <code>A</code> printed <code>Step 1</code>, then thread <code>B</code> printed <code>Step 2</code>, then the program kept running without printing <code>Step 3</code> and <code>Step 4</code>:</p>
<pre class="lang-none prettyprint-override"><code>Step 1
Step 2
</code></pre>
<p>I couldn't find any mistakes so how can I get the proper result with <code>Step 3</code> and <code>Step 4</code>? And, why did I get the result without <code>Step 3</code> and <code>Step 4</code>?</p>
|
[
{
"answer_id": 74585934,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())\n obj_fn Objetc()"
},
{
"answer_id": 74590796,
"author": "foglerit",
"author_id": 189418,
"author_profile": "https://Stackoverflow.com/users/189418",
"pm_score": 2,
"selected": true,
"text": "S_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nS_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nsum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex])\n\n> True\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8172439/"
] |
74,585,579
|
<p>i have a txt file which i got from zoom api. I want to transform it to a dataframe for later cleaning. But there is a column that comes with curly braces, it doesn't read it like a dictionary</p>
<pre><code>open = pd.read_csv("registrados111.txt", sep = " ")
open.columns = ["page_size","total_records","next_page_token","registrants"]
open.head(1)
</code></pre>
<p><a href="https://i.stack.imgur.com/Qgj4t.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><strong>strong text</strong></p>
<p>I want to be able to clean up that smear, but it won't allow me the square brackets. when I select what type is the dataframe I get pandas.core.frame.DataFrame. and when I only select the "registrants" column I get pandas.core.series.Series</p>
<p>I would like to have an idea of how to display that column in several others. Because I have more than 6000 thousand records that appear like this.</p>
<p>The output should be a dataframe like in the image</p>
<p><a href="https://i.stack.imgur.com/6emXn.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I've thought about using methods like explode or using split to cut it but it doesn't allow me to read the subscripts it generates later.</p>
<pre><code>df = pd.DataFrame(union['registrants']).explode('custom_questions').reset_index(drop=True)
</code></pre>
<pre><code>pe= pd.json_normalize(json.loads(ap.explode("custom_questions").to_json(orient="records")))
</code></pre>
<p>I would really appreciate anyone who could help me or give me a guide.</p>
<p>These are some records that I get from the txt file</p>
<p>300 6139 4D1YdjmRScmpymp "{'id': '6ciHOSm4Rw', 'first_name': 'yumi', 'last_name': 'napanga', 'email': 'yu@hotmail.com', 'address': '', 'city': '', 'country': 'PE', 'zip': '', 'state': '', 'phone': '', 'industry': '', 'org': '', 'job_title': '', 'purchasing_time_frame': '', 'role_in_purchase_process': '', 'no_of_employees': '', 'comments': '', 'custom_questions': [{'title': 'Departamento/ Región', 'value': 'Lima'}, {'title': 'Género', 'value': 'Femenino'}, {'title': 'Edad', 'value': 'De 18 a 35 años'}, {'title': 'Nivel de estudio', 'value': 'Secundaria'}], 'status': 'approved', 'create_time': '2022-11-24T19:57:18Z'}"
300 6139 4D1YdjmRScmpy "{'id': 'DgyhfejIug', 'first_name': 'Artur', 'last_name': '', 'email': 'ads@gmail.com', 'address': '', 'city': '', 'country': 'CL', 'zip': '', 'state': '', 'phone': '', 'industry': '', 'org': '', 'job_title': '', 'purchasing_time_frame': '', 'role_in_purchase_process': '', 'no_of_employees': '', 'comments': '', 'custom_questions': [{'title': 'Departamento/ Región', 'value': 'CL'}, {'title': 'Género', 'value': 'Masculino'}, {'title': 'Edad', 'value': 'De 18 a 35 años'}, {'title': 'Nivel de estudio', 'value': 'Técnico / Superior'}], 'status': 'approved', 'create_time': '2022-11-24T17:22:44Z'}"</p>
|
[
{
"answer_id": 74585934,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())\n obj_fn Objetc()"
},
{
"answer_id": 74590796,
"author": "foglerit",
"author_id": 189418,
"author_profile": "https://Stackoverflow.com/users/189418",
"pm_score": 2,
"selected": true,
"text": "S_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nS_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nsum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex])\n\n> True\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20608547/"
] |
74,585,614
|
<pre><code>tests.map((test) => {
format(test.Hour, `yyyy-MM-dd'T'HH`)
console.log(format(test.Hour, `yyyy-MM-dd'T'HH`));
})
console.log(tests);
</code></pre>
<p>I am trying to convert some data i pulled from an API to a better date format for my purpose by using date-fns' format function. When i loop over it, the format function inside the console.log displays 2022-11-23 H:23, but when i console log it after the map has run, it shows me the value i dont want: 2022-11-23T23:00:00.000Z</p>
<p>Any help is appriciated, thanks !</p>
|
[
{
"answer_id": 74585702,
"author": "Melih Bağçeli",
"author_id": 19463436,
"author_profile": "https://Stackoverflow.com/users/19463436",
"pm_score": 0,
"selected": false,
"text": "const numbers = [1, 4, 9];\nconst roots = numbers.map((num) => Math.sqrt(num));\n// roots is now [1, 2, 3]\n// numbers is still [1, 4, 9]\n"
},
{
"answer_id": 74585743,
"author": "Rohit Khandelwal",
"author_id": 15220748,
"author_profile": "https://Stackoverflow.com/users/15220748",
"pm_score": 1,
"selected": false,
"text": "map forEach map const newTests = tests.map((test) => {\n return format(test.Hour, `yyyy-MM-dd'T'HH`);\n})\nconsole.log(newTests);"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14786888/"
] |
74,585,622
|
<p>I'm trying to use <a href="https://pypi.org/project/pyFirmata/" rel="nofollow noreferrer">pyFirmata</a>, but I can't get it to work. Even the most basic of the library does not work. I guess there is something wrong with the library code.</p>
<pre class="lang-py prettyprint-override"><code>from pyfirmata import Arduino,util
import time
port = 'COM5'
board = Arduino(port)
</code></pre>
<p>I get this error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "c:\Users\Public\pythonpublic\arduino.py", line 5, in <module>
board = Arduino(port)
^^^^^^^^^^^^^
File "C:\Users\marce\AppData\Roaming\Python\Python311\site-packages\pyfirmata\__init__.py", line 19, in __init__
super(Arduino, self).__init__(*args, **kwargs)
File "C:\Users\marce\AppData\Roaming\Python\Python311\site-packages\pyfirmata\pyfirmata.py", line 101, in __init__
self.setup_layout(layout)
File "C:\Users\marce\AppData\Roaming\Python\Python311\site-packages\pyfirmata\pyfirmata.py", line 157, in setup_layout
self._set_default_handlers()
File "C:\Users\marce\AppData\Roaming\Python\Python311\site-packages\pyfirmata\pyfirmata.py", line 161, in _set_default_handlers
self.add_cmd_handler(ANALOG_MESSAGE, self._handle_analog_message)
File "C:\Users\marce\AppData\Roaming\Python\Python311\site-packages\pyfirmata\pyfirmata.py", line 185, in add_cmd_handler
len_args = len(inspect.getargspec(func)[0])
^^^^^^^^^^^^^^^^^^
AttributeError: module 'inspect' has no attribute 'getargspec'. Did you mean: 'getargs'?
</code></pre>
|
[
{
"answer_id": 74585666,
"author": "Le Minaw",
"author_id": 7021223,
"author_profile": "https://Stackoverflow.com/users/7021223",
"pm_score": 1,
"selected": true,
"text": "inspect"
},
{
"answer_id": 74586109,
"author": "wovano",
"author_id": 10669875,
"author_profile": "https://Stackoverflow.com/users/10669875",
"pm_score": -1,
"selected": false,
"text": "inspect.getargspec()"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609610/"
] |
74,585,643
|
<p>I am using visual studio code as my code editor for my angular application. Everything was perfectly fine and suddenly out of no where I am facing the following 2 issues.</p>
<blockquote>
<ol>
<li>When Command <code>ng serve </code>is run in the terminal I am getting <code>√ Compiled successfully.</code> message. Then I open the port 4200 and run the application. The application is opened there but the last changes are not reflected there.</li>
<li>When I do changes in my code and save it, compilation is not happening in the terminal.</li>
</ol>
</blockquote>
<p>Both of the above issues were not there just an hour before. Whatever changes I am doing with my code I am not able to get the view in the browser. Do I need to reinstall the VS code? I have restarted my system ,updated vs code still no change. Please help me out if there is something I am missing</p>
<p><strong>Detailed information about Visual Studio Code</strong></p>
<pre><code>Version: 1.73.1 (user setup)
Commit: 6261075646f055b99068d3688932416f2346dd3b
Date: 2022-11-09T04:27:29.066Z
Electron: 19.0.17
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Windows_NT x64 10.0.19044
Sandboxed: No
</code></pre>
|
[
{
"answer_id": 74585666,
"author": "Le Minaw",
"author_id": 7021223,
"author_profile": "https://Stackoverflow.com/users/7021223",
"pm_score": 1,
"selected": true,
"text": "inspect"
},
{
"answer_id": 74586109,
"author": "wovano",
"author_id": 10669875,
"author_profile": "https://Stackoverflow.com/users/10669875",
"pm_score": -1,
"selected": false,
"text": "inspect.getargspec()"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6676148/"
] |
74,585,652
|
<p>I want to emulate the Iphone Gallery, I am stacking div's correctly with flexbox, but with different widths and heights, and they don’t stack properly. Here is a screenshot since the code is so big:</p>
<p><img src="https://i.stack.imgur.com/ohgbd.png" alt="Image" /></p>
<p>I tried as shown in the photo, I can't get the div's to fill all the page. Here is an Iphone image that I want to do:</p>
<p><img src="https://i.stack.imgur.com/D1jO7.png" alt="Image" /></p>
<p>Here's an example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
display: flex;
flex-direction: column;
flex-flow: row wrap;
height: 600px;
width: 300px;
border-radius: 35px;
background-color: red;
}
.photo {
width: 50px;
height: 50px;
background-color: blue;
border-radius: 10px;
border: 2.5px solid white;
}
.photo.big {
width: 150px;
height: 250px;
background-color: blue;
border-radius: 10px;
border: 2.5px solid white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div id="container">
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo big"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
<div class="photo"></div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74586079,
"author": "Skin_phil",
"author_id": 13258195,
"author_profile": "https://Stackoverflow.com/users/13258195",
"pm_score": 2,
"selected": true,
"text": "#container {\n display: grid;\n \n grid-template-columns: 1fr 1fr 1fr;\n grid-template-rows:auto;\n height: 600px;\n width: 300px;\n border-radius: 35px;\n background-color: red;\n}\n\n.photo {\n width: 100%;\n height: 100%;\n background-color: blue;\n border-radius: 10px;\n border: 2.5px solid white;\n}\n\n.photo.big {\n\n grid-column-start:2;\n grid-column-end: span 2;\n grid-row-start:2;\n grid-row-end: span 2;\n \n background-color: green;\n border-radius: 10px;\n border: 2.5px solid white;\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link rel=\"stylesheet\" href=\"styles.css\">\n <title>Document</title>\n</head>\n<body>\n <div id=\"container\">\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo big\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n </div>\n</body>\n</html>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19444460/"
] |
74,585,664
|
<p>new true value that meets the condition = v</p>
<p>previous true value = vprev</p>
<p>I am trying to look for a v so that hash of str(((power(v,2))+(power(vprev, 3))) begins with ee</p>
<p>I tried this</p>
<pre><code>import hashlib
values_list = []# a list where v and prev will be
solved = False
v = 1 # to start looping from 1
while not solved:
for index, v in enumerate(values_list):
vprev = values_list[(index - 1)]
results = str(v**2 + vprev**3)
results_encoded = results.encode()
results_hashed = hashlib.sha256(results_encoded).hexdigest()
if results[0:2] == "ee":
solved = True
values_list.append(v)
else: v += 1
print(values_list)
</code></pre>
<p>I'm expecting a list with the first true value but I have failed</p>
|
[
{
"answer_id": 74586079,
"author": "Skin_phil",
"author_id": 13258195,
"author_profile": "https://Stackoverflow.com/users/13258195",
"pm_score": 2,
"selected": true,
"text": "#container {\n display: grid;\n \n grid-template-columns: 1fr 1fr 1fr;\n grid-template-rows:auto;\n height: 600px;\n width: 300px;\n border-radius: 35px;\n background-color: red;\n}\n\n.photo {\n width: 100%;\n height: 100%;\n background-color: blue;\n border-radius: 10px;\n border: 2.5px solid white;\n}\n\n.photo.big {\n\n grid-column-start:2;\n grid-column-end: span 2;\n grid-row-start:2;\n grid-row-end: span 2;\n \n background-color: green;\n border-radius: 10px;\n border: 2.5px solid white;\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link rel=\"stylesheet\" href=\"styles.css\">\n <title>Document</title>\n</head>\n<body>\n <div id=\"container\">\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo big\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n <div class=\"photo\"></div>\n </div>\n</body>\n</html>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609251/"
] |
74,585,703
|
<p>I'm trying to create a <code>JSON</code> array that contains list of weekdays.</p>
<p>I'm testing this in a console app but it keeps giving me an error i.e. exited with code 0.</p>
<p>Here's what I'm doing:</p>
<pre><code>using Newtonsoft.Json;
var days = new List<DayOfWeek>();
days.Add(DayOfWeek.Monday);
days.Add(DayOfWeek.Wednesday);
var json = JsonConvert.SerializeObject(days);
Console.WriteLine(json);
</code></pre>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 74585796,
"author": "Avrohom Yisroel",
"author_id": 706346,
"author_profile": "https://Stackoverflow.com/users/706346",
"pm_score": 2,
"selected": true,
"text": "System.Text.Json var days = JsonSerializer.Serialize(Enum.GetValues(typeof(DayOfWeek))\n .Cast<DayOfWeek>().ToList());\n Cast<>"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1705266/"
] |
74,585,752
|
<p>Here's a simple example:</p>
<pre><code>def separateFloatInt(L):
l1=list()
l2=list()
for x in L:
if type(x)==int:
l1.append(x)
else:
l2.append(x)
return l1,l2
L=['2', '3.5', '6', '5.1', '9.8', '7.8', '5', '3.3', '0.5', '9']
integer,reel=separateFloatInt(L)
</code></pre>
<p>How can I separate one list into two list, one has only integers, the other has only floats?</p>
|
[
{
"answer_id": 74585849,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "def separateFloatInt(L):\n l1, l2 = [], []\n for v in L:\n try:\n l1.append(int(v))\n except ValueError:\n l2.append(float(v))\n return l1, l2\n\n\nL = [\"2\", \"3.5\", \"6\", \"5.1\", \"9.8\", \"7.8\", \"5\", \"3.3\", \"0.5\", \"9\"]\ninteger, reel = separateFloatInt(L)\n\nprint(integer)\nprint(reel)\n [2, 6, 5, 9]\n[3.5, 5.1, 9.8, 7.8, 3.3, 0.5]\n"
},
{
"answer_id": 74586074,
"author": "Hamza KHEDDAR",
"author_id": 5738528,
"author_profile": "https://Stackoverflow.com/users/5738528",
"pm_score": 0,
"selected": false,
"text": "def separateFloatInt(L):\n L=[float(x) for x in L]\n L=[str(x) for x in L]\n l1=list()\n l2=list()\n for x in L:\n print(x)\n a,b=x.split(\".\")\n if int(b)!=0:\n l1.append(x) # float\n else:\n l2.append(a) # int\n return l1,l2 \n \np=read()\nprint(p)\nreal,integer=separateFloatInt(p) \n L=['2', '3.2', '6', '3.5', '8.4', '8.8', '9', '5', '4.1', '5']\n print(real)\nprint(integer)\n['3.2', '3.5', '8.4', '8.8', '4.1']\n['2', '6', '9', '5', '5']\n\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738528/"
] |
74,585,782
|
<p>I have this custom dropDown button and I want to get two values when I select one value from the list.</p>
<p>Here is the custom dropdown button</p>
<pre><code>Widget customJsonDropDown(List? jsonList, String? value, void onChange(val)) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: SizedBox(
//width: 80,
height: 50,
child: DropdownButton<String>(
hint: const Text('Select unit'),
value: value,
onChanged: (val) {
onChange(val);
},
items: jsonList?.map((item) {
return DropdownMenuItem(
value: item['conversion'].toString(),
child: Text(item['name']),
);
}).toList(),
underline: Container(),
isExpanded: true,
))));
}
</code></pre>
<p>here is the Json List</p>
<pre><code>{
"Length": [
{
"name": "Meter",
"conversion": 1.0,
"base_unit": true
},
{
"name": "Millimeter",
"conversion": 1000.0
},
{
"name": "Centimeter",
"conversion": 100.0
}
]
}
</code></pre>
<p>as you guys can see that I am returning a <strong>String</strong> value from <strong>['conversion']</strong> and I am using <strong>['name']</strong> from jsonList to display the names. this works fine and I get the <strong>['conversion']</strong> values in return but what I want more is to store the <strong>Selected</strong> name in a variable as well. for example if I select <strong>Meter</strong> from dropdown button, it returns the <strong>conversion</strong> value on <strong>onChanged</strong> but I want to capture and assign the <strong>selected name</strong> as well to a variable.</p>
<p>So how can I do that and is it even possible?
appreciate any help</p>
|
[
{
"answer_id": 74589367,
"author": "Peter Koltai",
"author_id": 14726230,
"author_profile": "https://Stackoverflow.com/users/14726230",
"pm_score": 0,
"selected": false,
"text": "DropdownButton String <Map<String, dynamic>> DropdownButton DropdownMenuItem Map name conversion import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n @override\n Widget build(BuildContext context) {\n return const MaterialApp(\n home: Scaffold(\n body: SafeArea(\n child: Padding(\n padding: EdgeInsets.all(8.0),\n child: MyDropdown(),\n )),\n ),\n );\n }\n}\n\nclass MyDropdown extends StatefulWidget {\n const MyDropdown({Key? key}) : super(key: key);\n\n @override\n State<MyDropdown> createState() => MyDropdownState();\n}\n\nclass MyDropdownState extends State<MyDropdown> {\n Map<String, dynamic>? _selected;\n\n final _json = {\n 'Length': [\n {'name': 'Meter', 'conversion': 1.0, 'base_unit': true},\n {'name': 'Millimeter', 'conversion': 1000.0},\n {'name': 'Centimeter', 'conversion': 100.0}\n ]\n };\n\n @override\n Widget build(BuildContext context) {\n return DropdownButton<Map<String, dynamic>>(\n value: _selected,\n onChanged: (selected) => setState(() {\n debugPrint(\n 'Selected name: ${selected?['name']}, conversion: ${selected?['conversion']}');\n _selected = selected;\n }),\n items: _json['Length']\n ?.map((Map<String, dynamic> item) =>\n DropdownMenuItem<Map<String, dynamic>>(\n value: item,\n child: Text(item['name']),\n ))\n .toList());\n }\n}\n"
},
{
"answer_id": 74591097,
"author": "Peter Koltai",
"author_id": 14726230,
"author_profile": "https://Stackoverflow.com/users/14726230",
"pm_score": 2,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass Unit {\n final String name;\n final double conversion;\n final bool baseUnit;\n const Unit(\n {required this.name, required this.conversion, this.baseUnit = false});\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n @override\n Widget build(BuildContext context) {\n return const MaterialApp(\n home: Scaffold(\n body: SafeArea(\n child: Padding(\n padding: EdgeInsets.all(8.0),\n child: MyDropdown(),\n )),\n ),\n );\n }\n}\n\nclass MyDropdown extends StatefulWidget {\n const MyDropdown({Key? key}) : super(key: key);\n\n @override\n State<MyDropdown> createState() => MyDropdownState();\n}\n\nclass MyDropdownState extends State<MyDropdown> {\n Unit? _selected;\n\n final _units = const <Unit>[\n Unit(name: 'Meter', conversion: 1.0, baseUnit: true),\n Unit(name: 'Millimeter', conversion: 1000.0),\n Unit(name: 'Centimeter', conversion: 100)\n ];\n\n @override\n Widget build(BuildContext context) {\n return DropdownButton<Unit>(\n value: _selected,\n onChanged: (selected) => setState(() {\n debugPrint(\n 'Selected name: ${selected?.name}}, conversion: ${selected?.conversion}');\n _selected = selected;\n }),\n items: _units\n .map((Unit unit) => DropdownMenuItem<Unit>(\n value: unit,\n child: Text(unit.name),\n ))\n .toList());\n }\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9702001/"
] |
74,585,842
|
<p>I have two groups of data I'm working with, which I'd like to show in a bar plot using plotly (example for data is shown below).</p>
<pre><code>import numpy as np
import plotly.express as px
import plotly.graph_objects as go
</code></pre>
<pre><code>values1 = abs(np.random.normal(0.5, 0.3, 13)) # random data and names
values2 = abs(np.random.normal(0.5, 0.3, 13))
values3 = abs(np.random.standard_normal(13))
values4 = abs(np.random.standard_normal(13))
names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
fig = go.Figure()
fig.add_trace(go.Bar(
x = names,
y = values1,
legendgroup="group",
legendgrouptitle_text="method one",
name="first"
))
fig.add_trace(go.Bar(
x=names,
y=values2,
legendgroup="group",
name="second"
))
fig.add_trace(go.Bar(
x=names,
y=values3,
legendgroup="group2",
legendgrouptitle_text="method two",
name="first"
))
fig.add_trace(go.Bar(
x=names,
y=values4,
legendgroup="group2",
name="second"
))
fig.update_layout(barmode='group')
fig.update_traces(texttemplate='%{y:.2}', textposition='inside')
fig.show()
</code></pre>
<p>This code produces the following graph:</p>
<p><img src="https://i.ibb.co/xGYpkMJ/Screenshot-2022-11-26-at-23-36-03.jpg" alt="Text" /></p>
<p>I would like to add a space between the two methods for each name (adding space between method one and method two for the two values in each value).</p>
<p>I tried using <code>offsetgroup</code> but doesn't seem to work. Any help on the matter would be appreciated.</p>
|
[
{
"answer_id": 74587158,
"author": "r-beginners",
"author_id": 13107804,
"author_profile": "https://Stackoverflow.com/users/13107804",
"pm_score": 2,
"selected": true,
"text": "fig.update_layout(barmode='group', bargroupgap=0.2)\n fig = go.Figure()\n\nfig.add_trace(go.Bar(\n x = names,\n y = values1,\n legendgroup=\"group\", \n legendgrouptitle_text=\"method one\",\n name=\"first\"\n))\n\nfig.add_trace(go.Bar(\n x=names,\n y=values2,\n legendgroup=\"group\",\n name=\"second\"\n))\n# add bar plot(null data) \nfig.add_trace(go.Bar(\n x=names,\n y=np.full((1,51),np.NaN),\n showlegend=False,\n))\n \nfig.add_trace(go.Bar(\n x=names,\n y=values3,\n legendgroup=\"group2\",\n legendgrouptitle_text=\"method two\",\n name=\"first\"\n))\n\nfig.add_trace(go.Bar(\n x=names,\n y=values4,\n legendgroup=\"group2\",\n name=\"second\"\n))\n\nfig.update_layout(barmode='group')#, bargroupgap=0.2\nfig.update_traces(texttemplate='%{y:.2}', textposition='inside')\nfig.show()\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14531338/"
] |
74,585,854
|
<p>Is there any fundamental difference between assigning a value to a variable before or inside the <code>Start()</code> method?</p>
<p>For clarity, I'm not talking about declaring variables but really just giving them values like, in this simple example:</p>
<pre><code>public class test : MonoBehaviour
{
private float exampleFloat = 12.34f;
private void Start()
{
// do stuff with exampleFloat
}
}
</code></pre>
<p>versus this :</p>
<pre><code>public class test : MonoBehaviour
{
private float exampleFloat;
private void Start()
{
exampleFloat = 12.34f;
// do stuff with exampleFloat
}
}
</code></pre>
|
[
{
"answer_id": 74585894,
"author": "gunr2171",
"author_id": 1043380,
"author_profile": "https://Stackoverflow.com/users/1043380",
"pm_score": 2,
"selected": false,
"text": "exampleFloat Start() Start() 12.34"
},
{
"answer_id": 74585895,
"author": "Avrohom Yisroel",
"author_id": 706346,
"author_profile": "https://Stackoverflow.com/users/706346",
"pm_score": -1,
"selected": false,
"text": "private float exampleFloat;\n Start Start 12.34"
},
{
"answer_id": 74588225,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 3,
"selected": true,
"text": "public class test : MonoBehaviour\n{\n private float exampleFloat = 12.34f;\n\n private void Awake ()\n {\n Debug.Log($\"Example 1: exampleFloat = {exampleFloat}\");\n }\n\n private void Start()\n {\n //do stuff with exampleFloat\n }\n}\n public class test : MonoBehaviour\n{\n private float exampleFloat;\n\n private void Awake ()\n {\n Debug.Log($\"Example 2: exampleFloat = {exampleFloat}\");\n }\n\n private void Start()\n {\n exampleFloat = 12.34f;\n //do stuff with exampleFloat\n }\n}\n Example 1: exampleFloat = 12.34\nExample 2: exampleFloat = 0\n public class test : MonoBehaviour\n{\n [SerializeField] private float exampleFloat = 12.34f;\n\n private void Start()\n {\n //do stuff with exampleFloat\n Debug.Log($\"Example 3: exampleFloat = {exampleFloat}\");\n }\n}\n public class test : MonoBehaviour\n{\n [SerializeField] private float exampleFloat;\n\n private void Start()\n {\n exampleFloat = 12.34f;\n Debug.Log($\"Example 4: exampleFloat = {exampleFloat}\");\n //do stuff with exampleFloat\n }\n}\n Example 3: exampleFloat = 12.34 // OR whatever is serialised in the Inspector!\nExample 4: exampleFloat = 12.34 // always 12.34.\n Awake Start Awake Component"
},
{
"answer_id": 74593848,
"author": "Sek",
"author_id": 17075435,
"author_profile": "https://Stackoverflow.com/users/17075435",
"pm_score": 1,
"selected": false,
"text": "public class test : MonoBehaviour\n{\n private float exampleFloat = 12.34f;\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20314934/"
] |
74,585,875
|
<p>This might be a really obvious solution to some, but, being pretty new to python, I'm unsure how to do it - In short, I want to take a user's input, and find the corresponding element on a 2D array, i.e. an input of '1' would print 'a', '2' would print 'b', and so on. Is there a way to do this?
The code I've written so far is below</p>
<pre><code>var=[["1","a"],["2","b"],["3","c"]]
inp='x'
while inp!='1' and inp!='2' and inp!='3':
inp=str(input("Enter a number 1-3\n"))
</code></pre>
<p>I've not got a clue what to try, and I'm yet to find a solution - that just might be due to my poor phrasing though - so any help is greatly appreciated!</p>
|
[
{
"answer_id": 74585894,
"author": "gunr2171",
"author_id": 1043380,
"author_profile": "https://Stackoverflow.com/users/1043380",
"pm_score": 2,
"selected": false,
"text": "exampleFloat Start() Start() 12.34"
},
{
"answer_id": 74585895,
"author": "Avrohom Yisroel",
"author_id": 706346,
"author_profile": "https://Stackoverflow.com/users/706346",
"pm_score": -1,
"selected": false,
"text": "private float exampleFloat;\n Start Start 12.34"
},
{
"answer_id": 74588225,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 3,
"selected": true,
"text": "public class test : MonoBehaviour\n{\n private float exampleFloat = 12.34f;\n\n private void Awake ()\n {\n Debug.Log($\"Example 1: exampleFloat = {exampleFloat}\");\n }\n\n private void Start()\n {\n //do stuff with exampleFloat\n }\n}\n public class test : MonoBehaviour\n{\n private float exampleFloat;\n\n private void Awake ()\n {\n Debug.Log($\"Example 2: exampleFloat = {exampleFloat}\");\n }\n\n private void Start()\n {\n exampleFloat = 12.34f;\n //do stuff with exampleFloat\n }\n}\n Example 1: exampleFloat = 12.34\nExample 2: exampleFloat = 0\n public class test : MonoBehaviour\n{\n [SerializeField] private float exampleFloat = 12.34f;\n\n private void Start()\n {\n //do stuff with exampleFloat\n Debug.Log($\"Example 3: exampleFloat = {exampleFloat}\");\n }\n}\n public class test : MonoBehaviour\n{\n [SerializeField] private float exampleFloat;\n\n private void Start()\n {\n exampleFloat = 12.34f;\n Debug.Log($\"Example 4: exampleFloat = {exampleFloat}\");\n //do stuff with exampleFloat\n }\n}\n Example 3: exampleFloat = 12.34 // OR whatever is serialised in the Inspector!\nExample 4: exampleFloat = 12.34 // always 12.34.\n Awake Start Awake Component"
},
{
"answer_id": 74593848,
"author": "Sek",
"author_id": 17075435,
"author_profile": "https://Stackoverflow.com/users/17075435",
"pm_score": 1,
"selected": false,
"text": "public class test : MonoBehaviour\n{\n private float exampleFloat = 12.34f;\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609766/"
] |
74,585,893
|
<p>I like to use <code>SMS Spam Collection Data Set</code> which can be found on <a href="https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection#" rel="nofollow noreferrer">UCI Machine Learning Repository</a>, to build a classification model. The data file that is shared on the repository has no file extension. The data is look like the following</p>
<pre><code> ham Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...
ham Ok lar... Joking wif u oni...
spam Free entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's
ham U dun say so early hor... U c already then say...
ham Nah I don't think he goes to usf, he lives around here though
spam FreeMsg Hey there darling it's been 3 week's now and no word back! I'd like some fun you up for it still? Tb ok! XxX std chgs to send, £1.50 to rcv
</code></pre>
<p>Where ham or spam should be the class attribute and the rest of the portion is the message. How could I transfer the dataset into Pandas dataframe? The dataframe should like the following</p>
<pre><code>Message Class Messages
ham Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...
ham Ok lar... Joking wif u oni...
spam Free entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C's apply 08452810075over18's
ham U dun say so early hor... U c already then say...
ham Nah I don't think he goes to usf, he lives around here though
spam FreeMsg Hey there darling it's been 3 week's now and no word back! I'd like some fun you up for it still? Tb ok! XxX std chgs to send, £1.50 to rcv
</code></pre>
|
[
{
"answer_id": 74585962,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": true,
"text": ".txt pandas.read_csv import pandas as pd\n\ndf = pd.read_csv(filepath_or_buffer= \"SMSSpamCollection\",\n header=None, sep=\"\\t\", names=[\"Message Class\", \"Messages\"])\n"
},
{
"answer_id": 74585966,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "df= pd.read_csv(\"your_file.csv\", sep=\"\\t\")\ndf.dropna(how=\"any\", inplace=True, axis=1)\ndf.columns = ['label', 'message']\ndf.head()\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9357484/"
] |
74,585,920
|
<p>I see some similar questions have been posted, but I am stuck with my issue considering it's a bit different. My question is that how can I add counting (like 1,2) for each list in the same line?</p>
<p>`</p>
<pre><code>
class AttendeeListPage extends Component<any,any> {
...
render(){
let attendarr: any[] = [];
let countArr : number[] = [];
for (let i = 0; i < this.state.arr.length; i++){
countArr.push(i+1);
attendarr.push(<AttendeeBox
email={this.state.arr[i][0]}
status={this.state.arr[i][1]}
eventNum={this.props.eventNum}
/>)
}
return (
<div className='App'>
<div>
{countArr}
{attendarr}
</div>
</div>
);
}
}
export default AttendeeListPage;
</code></pre>
<p>`</p>
<p>My AttendeeBox file:</p>
<p>`</p>
<pre><code>class AttendeeBox extends Component<any,any> {
constructor(props:any){
super(props);
this.state = {id: this.props.eventNum(), updateForced: false, ForceUpdateNow: false}
}
componentDidMount(): void {
this.setState({ForceUpdateNow:true})
}
componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<any>, snapshot?: any): void {
if(this.state.id !== this.props.id){
this.setState({id: this.props.id}); //should probably be id: this.state.id
}
}
render() {
return (
<div className='AttendeeBox'>
<div className='listElement'>
Email : {this.props.email} &nbsp;
</div>
<div className='listElement'>
Status : {this.props.status}
</div>
</div>
)
}
}
export default AttendeeBox;
</code></pre>
<p>`</p>
<p>My attempt looks like: <a href="https://i.stack.imgur.com/38GZn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/38GZn.png" alt="enter image description here" /></a></p>
<p>As you can see, the counter is seperated from the list box and positioned on top of it. I'm not sure how to make them work together. Thanks!</p>
|
[
{
"answer_id": 74586175,
"author": "dkunrath",
"author_id": 19480959,
"author_profile": "https://Stackoverflow.com/users/19480959",
"pm_score": 1,
"selected": true,
"text": ".map class AttendeeListPage extends Component<any,any> {\n ...\n render(){\n let attendarr: any[] = [];\n let countArr : number[] = [];\n for (let i = 0; i < this.state.arr.length; i++){\n countArr.push(i+1);\n attendarr.push(<AttendeeBox\n email={this.state.arr[i][0]}\n status={this.state.arr[i][1]}\n eventNum={this.props.eventNum}\n />)\n }\n\n return (\n <div className='App'>\n <div className='indexes'>\n {countArr.map(index => <div>{index}</index>}\n </div>\n <div className='container'>\n {attendarr}\n </div>\n </div>\n );\n }\n}\n\nexport default AttendeeListPage;\n .App {\n display: flex;\n}\n indexes divs countArr.push(<div>i+1</div>)"
},
{
"answer_id": 74586330,
"author": "jgurbanov",
"author_id": 5589483,
"author_profile": "https://Stackoverflow.com/users/5589483",
"pm_score": 1,
"selected": false,
"text": "map 1 Email: email@email.com STATUS: WILLATTEND\n2 Email: email@email.com STATUS: WILLATTEND\n AttendeeBox class AttendeeListPage extends Component<any,any> {\n ...\n render(){\n let attendarr: any[] = [];\n for (let i = 0; i < this.state.arr.length; i++){\n attendarr.push(<AttendeeBox\n email={this.state.arr[i][0]}\n status={this.state.arr[i][1]}\n eventNum={this.props.eventNum}\n order={i+1}\n />)\n }\n\n return (\n <div className='App'>\n <div>\n {attendarr.map(attendee => <div>{attendee}</div>)}\n </div>\n </div>\n );\n }\n}\n\nexport default AttendeeListPage;\n class AttendeeBox extends Component<any,any> {\n constructor(props:any){\n super(props);\n this.state = {id: this.props.eventNum(), updateForced: false, ForceUpdateNow: false}\n }\n componentDidMount(): void {\n this.setState({ForceUpdateNow:true})\n }\n componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<any>, snapshot?: any): void {\n if(this.state.id !== this.props.id){\n this.setState({id: this.props.id}); //should probably be id: this.state.id\n }\n }\n\n render() {\n return (\n <div className='AttendeeBox'>\n <div>{this.props.order}</div> \n <div className='listElement'>\n Email : {this.props.email} \n </div>\n <div className='listElement'>\n Status : {this.props.status}\n </div>\n </div>\n )\n }\n}\n\nexport default AttendeeBox;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19249893/"
] |
74,585,987
|
<p>My ultimate goal is to add the decimal value associated with the drop down item selected to any other number the user inputs (so they might input 1 and then choose 1/8 and I want it to spit out 1.125.) - it's a web app for me to keep track of the food and spices I have in the kitchen.</p>
<p>I can't get it to grab the value I've assigned to each option in the drop down. I keep getting the following error:</p>
<p>script.js:7 Uncaught TypeError: Cannot read properties of null (reading 'value')</p>
<p>I figured it would struggle with actual fractions, so my html drop down looks like this:</p>
<pre><code> <label for="fractions"></label>
<select name="fractions" id="fractions">
<option value="0">.0</option>
<option value="0.125">1/8</option>
<option value="0.25">1/4</option>
<option value="0.67">1/3</option>
<option value="0.50">1/2</option>
<option value="0.75">3/4</option>
</select>
</code></pre>
<p>Originally, I had my script using var fractions = document.getElementById("fractions") and then using fractions.value to get the value I assigned in the drop down, but it wouldn't give me the value. I found pretty much the same answer on here and on another website - use .value - and I can't figure out any other way to do it.</p>
<p>I also tried using var whatever = parseFloat(fractions); and then whatever.value to change the value to a float and then get that value, thinking maybe it was giving me a string, so that's why it wasn't adding properly, but it had the same error on it.</p>
<p>I did end up changing my selector thinking maybe that was the issue, so now my script looks like this:</p>
<pre><code>const fractions = document.querySelector('#fractions')
const fractionsValue = fractions.value
</code></pre>
<p>I also tried implement .value this way:</p>
<pre><code>const fractionsValue = fractions.options[fractions.selectedIndex].value
</code></pre>
<p>But I keep getting the same error.</p>
<p>I'm probably making a really silly mistake - what am I doing wrong?</p>
|
[
{
"answer_id": 74586175,
"author": "dkunrath",
"author_id": 19480959,
"author_profile": "https://Stackoverflow.com/users/19480959",
"pm_score": 1,
"selected": true,
"text": ".map class AttendeeListPage extends Component<any,any> {\n ...\n render(){\n let attendarr: any[] = [];\n let countArr : number[] = [];\n for (let i = 0; i < this.state.arr.length; i++){\n countArr.push(i+1);\n attendarr.push(<AttendeeBox\n email={this.state.arr[i][0]}\n status={this.state.arr[i][1]}\n eventNum={this.props.eventNum}\n />)\n }\n\n return (\n <div className='App'>\n <div className='indexes'>\n {countArr.map(index => <div>{index}</index>}\n </div>\n <div className='container'>\n {attendarr}\n </div>\n </div>\n );\n }\n}\n\nexport default AttendeeListPage;\n .App {\n display: flex;\n}\n indexes divs countArr.push(<div>i+1</div>)"
},
{
"answer_id": 74586330,
"author": "jgurbanov",
"author_id": 5589483,
"author_profile": "https://Stackoverflow.com/users/5589483",
"pm_score": 1,
"selected": false,
"text": "map 1 Email: email@email.com STATUS: WILLATTEND\n2 Email: email@email.com STATUS: WILLATTEND\n AttendeeBox class AttendeeListPage extends Component<any,any> {\n ...\n render(){\n let attendarr: any[] = [];\n for (let i = 0; i < this.state.arr.length; i++){\n attendarr.push(<AttendeeBox\n email={this.state.arr[i][0]}\n status={this.state.arr[i][1]}\n eventNum={this.props.eventNum}\n order={i+1}\n />)\n }\n\n return (\n <div className='App'>\n <div>\n {attendarr.map(attendee => <div>{attendee}</div>)}\n </div>\n </div>\n );\n }\n}\n\nexport default AttendeeListPage;\n class AttendeeBox extends Component<any,any> {\n constructor(props:any){\n super(props);\n this.state = {id: this.props.eventNum(), updateForced: false, ForceUpdateNow: false}\n }\n componentDidMount(): void {\n this.setState({ForceUpdateNow:true})\n }\n componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<any>, snapshot?: any): void {\n if(this.state.id !== this.props.id){\n this.setState({id: this.props.id}); //should probably be id: this.state.id\n }\n }\n\n render() {\n return (\n <div className='AttendeeBox'>\n <div>{this.props.order}</div> \n <div className='listElement'>\n Email : {this.props.email} \n </div>\n <div className='listElement'>\n Status : {this.props.status}\n </div>\n </div>\n )\n }\n}\n\nexport default AttendeeBox;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19369950/"
] |
74,585,992
|
<p>How can I collect data from all the sheets of the table?</p>
<p>Through apps script, I get all the unprotected sheets on the book, and the width of the range with data on sheets with the same structure.</p>
<pre><code>function GetRangeArray() {
var sheets = SpreadsheetApp.getActive().getSheets();
var counter = 0;
var StrRange = "";
var Result = new Array();
for (var i=0 ; i<sheets.length ; i++) {
if (sheets[i].getProtections(SpreadsheetApp.ProtectionType.SHEET)[0]){
continue;
};
counter++;
if ( counter == 1 ) {
LastColumn = NumRetLetra(sheets[i].getLastColumn());
}
StrRange = "'" + sheets[i].getName() + "'!A2:" + LastColumn;
Result.push([StrRange]);
}
return Result;
function NumRetLetra(column){
var temp, letter = '';
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
</code></pre>
<p>On the protected "Total" sheet, I enter the formula into cell A1 =GetRangeArray().</p>
<pre><code>=query({INDIRECT(A1);INDIRECT(A2)};"SELECT Col1, Col2")
</code></pre>
<p>But I get an error: <strong>The result is not fully displayed. Add rows (6) to the table.</strong></p>
<p>I try, where A1 - key, A3 - formula =GetRangeArray()</p>
<pre><code>=QUERY({IMPORTRANGE(A1;A3);IMPORTRANGE(A1;A4)};"SELECT Col1, Col2")
</code></pre>
<p>But I get an error: <strong>The result is not fully displayed. Add rows (6) to the table.</strong></p>
<p>If i use:</p>
<pre><code>=QUERY({IMPORTRANGE(A1;A3)};"SELECT Col1, Col2")
</code></pre>
<p>or</p>
<pre><code>=query({INDIRECT(A3)};"SELECT *")
</code></pre>
<p>This works, but only for one of the sheets.</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74586175,
"author": "dkunrath",
"author_id": 19480959,
"author_profile": "https://Stackoverflow.com/users/19480959",
"pm_score": 1,
"selected": true,
"text": ".map class AttendeeListPage extends Component<any,any> {\n ...\n render(){\n let attendarr: any[] = [];\n let countArr : number[] = [];\n for (let i = 0; i < this.state.arr.length; i++){\n countArr.push(i+1);\n attendarr.push(<AttendeeBox\n email={this.state.arr[i][0]}\n status={this.state.arr[i][1]}\n eventNum={this.props.eventNum}\n />)\n }\n\n return (\n <div className='App'>\n <div className='indexes'>\n {countArr.map(index => <div>{index}</index>}\n </div>\n <div className='container'>\n {attendarr}\n </div>\n </div>\n );\n }\n}\n\nexport default AttendeeListPage;\n .App {\n display: flex;\n}\n indexes divs countArr.push(<div>i+1</div>)"
},
{
"answer_id": 74586330,
"author": "jgurbanov",
"author_id": 5589483,
"author_profile": "https://Stackoverflow.com/users/5589483",
"pm_score": 1,
"selected": false,
"text": "map 1 Email: email@email.com STATUS: WILLATTEND\n2 Email: email@email.com STATUS: WILLATTEND\n AttendeeBox class AttendeeListPage extends Component<any,any> {\n ...\n render(){\n let attendarr: any[] = [];\n for (let i = 0; i < this.state.arr.length; i++){\n attendarr.push(<AttendeeBox\n email={this.state.arr[i][0]}\n status={this.state.arr[i][1]}\n eventNum={this.props.eventNum}\n order={i+1}\n />)\n }\n\n return (\n <div className='App'>\n <div>\n {attendarr.map(attendee => <div>{attendee}</div>)}\n </div>\n </div>\n );\n }\n}\n\nexport default AttendeeListPage;\n class AttendeeBox extends Component<any,any> {\n constructor(props:any){\n super(props);\n this.state = {id: this.props.eventNum(), updateForced: false, ForceUpdateNow: false}\n }\n componentDidMount(): void {\n this.setState({ForceUpdateNow:true})\n }\n componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<any>, snapshot?: any): void {\n if(this.state.id !== this.props.id){\n this.setState({id: this.props.id}); //should probably be id: this.state.id\n }\n }\n\n render() {\n return (\n <div className='AttendeeBox'>\n <div>{this.props.order}</div> \n <div className='listElement'>\n Email : {this.props.email} \n </div>\n <div className='listElement'>\n Status : {this.props.status}\n </div>\n </div>\n )\n }\n}\n\nexport default AttendeeBox;\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609847/"
] |
74,585,996
|
<p>I have a 5000 lines file consisting of blocks of lines, with an END string between blocks, as follows</p>
<pre><code>ATOM 1
ATOM 3
ATOM 25
END
ATOM 2
ATOM 36
ATOM 22
ATOM 12
END
ATOM 1
ATOM 87
END
</code></pre>
<p>I want to find a way to split the file into several files, each containing a single block of lines before the END string. The first file should look as follows:</p>
<pre><code>ATOM 1
ATOM 3
ATOM 25
</code></pre>
<p>The second file should contain</p>
<pre><code>ATOM 2
ATOM 36
ATOM 22
ATOM 12
</code></pre>
<p>And so on. I have thought of using something like <code>awk '/END/{flag=1; next} /END/{flag=0} flag' file</code> to take the blocks between the END strings. This, however, does not work for my first block, as the END string is only after the block, and most importantly, cannot take into account the number of times it has found the string END to separate each block into its individual file.
Is there a way I can use the string END to split my file into several, each containing a block that ends with the string END?</p>
|
[
{
"answer_id": 74586027,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": false,
"text": "awk 'BEGIN{flag=0} /END/{flag++} {print $0 > flag \".txt\"}' file\n flag=0\nwhile IFS= read -r line; do\n if [[ \"$line\" = \"END\" ]]; then\n flag=$((flag + 1))\n else\n printf \"%s\\n\" \"$line\" >> \"$flag.txt\"\n fi\ndone <inputfile\n"
},
{
"answer_id": 74586188,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 2,
"selected": false,
"text": "awk record RS awk 'BEGIN{RS=\"END\";ORS=\"\";i=1;} {print > \"part\"i\".file\"; i++}' file.txt\n ORS i > ls part*\npart1.file part2.file part3.file part4.file\n> cat part1.file\nATOM 1\nATOM 3\nATOM 25\n>cat part2.file\n \nATOM 2\nATOM 36\nATOM 22\nATOM 12 \n awk 'BEGIN{RS=\"END\";ORS=\"\";i=1;} {flname=\"part\"i\".file\"; print > flname; i++}' file.txt\n"
},
{
"answer_id": 74586515,
"author": "karakfa",
"author_id": 1435869,
"author_profile": "https://Stackoverflow.com/users/1435869",
"pm_score": 0,
"selected": false,
"text": "$ awk '/END/{c++; next} {print > (\"file.\"(c+1)\".txt\")}' file\n\n\n\n==> file.1.txt <==\nATOM 1\nATOM 3\nATOM 25\n\n==> file.2.txt <==\nATOM 2\nATOM 36\nATOM 22\nATOM 12\n\n==> file.3.txt <==\nATOM 1\nATOM 87\n $ awk 'BEGIN {f=\"file.\"(++c)\".txt\"} \n /END/ {close(f); f=\"file\"(++c)\".txt\"; next} \n {print > f}' file\n"
},
{
"answer_id": 74586531,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "$ awk -v cnt=1 '\n /END/ { cnt++; next }\n cnt != prev { close(out); out=\"foo\" cnt \".txt\"; prev=cnt }\n { print > out }\n' file\n $ head foo*.txt\n==> foo1.txt <==\nATOM 1\nATOM 3\nATOM 25\n\n==> foo2.txt <==\nATOM 2\nATOM 36\nATOM 22\nATOM 12\n\n==> foo3.txt <==\nATOM 1\nATOM 87\n"
},
{
"answer_id": 74586787,
"author": "dawg",
"author_id": 298607,
"author_profile": "https://Stackoverflow.com/users/298607",
"pm_score": 0,
"selected": false,
"text": "perl -0777 -lnE 'while (/([\\s\\S]*?)^END\\s*/gm) {\n $cnt++;\n open(FH, \">file_${cnt}.txt\");\n print FH $1;\n close (FH);\n}' file \n ruby -e 'cnt=1; s=$<.read.scan(/([\\s\\S]*?)^END\\s*/m) { |b|\n File.write(\"file_#{cnt}.txt\", b.join(\"\"))\n cnt+=1\n}' file \n awk 'BEGIN { i=1; fn=sprintf(\"file_%s.txt\", i) }\n $1==\"END\" { close(fn); fn=sprintf(\"file_%s.txt\", ++i); next }\n {print > fn }\n' file \n sed while IFS= read -r -d $'\\3' block; do\n (( i++ ))\n printf \"%s\" \"$block\" > \"file_${i}.txt\"\ndone < <(sed '/^END[[:space:]]*$/N; s/^END[[:space:]]*/\\x3/' file)\n head file_*.txt\n==> file_1.txt <==\nATOM 1\nATOM 3\nATOM 25\n\n==> file_2.txt <==\nATOM 2\nATOM 36\nATOM 22\nATOM 12 \n\n==> file_3.txt <==\nATOM 1\nATOM 87\n\n# ^ Note final file has proper \\n termination\n"
},
{
"answer_id": 74588432,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 1,
"selected": false,
"text": "csplit -qz -f file -b '%04d.txt' --suppress-matched file '/END/' '{*}'\n file .txt END xxn csplit -qz --sup file '/END/' '{*}'\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74585996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19619903/"
] |
74,586,017
|
<p>Is there a way for me to dynamically multiply columns together based on a value in another column in Python? I'm using Polars if that makes a difference. For example, if <code>calendar_year</code> is 2018, I'd want to multiply columns <code>2018</code>, <code>2019</code>, <code>2020</code>, and <code>2021</code> together, but if <code>calendar_year</code> is 2019, I'd only want to multiply columns <code>2019</code>, <code>2020</code>, and <code>2021</code> together. I'd like to store the result in a new column called <code>product</code>. In the future, we'll have additional columns such as <code>2022</code>, and <code>2023</code>, so I'd love the ability to have my formula account for these new columns without having to go into the code base each year and add them to my product manually.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">id</th>
<th style="text-align: center;">...</th>
<th style="text-align: center;">calendar_year</th>
<th style="text-align: center;">2017</th>
<th style="text-align: center;">2018</th>
<th style="text-align: center;">2019</th>
<th style="text-align: center;">2020</th>
<th style="text-align: center;">2021</th>
<th style="text-align: center;">product</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">123</td>
<td style="text-align: center;">...</td>
<td style="text-align: center;">2018</td>
<td style="text-align: center;">0.998</td>
<td style="text-align: center;">0.997</td>
<td style="text-align: center;">0.996</td>
<td style="text-align: center;">0.995</td>
<td style="text-align: center;">0.994</td>
<td style="text-align: center;">0.9801</td>
</tr>
<tr>
<td style="text-align: center;">456</td>
<td style="text-align: center;">...</td>
<td style="text-align: center;">2019</td>
<td style="text-align: center;">0.993</td>
<td style="text-align: center;">0.992</td>
<td style="text-align: center;">0.991</td>
<td style="text-align: center;">0.990</td>
<td style="text-align: center;">0.989</td>
<td style="text-align: center;">0.9557</td>
</tr>
</tbody>
</table>
</div>
<p>Thanks in advance for the help!</p>
|
[
{
"answer_id": 74586036,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": -1,
"selected": false,
"text": "np.where(condition,then,else) df['2018_result'] = np.where(df.calendar_year.isin(['2019','2020','2021']),df.2019*df.2020*df.2021, 'add more calculations')\n"
},
{
"answer_id": 74586575,
"author": "ΩΠΟΚΕΚΡΥΜΜΕΝΟΣ",
"author_id": 20557510,
"author_profile": "https://Stackoverflow.com/users/20557510",
"pm_score": 3,
"selected": true,
"text": "calendar_year melt (\n df\n .select([\n 'id',\n 'calendar_year',\n pl.col('^20\\d\\d$')\n ])\n .melt(\n id_vars=['id', 'calendar_year'],\n variable_name='CY',\n value_name='CY factor',\n )\n .with_column(pl.col('CY').cast(pl.Int64))\n .filter(pl.col('CY') >= pl.col('calendar_year'))\n .groupby('id')\n .agg(\n pl.col('CY factor').product().alias('product')\n )\n)\n shape: (2, 2)\n┌─────┬──────────┐\n│ id ┆ product │\n│ --- ┆ --- │\n│ i64 ┆ f64 │\n╞═════╪══════════╡\n│ 456 ┆ 0.970298 │\n├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤\n│ 123 ┆ 0.982119 │\n└─────┴──────────┘\n id"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10760940/"
] |
74,586,028
|
<p>So I have this piece of code which I think can be improved but I don't know how</p>
<pre><code>IList<User> users = await _unitOfWork.UserRepository.SelectAllAsync();
users = users.Where(x => x.Field == MyField).ToList();
foreach (var user in users)
{
user.Active = IsActive;
await _unitOfWork.UserRepository.UpdateAsync(user);
}
</code></pre>
<p>What I want to achieve is:</p>
<pre><code>1) get all entries
2) filter them
3) on the filtered list, update their active status
</code></pre>
<p>How can I improve this code, both performance-wise and clean-wise?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74586073,
"author": "Avrohom Yisroel",
"author_id": 706346,
"author_profile": "https://Stackoverflow.com/users/706346",
"pm_score": 4,
"selected": true,
"text": "_unitOfWork DbContext IList<User> users = await _ctx.Users\n .Where(x => x.Field == MyField)\n .ToListAsync();\n\nforeach (var user in users)\n{\n user.Active = IsActive;\n}\n\nawait _ctx.SaveChangesAsync()\n"
},
{
"answer_id": 74586265,
"author": "Ashkan Khalaj",
"author_id": 15148777,
"author_profile": "https://Stackoverflow.com/users/15148777",
"pm_score": 0,
"selected": false,
"text": "where public async Task<List<T>> SelectAllAsync(Expression<Func<T, bool>>? filter = null)\n{\n IQueryable<T> query = dbSet;\n if (filter != null)\n {\n // now you can put your where clause here\n query = query.Where(filter);\n }\n return await query.ToListAsync();\n}\n IList<User> users = await _unitOfWork.UserRepository.SelectAllAsync(filter: x => x.Field == MyField);\n"
},
{
"answer_id": 74595367,
"author": "Justin Soderstrom",
"author_id": 6798222,
"author_profile": "https://Stackoverflow.com/users/6798222",
"pm_score": 1,
"selected": false,
"text": "await _ctx.Users\n .Where(u => u.Field == MyField)\n .ExecuteUpdateAsync(s => s.SetProperty(s => s.Active, s => IsActive));\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17274803/"
] |
74,586,032
|
<p>If I import an external module I can reference items in that module via the module variable from the import.</p>
<pre class="lang-js prettyprint-override"><code>import * as foo from 'foo';
foo.fn()
foo['fn']()
</code></pre>
<p>But how do I get a reference to the current module context if I want to do something similar?</p>
<pre class="lang-js prettyprint-override"><code>const thisModule = ???;
thisModule[`fn`]();
</code></pre>
|
[
{
"answer_id": 74586083,
"author": "Nikolay",
"author_id": 929187,
"author_profile": "https://Stackoverflow.com/users/929187",
"pm_score": 1,
"selected": false,
"text": "foo.ts export function foo() {\n console.log('foo');\n}\n\nimport * as self from './foo';\n\nself.foo();\n"
},
{
"answer_id": 74586150,
"author": "MarkE",
"author_id": 2281159,
"author_profile": "https://Stackoverflow.com/users/2281159",
"pm_score": 0,
"selected": false,
"text": "import * as local from './foo';\n\nexport function fn() {\n console.log('fn()');\n}\n\nexport class bar {\n constructor() {\n console.log('bar');\n }\n}\n\nlocal['fn']();\nnew local['bar']();\n\n// if using a variable\nconst c = 'bar';\nnew (<any>local>)[c]();\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281159/"
] |
74,586,033
|
<p>I am on codewars, here is the challenge:</p>
<blockquote>
<p>Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.<br />
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.</p>
</blockquote>
<p>Here is what I tried:</p>
<pre><code>const quarterOf = (month) => {
// Your code here
if (month <= 3) {
return 1
} else if (6 >= month > 3) {
return 2
} else if (9 >= month > 6) {
return 3
} else if (12 >= month > 9) {
return 4
}
}
</code></pre>
<p>This doesn't seem to work, I know I could assign each month a variable, but I'm trying to improve my skills, can someone explain why this does not work to me?</p>
|
[
{
"answer_id": 74586083,
"author": "Nikolay",
"author_id": 929187,
"author_profile": "https://Stackoverflow.com/users/929187",
"pm_score": 1,
"selected": false,
"text": "foo.ts export function foo() {\n console.log('foo');\n}\n\nimport * as self from './foo';\n\nself.foo();\n"
},
{
"answer_id": 74586150,
"author": "MarkE",
"author_id": 2281159,
"author_profile": "https://Stackoverflow.com/users/2281159",
"pm_score": 0,
"selected": false,
"text": "import * as local from './foo';\n\nexport function fn() {\n console.log('fn()');\n}\n\nexport class bar {\n constructor() {\n console.log('bar');\n }\n}\n\nlocal['fn']();\nnew local['bar']();\n\n// if using a variable\nconst c = 'bar';\nnew (<any>local>)[c]();\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20193212/"
] |
74,586,046
|
<p>Hi,</p>
<p>I have one array of objects with all items and their respective price like this:</p>
<pre><code>var items = [
{
"id": "001",
"name": "apple",
"price": 500
},
{
"id": "002",
"name": "banana",
"price": 700
},
{
"id": "003",
"name": "pear",
"price": 200
}
];
</code></pre>
<p>then I have a client's car like this:</p>
<pre><code>var cart = [{
"id": "001",
"qty": 2
},
{
"id": "002",
"qty": 3
},
{
"id": "003",
"qty": 4
}
];
</code></pre>
<p>client's credit is stored in a variable. I want to check the second array against the first one to get the total of the cart and make sure it wont exceed client's credit. Im not sure how to do it though. I tried:</p>
<pre><code>var mytotal=cart.map(d => {
var total=0;
items.forEach(rm => {
total = total+(d.qty*rm.price);
} return total;
});
if(credit >= total) {//dosomething}
</code></pre>
<p>but it didnt work. What is the right approach?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74586203,
"author": "Christian Vincenzo Traina",
"author_id": 1850851,
"author_profile": "https://Stackoverflow.com/users/1850851",
"pm_score": 2,
"selected": false,
"text": "const joined = items.map(item => ({...item, ...cart.find(c => c.id === item.id)}));\n find null ... const sum = joined.reduce((sum, curr) => sum += curr.price * curr.qty, 0);\n const sum = joined.reduce((sum, curr) => sum += (curr.price ?? 0) * (curr.qty ?? 0), 0);\n var items = [\n {\n \"id\": \"001\",\n \"name\": \"apple\",\n \"price\": 500\n},\n{\n \"id\": \"002\",\n \"name\": \"banana\",\n \"price\": 700\n},\n{\n \"id\": \"003\",\n \"name\": \"pear\",\n \"price\": 200\n }\n];\n\nvar cart = [{\n \"id\": \"001\",\n \"qty\": 2\n},\n{\n \"id\": \"002\",\n \"qty\": 3\n},\n{\n \"id\": \"003\",\n \"qty\": 4\n}\n];\n\n\nconst joined = items.map(item => ({...item, ...cart.find(c => c.id === item.id)}));\n\nconst sum = joined.reduce((sum, curr) => sum += curr.price * curr.qty, 0);\n\nconsole.log(`joined object is: `, joined);\nconsole.log(`sum is: ${sum}`);"
},
{
"answer_id": 74586438,
"author": "pilchard",
"author_id": 13762301,
"author_profile": "https://Stackoverflow.com/users/13762301",
"pm_score": 1,
"selected": false,
"text": "items Map id const itemLookup = new Map(items.map((item) => [item.id, item]))\n // Map(3) {\n // '001' => { id: '001', name: 'apple', price: 500 },\n // '002' => { id: '002', name: 'banana', price: 700 },\n // '003' => { id: '003', name: 'pear', price: 200 }\n // }\n getCartTotal t += (itemLookup.get(id)?.price ?? 0) * qty const getCartTotal = (cart) => {\n return cart.reduce((t, { id, qty }) => (\n t += itemLookup.get(id).price * qty\n ), 0);\n}\n const items = [{ \"id\": \"001\", \"name\": \"apple\", \"price\": 500 }, { \"id\": \"002\", \"name\": \"banana\", \"price\": 700 }, { \"id\": \"003\", \"name\": \"pear\", \"price\": 200 }];\n\nconst itemLookup = new Map(items.map(({ id, ...item }) => [id, { id, ...item }]));\n\nconst getCartTotal = (cart) => {\n return cart.reduce((total, { id, qty }) => (\n total += itemLookup.get(id).price * qty\n ), 0);\n}\n\nconst cart = [{ \"id\": \"001\", \"qty\": 2 }, { \"id\": \"002\", \"qty\": 3 }, { \"id\": \"003\", \"qty\": 4 }];\nconsole.log(getCartTotal(cart)); // 3900\n\ncart[0].qty += 2;\nconsole.log(getCartTotal(cart)); // 4900"
},
{
"answer_id": 74588029,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 2,
"selected": true,
"text": "itms subt ttl const items = [\n {\n \"id\": \"001\",\n \"name\": \"apple\",\n \"price\": 500\n},\n{\n \"id\": \"002\",\n \"name\": \"banana\",\n \"price\": 700\n},\n{\n \"id\": \"003\",\n \"name\": \"pear\",\n \"price\": 200\n }\n],\n cart = [{\n \"id\": \"001\",\n \"qty\": 2\n},\n{\n \"id\": \"002\",\n \"qty\": 3\n},\n{\n \"id\": \"003\",\n \"qty\": 4\n}\n];\n// Turn the items array into an object, facilitating a fast lookup:\nconst itms=items.reduce((a,c)=>(a[c.id]=c,a),{});\nlet ttl=0;\n// calculate the totals:\nconst res=cart.map(c=>{\n const p=itms[c.id], subt=c.qty*p.price;\n ttl+=subt;\n return {...c,...p,subt}\n})\n\n// Show the result:\nconsole.log(res,ttl);"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2230939/"
] |
74,586,075
|
<p>I've been trying to debug it but couldn't get anywhere I'm sure problem lies in rendering the value. otherwise it would be something else. I think its the screen component that is making problems or button component. I'm still a beginner in react that's why I cant clearly express where I'm going wrong</p>
<pre><code>class Calculator extends React.Component{
constructor(props){
super(props);
this.state={
question:"",
answer: ""
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
const value = e.target.value;
switch(value){
case "=" :{
if(this.state.question !== ""){
let result = "";
try {
result = eval(this.state.question);
}
catch(err){
this.setState({
answer: "MATH ERROR"
});
}
if(result ===undefined){
this.setState({answer: "MATH ERROR"})
}
else{
this.setState({
question: "",
answer: result
});
}
}
break;
}
case "del" : {
var str = this.state.question;
str = str.substr(0, str.length-1);
this.setState({
question: str
})
break;
}
case "AC" : {
this.setState({
question: " ",
answer: " "
});
break;
}
default:{
this.setState({
question: this.state.question += value
});
break;
}
}
}
render(){
return <div>
<div className="main-body">
<Screen question={this.state.question}/>
<Screen answer={this.state.answer}/>
<Buttons handleClick={this.handleClick}/>
</div>
</div>
}
}
class Screen extends React.Component{
constructor(props){
super(props);
this.state={
value: props.value
}
}
render(){
return<div>
<div className="screen">{this.state.value}</div>
</div>
}
}
class Buttons extends React.Component{
constructor(props){
super(props);
}
render(){
return <div>
<div className="btn-box">
<button value="0" className="btn-style" onClick={props.handleClick} >0</button>
<button value="del" className="btn-style" onClick={props.handleClick}>DEL</button>
<button value="AC"className="btn-style" onClick={props.handleClick}>AC</button>
<button value="1" className="btn-style" onClick={props.handleClick}>1</button>
<button value="2" className="btn-style" onClick={props.handleClick}>2</button>
<button value="3" className="btn-style" onClick={props.handleClick}>3</button>
<button value="4" className="btn-style" onClick={props.handleClick}>4</button>
<button value="5" className="btn-style" onClick={props.handleClick}>5</button>
<button value="6" className="btn-style" onClick={props.handleClick}>6</button>
<button value="7" className="btn-style" onClick={props.handleClick}>7</button>
<button value="8" className="btn-style" onClick={props.handleClick}>8</button>
<button value="9" className="btn-style" onClick={props.handleClick}>9</button>
<button value="+" className="btn-style" onClick={props.handleClick}>+</button>
<button value="-" className="btn-style" onClick={props.handleClick}>-</button>
<button value="=" className="btn-style" onClick={props.handleClick}>=</button>
<button value="/" className="btn-style" onClick={props.handleClick}>/</button>
<button value="*" className="btn-style" onClick={props.handleClick}>*</button>
<button value="." className="btn-style" onClick={props.handleClick}>.</button>
</div>
</div>
}
}
const container = document.getElementById("calculator");
ReactDOM.render(<Calculator />, container);
</code></pre>
<p>i think functionality between button and screen dosent work in my code. i've been trying to solve it for 2 days couldn't get anywhere</p>
|
[
{
"answer_id": 74586203,
"author": "Christian Vincenzo Traina",
"author_id": 1850851,
"author_profile": "https://Stackoverflow.com/users/1850851",
"pm_score": 2,
"selected": false,
"text": "const joined = items.map(item => ({...item, ...cart.find(c => c.id === item.id)}));\n find null ... const sum = joined.reduce((sum, curr) => sum += curr.price * curr.qty, 0);\n const sum = joined.reduce((sum, curr) => sum += (curr.price ?? 0) * (curr.qty ?? 0), 0);\n var items = [\n {\n \"id\": \"001\",\n \"name\": \"apple\",\n \"price\": 500\n},\n{\n \"id\": \"002\",\n \"name\": \"banana\",\n \"price\": 700\n},\n{\n \"id\": \"003\",\n \"name\": \"pear\",\n \"price\": 200\n }\n];\n\nvar cart = [{\n \"id\": \"001\",\n \"qty\": 2\n},\n{\n \"id\": \"002\",\n \"qty\": 3\n},\n{\n \"id\": \"003\",\n \"qty\": 4\n}\n];\n\n\nconst joined = items.map(item => ({...item, ...cart.find(c => c.id === item.id)}));\n\nconst sum = joined.reduce((sum, curr) => sum += curr.price * curr.qty, 0);\n\nconsole.log(`joined object is: `, joined);\nconsole.log(`sum is: ${sum}`);"
},
{
"answer_id": 74586438,
"author": "pilchard",
"author_id": 13762301,
"author_profile": "https://Stackoverflow.com/users/13762301",
"pm_score": 1,
"selected": false,
"text": "items Map id const itemLookup = new Map(items.map((item) => [item.id, item]))\n // Map(3) {\n // '001' => { id: '001', name: 'apple', price: 500 },\n // '002' => { id: '002', name: 'banana', price: 700 },\n // '003' => { id: '003', name: 'pear', price: 200 }\n // }\n getCartTotal t += (itemLookup.get(id)?.price ?? 0) * qty const getCartTotal = (cart) => {\n return cart.reduce((t, { id, qty }) => (\n t += itemLookup.get(id).price * qty\n ), 0);\n}\n const items = [{ \"id\": \"001\", \"name\": \"apple\", \"price\": 500 }, { \"id\": \"002\", \"name\": \"banana\", \"price\": 700 }, { \"id\": \"003\", \"name\": \"pear\", \"price\": 200 }];\n\nconst itemLookup = new Map(items.map(({ id, ...item }) => [id, { id, ...item }]));\n\nconst getCartTotal = (cart) => {\n return cart.reduce((total, { id, qty }) => (\n total += itemLookup.get(id).price * qty\n ), 0);\n}\n\nconst cart = [{ \"id\": \"001\", \"qty\": 2 }, { \"id\": \"002\", \"qty\": 3 }, { \"id\": \"003\", \"qty\": 4 }];\nconsole.log(getCartTotal(cart)); // 3900\n\ncart[0].qty += 2;\nconsole.log(getCartTotal(cart)); // 4900"
},
{
"answer_id": 74588029,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 2,
"selected": true,
"text": "itms subt ttl const items = [\n {\n \"id\": \"001\",\n \"name\": \"apple\",\n \"price\": 500\n},\n{\n \"id\": \"002\",\n \"name\": \"banana\",\n \"price\": 700\n},\n{\n \"id\": \"003\",\n \"name\": \"pear\",\n \"price\": 200\n }\n],\n cart = [{\n \"id\": \"001\",\n \"qty\": 2\n},\n{\n \"id\": \"002\",\n \"qty\": 3\n},\n{\n \"id\": \"003\",\n \"qty\": 4\n}\n];\n// Turn the items array into an object, facilitating a fast lookup:\nconst itms=items.reduce((a,c)=>(a[c.id]=c,a),{});\nlet ttl=0;\n// calculate the totals:\nconst res=cart.map(c=>{\n const p=itms[c.id], subt=c.qty*p.price;\n ttl+=subt;\n return {...c,...p,subt}\n})\n\n// Show the result:\nconsole.log(res,ttl);"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15780750/"
] |
74,586,081
|
<p>I am creating a custom JsonConverterto parse datetimeoffset, to fix utc issue with offset. I am following <a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-6-0" rel="nofollow noreferrer">MS doc</a></p>
<pre><code>using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SystemTextJsonSamples
{
public class DateTimeOffsetJsonConverter : JsonConverter<DateTimeOffset>
{
public override DateTimeOffset Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
DateTimeOffset.ParseExact(reader.GetString()!,
"MM/dd/yyyy", CultureInfo.InvariantCulture);
public override void Write(
Utf8JsonWriter writer,
DateTimeOffset dateTimeValue,
JsonSerializerOptions options) =>
writer.WriteStringValue(dateTimeValue.ToString(
"MM/dd/yyyy", CultureInfo.InvariantCulture));
}
}
</code></pre>
<p>I have registered the converter in the startup like so</p>
<pre><code>.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetConverter());
})
</code></pre>
<p>and here is my model</p>
<pre><code> [Serializable()]
public class Travel
{
public DateTimeOffset TravelTime { get; set; }
}
</code></pre>
<p>When i make call to my api, my custom converter for datetimeoffset is not getting called. Please note that i also have a customdate converter which is working as expected.</p>
<p>Why is my offsetdatetime converter not getting invoked when i serialize/deserialize.
I am using .Net core 6</p>
|
[
{
"answer_id": 74586112,
"author": "Poul Bak",
"author_id": 5741643,
"author_profile": "https://Stackoverflow.com/users/5741643",
"pm_score": 2,
"selected": false,
"text": "JsonConverter [JsonConverter(typeof(DateTimeOffsetJsonConverter))]\npublic DateTimeOffset TravelTime { get; set; }\n"
},
{
"answer_id": 74596971,
"author": "Rena",
"author_id": 11398810,
"author_profile": "https://Stackoverflow.com/users/11398810",
"pm_score": 0,
"selected": false,
"text": "DateTimeOffsetJsonConverter DateTimeOffsetConverter builder.Services.AddControllersWithViews().AddJsonOptions(options =>\n{\n options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));\n options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;\n options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());\n //options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetConverter());\n options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetJsonConverter());\n\n});\n application/json [FromBody] [HttpPost]\npublic IActionResult Index([FromBody]Travel model)\n{\n //do your stuff...\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600943/"
] |
74,586,098
|
<p>Implement a program to multiply two numbers, with the mention that the first can have a maximum of 2048 digits, and the second number is less than 100. HINT: multiplication can be done using repeated additions.</p>
<p>Up to a certain point, the program works using long double, but when working with larger numbers, only INF is displayed. Any ideas?</p>
|
[
{
"answer_id": 74586112,
"author": "Poul Bak",
"author_id": 5741643,
"author_profile": "https://Stackoverflow.com/users/5741643",
"pm_score": 2,
"selected": false,
"text": "JsonConverter [JsonConverter(typeof(DateTimeOffsetJsonConverter))]\npublic DateTimeOffset TravelTime { get; set; }\n"
},
{
"answer_id": 74596971,
"author": "Rena",
"author_id": 11398810,
"author_profile": "https://Stackoverflow.com/users/11398810",
"pm_score": 0,
"selected": false,
"text": "DateTimeOffsetJsonConverter DateTimeOffsetConverter builder.Services.AddControllersWithViews().AddJsonOptions(options =>\n{\n options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));\n options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;\n options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());\n //options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetConverter());\n options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetJsonConverter());\n\n});\n application/json [FromBody] [HttpPost]\npublic IActionResult Index([FromBody]Travel model)\n{\n //do your stuff...\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20609921/"
] |
74,586,124
|
<p>I need to calculate euclidian distance for every point in matrix and store it into the List. But it works too slow. How can I get it faster?</p>
<pre><code>public static char[,] fields = new char[10000, 10000]; // it contains different count of 't' and 'r' symbols
List<Tuple<int, int, double>> tuples = new List<Tuple<int, int, double>>();
for (int i = 0; i < 10000; i++)
{
for (int r = 0; r < 10000; r++)
{
if (fields[i, r] != 't')
tuples.Add(Tuple.Create(i, r, Math.Sqrt(Math.Pow(i - x, 2) + Math.Pow(r - y, 2))));
}
}
</code></pre>
|
[
{
"answer_id": 74586869,
"author": "Severin Pappadeux",
"author_id": 4044696,
"author_profile": "https://Stackoverflow.com/users/4044696",
"pm_score": 2,
"selected": false,
"text": "double Squared(int x) => (double)(x*x);\n Math.Sqrt(Squared(i - x) + Squared(r - y))\n int Squared(int x) => (x*x);\n Math.Sqrt((double)(Squared(i - x) + Squared(r - y)));\n"
},
{
"answer_id": 74605073,
"author": "phatfingers",
"author_id": 1031887,
"author_profile": "https://Stackoverflow.com/users/1031887",
"pm_score": 2,
"selected": true,
"text": "public static double[] preCalcSquares(int n) {\n double[] pre=new double[10000];\n for (int i = 0; i < 10000; i++)\n {\n pre[i]=(i-n)*(i-n);\n }\n return pre;\n}\n\n. . .\ndouble[] xSquares=preCalcSquares(x);\ndouble[] ySquares=preCalcSquares(y);\nfor (int i = 0; i < 10000; i++)\n{\n for (int r = 0; r < 10000; r++)\n {\n if (fields[i, r] != 't')\n tuples.Add(Tuple.Create(i, r, Math.Sqrt(xSquares[i] + ySquares[r])));\n }\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13858488/"
] |
74,586,171
|
<p>I am exploring .tga files.</p>
<p>I have fully working code that looks like this:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
const int letterHeight = 34;
const int spacer = 5;
typedef struct{
uint8_t idlength;
uint8_t colourmaptype;
uint8_t datatypecode;
uint16_t colourmaporigin;
uint16_t colourmaplength;
uint8_t colourmapdepth;
uint16_t x_origin;
uint16_t y_origin;
uint16_t width;
uint16_t height;
uint8_t bitsperpixel;
uint8_t imagedescriptor;
} TGA_Header;
typedef struct
{
uint8_t B;
uint8_t G;
uint8_t R;
} Pixel;
typedef struct{
TGA_Header header;
Pixel* pixels;
int width;
int height;
} Image;
void readHeader(TGA_Header* header, FILE* input_F){
fread(&header->idlength, sizeof(header->idlength), 1, input_F);
fread(&header->colourmaptype, sizeof(header->colourmaptype), 1, input_F);
fread(&header->datatypecode, sizeof(header->datatypecode), 1, input_F);
fread(&header->colourmaporigin, sizeof(header->colourmaporigin), 1, input_F);
fread(&header->colourmaplength, sizeof(header->colourmaplength), 1, input_F);
fread(&header->colourmapdepth, sizeof(header->colourmapdepth), 1, input_F);
fread(&header->x_origin, sizeof(header->x_origin), 1, input_F);
fread(&header->y_origin, sizeof(header->y_origin), 1, input_F);
fread(&header->width, sizeof(header->width), 1, input_F);
fread(&header->height, sizeof(header->height), 1, input_F);
fread(&header->bitsperpixel, sizeof(header->bitsperpixel), 1, input_F);
fread(&header->imagedescriptor, sizeof(header->imagedescriptor), 1, input_F);
}
void writeHeader(TGA_Header* header, FILE* output_F){
fwrite(&header->idlength, sizeof(header->idlength), 1, output_F);
fwrite(&header->colourmaptype, sizeof(header->colourmaptype), 1, output_F);
fwrite(&header->datatypecode, sizeof(header->datatypecode), 1, output_F);
fwrite(&header->colourmaporigin, sizeof(header->colourmaporigin), 1, output_F);
fwrite(&header->colourmaplength, sizeof(header->colourmaplength), 1, output_F);
fwrite(&header->colourmapdepth, sizeof(header->colourmapdepth), 1, output_F);
fwrite(&header->x_origin, sizeof(header->x_origin), 1, output_F);
fwrite(&header->y_origin, sizeof(header->y_origin), 1, output_F);
fwrite(&header->width, sizeof(header->width), 1, output_F);
fwrite(&header->height, sizeof(header->height), 1, output_F);
fwrite(&header->bitsperpixel, sizeof(header->bitsperpixel), 1, output_F);
fwrite(&header->imagedescriptor, sizeof(header->imagedescriptor), 1, output_F);
}
void image_load(Image* image, const char* path){
FILE* input_F = fopen(path, "rb");
readHeader(&image->header, input_F);
image->width = image->header.width;
image->height = image->header.height;
image->pixels = (Pixel*) malloc(sizeof(Pixel) * image->header.width * image->header.height);
fread(image->pixels, sizeof(Pixel), image->header.width * image->header.height, input_F);
fclose(input_F);
}
void image_create(Image* image, const char* path){
FILE* output_F = fopen(path, "wb");
writeHeader(&image->header, output_F);
fwrite(image->pixels, sizeof(Pixel), image->header.width * image->header.height, output_F);
fclose(output_F);
}
void load_letters(Image (*letters)[26], const char* f){
char path[101];
for(int i=0; i<26; i++){
strcpy(path, f);
strcat(path, "/");
char c[2] = {(char)(65+i), '\0'};
strcat(path, c);
strcat(path, ".tga\0");
image_load(&(*letters)[i], &path[0]);
}
}
void drawLetter(Image* image, Image* letter, int X, int Y){
Y += letterHeight - letter->height;
int letter_y = letter->height;
int letter_x = letter->width;
int image_x = image->width;
for(int y=0; y<letter_y; y++){
for(int x=0; x<letter_x; x++){
if(letter->pixels[y*letter_x+x].R != (uint8_t)0 || letter->pixels[y*letter_x+x].G != (uint8_t)0 || letter->pixels[y*letter_x+x].B != (uint8_t)0){
image->pixels[(y+Y)*image_x+(x+X)] = letter->pixels[y*letter_x+x];
}
}
}
}
void drawString(Image* image, Image (*letters)[26], char (*text)[101], int Y){
int dejToSzajzym = 0;
for(int i=0; i<strlen((*text)); i++){
dejToSzajzym += (*letters)[(int)(*text)[i] - 65].width;
}
dejToSzajzym = dejToSzajzym/2;
dejToSzajzym = image->width/2 - dejToSzajzym;
for(int i=0; i<strlen(*text); i++){
if((*text)[i] != ' '){
drawLetter(image, &(*letters)[(int)(*text)[i] - 65], dejToSzajzym, Y);
dejToSzajzym += (*letters)[(int)(*text)[i] - 65].width;
}else{
dejToSzajzym += 10;
}
}
}
int main(int argc, char* argv[]){
Image* image;
Image letters[26];
image_load(image, "img1.tga");
load_letters(&letters, "font");
/*
char buffer[100];
*/
drawString(image, &letters, "LOL", 5);
image_create(image, "image.tga");
free(image->pixels);
image->pixels = NULL;
for(int i=0; i<26; i++){
free(letters[i].pixels);
letters[i].pixels = NULL;
}
return 0;
}
</code></pre>
<p>But when I write the declaration of <code>buffer</code> as shown (could be anywhere in <code>main</code>) the program immediately breaks.
It doesn´t even need to do anything.</p>
<p><strong>error:</strong></p>
<pre><code>Unable to open 'memmove-vec-unaligned-erms.S': Unable to read file '/build/glibc-YYA7BZ/glibc-
2.31/sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S'
(Error: Unable to resolve non-existing file '/build/glibc-YYA7BZ/glibc-2.31/sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S').
</code></pre>
<p>BTW: Isn't there any easier way to copy the header data?</p>
|
[
{
"answer_id": 74586207,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": -1,
"selected": false,
"text": "memmove memmove void *memmove(void *sm, const void *tm, size_t n)\n{\n char *s = (char *)sm;\n const char *t = (const char *)tm;\n if (s > t) {\n s += n;\n t += n;\n while (n--)\n *--s = *--t;\n } else {\n while (n--)\n *s++ = *t++;\n }\n return sm;\n}\n memmove"
},
{
"answer_id": 74586879,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "Image *image; image image_load() buffer Image image; &image image_load() Image * fwrite(header, sizeof(*header), 1, fp) fread(header, sizeof(*header), 1, fp) datatypecode colourmapdepth colourmapdepth datatypecode uint16_t uint16_t uint8_t"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19121298/"
] |
74,586,200
|
<p>I did some Googling and figured out how to generate all Friday dates in a year.</p>
<pre><code># get all Fridays in a year
from datetime import date, timedelta
def allfridays(year):
d = date(year, 1, 1) # January 1st
d += timedelta(days = 8 - 2) # Friday
while d.year == year:
yield d
d += timedelta(days = 7)
for d in allfridays(2022):
print(d)
</code></pre>
<p>Result:</p>
<pre><code>2022-01-07
2022-01-14
2022-01-21
etc.
2022-12-16
2022-12-23
2022-12-30
</code></pre>
<p>Now, I'm trying to figure out how to loop through a range of rolling dates, so like 2022-01-07 + 60 days, then 2022-01-14 + 60 days, then 2022-01-21 + 60 days.</p>
<pre><code>step #1:
start = '2022-01-07'
end = '2022-03-08'
step #2:
start = '2022-01-14'
end = '2022-03-15'
</code></pre>
<p>Ideally, I want to pass in the start and end date loop, into another loop, which looks like this...</p>
<pre><code>price_data = []
for ticker in tickers:
try:
prices = wb.DataReader(ticker, start = start.strftime('%m/%d/%Y'), end = end.strftime('%m/%d/%Y'), data_source='yahoo')[['Adj Close']]
price_data.append(prices.assign(ticker=ticker)[['ticker', 'Adj Close']])
except:
print(ticker)
df = pd.concat(price_data)
</code></pre>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5212614/"
] |
74,586,208
|
<p>I want to be able to retain the margin between the boxes and have a single line of these squares with 3 maximum on screen, but no matter what command I put in they do not center. I have tried everything I can think of and I am at a loss. If someone could help me with this and explain why it was not working, I would be extremely grateful.</p>
<p>I have tried using display, position, align-item, align-content, etc, all to no avail. I have even tried to edit things such as margin to make sure all elements are centered at all times with a maximum of 3 squares on screen, but this did not work either.</p>
<p>Code (HTML, CSS)</p>
<p>`</p>
<pre><code> <div> <!-- Cadet Info Animation -->
<div class = 'cadetsAnimation'>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion Commander Lieutenant Colonel</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion XO Major</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion NCO Command Sergeant Major</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion S1 Captain</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion S2 Captain</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion S3 Captain</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion S4 Captain</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion S5 Captain</p>
</div>
</div>
<div class = 'cadetBox'>
<div class = 'cadetNameBox'>
<p class = 'cadetName'>Battalion S6 Captain</p>
</div>
</div>
</div>
</div>
</code></pre>
<pre><code>.cadetsAnimation {
position: relative;
margin: 50px;
left: 50%;
transform: translate(-50%, 0%);
}
.cadetBox {
position: relative;
display: inline-block;
width: 400px;
height: 400px;
margin: 5px;
background-color: #2148a8;
transition: 1s;
z-index: 1;
}
.cadetNameBox {
position: absolute;
width: 100%;
height: 50px;
top: 350px;
left: 50%;
transform: translate(-50%, 0%);
background-color: #0e0e0e;
opacity: 90%;
z-index: 2;
}
.cadetName {
position: relative;
display: inline-block;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-family: 'Montserrat', sans-serif;
font-size: 20rem;
color: #ffffff;
z-index: 3;
}
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20596146/"
] |
74,586,215
|
<p>I have a data of 199 test subjects (125 exposed subjects & 74 unexposed subjects).
Each subject has 3 different points attached to them.
I need to:</p>
<ol>
<li>Split the data into 2 groups (the exposed group & the unexposed group).</li>
<li>Find the average of the 3 points for each subject</li>
<li>Find the average of the averages for both groups</li>
</ol>
<pre><code>The data:
...1 babyStatus oneMin fiveMin tenMin
1 1 ZIKV-exposed 6 7 9
2 2 ZIKV-exposed 4 8 8
3 3 ZIKV-exposed 4 9 8
4 4 ZIKV-exposed 8 9 7
5 5 ZIKV-exposed 7 7 7
6 6 ZIKV-exposed 10 10 7
7 7 ZIKV-exposed 9 6 7
8 8 ZIKV-exposed 8 7 6
9 9 ZIKV-exposed 4 6 8
10 10 ZIKV-exposed 1 7 9
11 11 ZIKV-exposed 4 8 7
12 12 ZIKV-exposed 2 6 10
13 13 ZIKV-exposed 5 9 7
14 14 ZIKV-exposed 7 6 7
15 15 ZIKV-exposed 6 8 7
16 16 ZIKV-exposed 2 10 9
17 17 ZIKV-exposed 8 5 7
18 18 ZIKV-exposed 7 8 10
19 19 ZIKV-exposed 8 7 8
20 20 ZIKV-exposed 8 9 8
21 21 ZIKV-exposed 9 8 10
22 22 ZIKV-exposed 4 10 8
23 23 ZIKV-exposed 9 6 6
24 24 ZIKV-exposed 5 8 8
25 25 ZIKV-exposed 6 10 8
26 26 ZIKV-exposed 3 8 8
27 27 ZIKV-exposed 10 10 10
28 28 ZIKV-exposed 3 7 7
29 29 ZIKV-exposed 6 9 8
30 30 ZIKV-exposed 9 6 7
31 31 ZIKV-exposed 7 6 8
32 32 ZIKV-exposed 7 6 8
33 33 ZIKV-exposed 7 9 9
34 34 ZIKV-exposed 4 7 9
35 35 ZIKV-exposed 3 7 6
36 36 ZIKV-exposed 2 6 8
37 37 ZIKV-exposed 3 8 8
38 38 ZIKV-exposed 2 9 10
39 39 ZIKV-exposed 1 9 6
40 40 ZIKV-exposed 7 7 6
41 41 ZIKV-exposed 5 8 8
42 42 ZIKV-exposed 3 9 9
43 43 ZIKV-exposed 9 9 7
44 44 ZIKV-exposed 8 9 7
45 45 ZIKV-exposed 5 6 9
46 46 ZIKV-exposed 4 8 7
47 47 ZIKV-exposed 3 5 7
48 48 ZIKV-exposed 5 10 6
49 49 ZIKV-exposed 3 7 6
50 50 ZIKV-exposed 6 9 10
51 51 ZIKV-exposed 4 9 9
52 52 ZIKV-exposed 3 8 9
53 53 ZIKV-exposed 8 7 8
54 54 ZIKV-exposed 4 10 9
55 55 ZIKV-exposed 8 6 8
56 56 ZIKV-exposed 8 8 8
57 57 ZIKV-exposed 5 6 9
58 58 ZIKV-exposed 1 5 8
59 59 ZIKV-exposed 4 8 8
60 60 ZIKV-exposed 2 7 8
61 61 ZIKV-exposed 3 8 7
62 62 ZIKV-exposed 9 7 10
63 63 ZIKV-exposed 6 6 6
64 64 ZIKV-exposed 8 8 9
65 65 ZIKV-exposed 6 7 7
66 66 ZIKV-exposed 3 10 8
67 67 ZIKV-exposed 9 7 7
68 68 ZIKV-exposed 2 10 6
69 69 ZIKV-exposed 10 5 8
70 70 ZIKV-exposed 8 9 7
71 71 ZIKV-exposed 5 10 8
72 72 ZIKV-exposed 3 7 7
73 73 ZIKV-exposed 1 8 7
74 74 ZIKV-exposed 3 6 6
75 75 ZIKV-exposed 2 5 7
76 76 ZIKV-exposed 6 9 6
77 77 ZIKV-exposed 2 7 10
78 78 ZIKV-exposed 3 7 7
79 79 ZIKV-exposed 5 9 10
80 80 ZIKV-exposed 2 9 6
81 81 ZIKV-exposed 10 6 7
82 82 ZIKV-exposed 2 9 10
83 83 ZIKV-exposed 2 5 9
84 84 ZIKV-exposed 4 6 7
85 85 ZIKV-exposed 6 8 9
86 86 ZIKV-exposed 5 8 9
87 87 ZIKV-exposed 6 9 8
88 88 ZIKV-exposed 7 7 10
89 89 ZIKV-exposed 8 9 9
90 90 ZIKV-exposed 8 6 7
91 91 ZIKV-exposed 6 6 7
92 92 ZIKV-exposed 5 6 9
93 93 ZIKV-exposed 6 6 8
94 94 ZIKV-exposed 8 7 10
95 95 ZIKV-exposed 5 9 6
96 96 ZIKV-exposed 9 7 10
97 97 ZIKV-exposed 10 6 7
98 98 ZIKV-exposed 1 8 9
99 99 ZIKV-exposed 7 7 9
100 100 ZIKV-exposed 3 8 7
101 101 ZIKV-exposed 3 7 7
102 102 ZIKV-exposed 7 6 8
103 103 ZIKV-exposed 4 5 9
104 104 ZIKV-exposed 4 8 6
105 105 ZIKV-exposed 4 7 7
106 106 ZIKV-exposed 3 8 6
107 107 ZIKV-exposed 9 9 7
108 108 ZIKV-exposed 4 5 9
109 109 ZIKV-exposed 4 6 10
110 110 ZIKV-exposed 9 5 8
111 111 ZIKV-exposed 6 10 6
112 112 ZIKV-exposed 1 9 7
113 113 ZIKV-exposed 8 6 8
114 114 ZIKV-exposed 8 9 6
115 115 ZIKV-exposed 2 9 7
116 116 ZIKV-exposed 7 7 7
117 117 ZIKV-exposed 6 7 6
118 118 ZIKV-exposed 2 6 10
119 119 ZIKV-exposed 6 8 7
120 120 ZIKV-exposed 2 7 8
121 121 ZIKV-exposed 5 10 8
122 122 ZIKV-exposed 5 7 9
123 123 ZIKV-exposed 5 9 10
124 124 ZIKV-exposed 10 8 8
125 125 ZIKV-exposed 9 8 9
126 126 ZIKV-unexposed 8 9 10
127 127 ZIKV-unexposed 9 10 10
128 128 ZIKV-unexposed 7 10 10
129 129 ZIKV-unexposed 7 10 9
130 130 ZIKV-unexposed 10 10 9
131 131 ZIKV-unexposed 9 10 9
132 132 ZIKV-unexposed 9 10 9
133 133 ZIKV-unexposed 7 10 10
134 134 ZIKV-unexposed 8 10 9
135 135 ZIKV-unexposed 8 10 9
136 136 ZIKV-unexposed 9 9 9
137 137 ZIKV-unexposed 10 10 10
138 138 ZIKV-unexposed 7 10 10
139 139 ZIKV-unexposed 10 9 10
140 140 ZIKV-unexposed 7 9 10
141 141 ZIKV-unexposed 10 9 9
142 142 ZIKV-unexposed 6 10 9
143 143 ZIKV-unexposed 10 10 9
144 144 ZIKV-unexposed 7 10 9
145 145 ZIKV-unexposed 6 9 9
146 146 ZIKV-unexposed 6 10 9
147 147 ZIKV-unexposed 6 10 9
148 148 ZIKV-unexposed 7 9 9
149 149 ZIKV-unexposed 6 10 9
150 150 ZIKV-unexposed 9 9 9
151 151 ZIKV-unexposed 9 10 9
152 152 ZIKV-unexposed 8 10 10
153 153 ZIKV-unexposed 8 10 9
154 154 ZIKV-unexposed 7 10 9
155 155 ZIKV-unexposed 10 9 9
156 156 ZIKV-unexposed 8 10 10
157 157 ZIKV-unexposed 8 9 9
158 158 ZIKV-unexposed 10 10 9
159 159 ZIKV-unexposed 8 10 10
160 160 ZIKV-unexposed 8 10 9
161 161 ZIKV-unexposed 9 9 10
162 162 ZIKV-unexposed 7 10 10
163 163 ZIKV-unexposed 8 10 10
164 164 ZIKV-unexposed 10 9 9
165 165 ZIKV-unexposed 8 9 9
166 166 ZIKV-unexposed 7 9 10
167 167 ZIKV-unexposed 9 10 10
168 168 ZIKV-unexposed 8 10 10
169 169 ZIKV-unexposed 6 9 9
170 170 ZIKV-unexposed 8 10 10
171 171 ZIKV-unexposed 10 10 10
172 172 ZIKV-unexposed 7 10 9
173 173 ZIKV-unexposed 10 9 9
174 174 ZIKV-unexposed 7 10 10
175 175 ZIKV-unexposed 8 10 10
176 176 ZIKV-unexposed 9 9 10
177 177 ZIKV-unexposed 8 9 9
178 178 ZIKV-unexposed 7 9 9
179 179 ZIKV-unexposed 8 9 10
180 180 ZIKV-unexposed 8 9 10
181 181 ZIKV-unexposed 8 10 10
182 182 ZIKV-unexposed 7 10 9
183 183 ZIKV-unexposed 10 9 10
184 184 ZIKV-unexposed 10 10 9
185 185 ZIKV-unexposed 9 9 9
186 186 ZIKV-unexposed 9 10 9
187 187 ZIKV-unexposed 8 10 9
188 188 ZIKV-unexposed 8 9 10
189 189 ZIKV-unexposed 9 9 9
190 190 ZIKV-unexposed 9 9 10
191 191 ZIKV-unexposed 8 10 9
192 192 ZIKV-unexposed 10 9 9
193 193 ZIKV-unexposed 8 10 10
194 194 ZIKV-unexposed 6 10 9
195 195 ZIKV-unexposed 8 9 10
196 196 ZIKV-unexposed 7 10 9
197 197 ZIKV-unexposed 7 10 9
198 198 ZIKV-unexposed 7 10 9
199 199 ZIKV-unexposed 8 9 9
</code></pre>
<p>The final result I need:</p>
<pre><code>ZIKV-exposed: 6.928000
ZIKV-unexposed: 9.040541
</code></pre>
<p><a href="https://i.stack.imgur.com/LLh7R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LLh7R.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20610033/"
] |
74,586,272
|
<p>How to create 2 pull requests with different changes but in the same fork and at the same time?</p>
<p>I have tried to use the same branch, but the changes of the second PR are committed in the first one</p>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14650130/"
] |
74,586,281
|
<p>I am having a problem downloading monthly data for any ticker (or list of tickers). The dates in the index of the result show more than just the beginning of the month.</p>
<p>Example :</p>
<pre><code>import yfinance as yf
y_params = {
'tickers': 'AAPL',
'start': '2020-01-01',
'end': '2022-11-01',
'interval': '1mo'
}
data = yf.download(**y_params)['Adj Close']
</code></pre>
<p>The result I get for data is :</p>
<pre><code>Date
2020-01-01 75.805000
2020-02-01 66.951164
2020-02-07 NaN
2020-03-01 62.428360
2020-04-01 72.128082
2020-05-01 78.054482
2020-05-08 NaN
2020-06-01 89.801064
2020-07-01 104.630051
2020-08-01 127.060638
2020-08-07 NaN
2020-08-31 NaN
2020-09-01 114.239166
2020-10-01 107.383446
2020-11-01 117.435234
2020-11-06 NaN
2020-12-01 131.116058
2021-01-01 130.394714
2021-02-01 119.821625
2021-02-05 NaN
2021-03-01 120.881424
2021-04-01 130.094742
2021-05-01 123.315880
2021-05-07 NaN
2021-06-01 135.767838
2021-07-01 144.590378
2021-08-01 150.508408
2021-08-06 NaN
2021-09-01 140.478470
2021-10-01 148.718552
2021-11-01 164.106659
2021-11-05 NaN
2021-12-01 176.545380
2022-01-01 173.771454
2022-02-01 164.167221
2022-02-04 NaN
2022-03-01 173.823639
2022-04-01 156.940002
2022-05-01 148.169693
2022-05-06 NaN
2022-06-01 136.304245
2022-07-01 162.015808
2022-08-01 156.741913
2022-08-05 NaN
2022-09-01 137.971115
2022-10-01 153.086044
Name: Adj Close, dtype: float64
</code></pre>
<p>You see I have a lot of NaN for apparently random dates.
Am I doing something wrong or this is a bug ?</p>
<p>Thank you in advance</p>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13595548/"
] |
74,586,292
|
<p>I'm making an FPS game, but the bullets are not hitting in the right spot sometimes the bullets are below the crosshair but the next time it will be way off to the left.</p>
<p>I tried moving the gun tip (aka the thing that spawned the bullets) to aim at the center of the screen but then the bullets just went way of track. The code for launching the bullets is simple. If you can help me make the bullets land where the crosshair is, thank you if not thanks for reading this.</p>
<p>The Code</p>
<pre><code>if(Input.GetMouseButton(0) && Time.time >= nextTimeToFire)
{
Rigidbody rb = Instantiate(Bullet, GunTip.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(GunTip.forward * 500f, ForceMode.Impulse);
}
</code></pre>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19607501/"
] |
74,586,307
|
<p>I’m pretty new to PowerApps and need to migrate an Access database over to PowerApps, first of all it’s tables to Dataverse. It’s a typical use case for a model-driven app, with many relationships between the tables. All Access tables had an autogenerated ID field as their primary key.</p>
<p>I transferred all tables via Excel ex/import to Dataverse. Before importing,I renamed all ID fields (columns) to ID_old and let Dataverse create its own, autogenerated ID field for each table.</p>
<p>What I want to achieve is to re-establish all relationships between the tables, where the foreign key points to the new primary key provided by Dataverse, as I want to avoid double keys. As a first step I created relationships between the ID_old field and the corresponding (old) foreign key field in the related table.</p>
<p>In good old Access, I’d now simply run an update query, filling the new (yet empty) foreign key field with the new ID of the related table. Finally, I would change the relationship to the new primary and foreign keys and then delete the old ID fields.</p>
<p>Where I got stuck is the update query. I searched the net and found a couple of options like UpdateIf / Patch functions or Power Query or Excel ex/import and some more. They all read pretty complicated and time intensive and I think I must have overseen a very simple solution for such a pretty common problem.</p>
<p>Is there someone out there who might point me in the right (and simple) direction? Thanks!</p>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10600241/"
] |
74,586,318
|
<p>I'm trying to add items from the console input and scanner input to arraylists in java.
(To run the program user types Program ID)</p>
<p>The problem is that each time I run the program the contents of the arraylists update to only what has been entered that time. I would like the arraylists to contain all of the inputs that have been entered.</p>
<pre><code>public class User{
private static List<String> listNames = new ArrayList<String>();
private static List<Integer> listIds = new ArrayList<Integer>();
public static void main(String[] args)
{
int tempID = 5000;
if (args.length>0) tempID= Integer.parseInt(args[0]);
System.out.println("Login "+tempID);
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your Name : ");
tempName = scanner.nextLine();
User n = new User();
n.ID= tempID;
n.name = tempName;
listIds.add(n.ID);
listNames.add(n.name);
}
}
}
</code></pre>
<p>Does anyone know if this is possible?</p>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564816/"
] |
74,586,320
|
<p>I'm quite an infrequent coder, I hope my question won't be too obvious.</p>
<p>I have this very simple code to open some websites based on string (open website for a specific word) which works on Windows but somehow doesn't on my new computer with Mac OS. The tricky part is that I'm using Korean alphabet (I learn this language and therefore research websites to create flashcards) which somehow doesn't land properly in the website's URL when opening based on this simple script.</p>
<p>Example:</p>
<p>If I run python3 flashcard.py 가다 in my terminal, I would expect it to return (among others):
<a href="https://en.dict.naver.com/#/search?query=%EA%B0%80%EB%8B%A4" rel="nofollow noreferrer">https://en.dict.naver.com/#/search?query=가다</a></p>
<p>But unfortunately it returns:
<a href="https://en.dict.naver.com/#/search?query=??" rel="nofollow noreferrer">https://en.dict.naver.com/#/search?query=??</a>?</p>
<p>Which means Korean characters are somehow not recognised and changed to question marks.
I tested different parts of code with print statements, but everything down to for loop works fine, so the culprit is the webbrowser.open(). I tried encoding the strings, but then usually getting some errors and apparently I'm not doing it right.
I have Korean installed as language both in system & browser.</p>
<p>Has anyone of you experienced similar issue and has resolved the problem?</p>
<pre><code>import sys
import webbrowser
import pyperclip
# Get search word from command line
search_word = sys.argv[1]
# Sites to search for search word
sites = [
f'https://en.dict.naver.com/#/search?query={search_word}',
f'https://search.naver.com/search.naver?where=image&sm=tab_jum&query={search_word}',
# f'https://ko.dict.naver.com/#/search?query={search_word}',
f'https://forvo.com/word/{search_word}/#ko',
# f'https://translate.google.com/#view=home&op=translate&sl=ko&tl=en&text={search_word}',
# f'https://papago.naver.com/?sk=ko&tk=en&st={search_word}',
# f'https://ko.wiktionary.org/wiki/{search_word}#%ED%95%9C%EA%B5%AD%EC%96%B4'
]
# Search for search word in each site
for site in sites:
webbrowser.open(site)
# Copy search word to clipboard
pyperclip.copy(search_word)
</code></pre>
|
[
{
"answer_id": 74586269,
"author": "Selknam_CL",
"author_id": 13652570,
"author_profile": "https://Stackoverflow.com/users/13652570",
"pm_score": 0,
"selected": false,
"text": "from datetime import date, timedelta\n def allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7) \n list_dates = []\n for d in allfridays(2022):\n list_dates.append(d)\n \n\n add_days = map(lambda x: x+timedelta(days = 60),list_dates)\n print(list(add_days))\n"
},
{
"answer_id": 74586352,
"author": "ASH",
"author_id": 5212614,
"author_profile": "https://Stackoverflow.com/users/5212614",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n# get all Fridays in a year\nfrom datetime import date, timedelta\ndef allfridays(year):\n d = date(year, 1, 1) # January 1st \n d += timedelta(days = 8 - 2) # Friday \n while d.year == year:\n yield d\n d += timedelta(days = 7)\n\nlst=[]\nfor d in allfridays(2022):\n lst.append(d)\n \ndf = pd.DataFrame(lst)\nprint(type(df))\ndf.columns = ['my_dates']\n\n\ndf['sixty_ahead'] = df['my_dates'] + timedelta(days=60)\ndf \n\nResult:\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\netc.\n49 2022-12-16 2023-02-14\n50 2022-12-23 2023-02-21\n51 2022-12-30 2023-02-28\n"
},
{
"answer_id": 74586591,
"author": "Hai Vu",
"author_id": 459745,
"author_profile": "https://Stackoverflow.com/users/459745",
"pm_score": 1,
"selected": false,
"text": "import datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.date(year, 1, 1)\n while the_date.weekday() != FRIDAY:\n the_date = the_date + datetime.timedelta(days=1)\n return the_date\n\n\ndef friday_ranges(year, days_count):\n \"\"\"\n Generate date ranges that starts on first Friday of `year` and\n lasts for `days_count`.\n \"\"\"\n DURATION = datetime.timedelta(days=days_count)\n\n start_date = first_friday(year)\n end_date = start_date + DURATION\n\n while end_date.year == year:\n yield start_date, end_date\n start_date += WEEK\n end_date = start_date + DURATION\n\n\nfor start_date, end_date in friday_ranges(year=2022, days_count=60):\n # Do what you want with start_date and end_date\n print((start_date, end_date))\n (datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))\n(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))\n(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))\n...\n(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))\n(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))\n while"
},
{
"answer_id": 74592054,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\nyear = 2022\ndates = pd.date_range(start=f'{year}-01-01',end=f'{year}-12-31',freq='W-FRI')\ndf = pd.DataFrame({'my_dates':dates, 'sixty_ahead':dates + pd.Timedelta(days=60)})\n\nprint(df.head())\n'''\n my_dates sixty_ahead\n0 2022-01-07 2022-03-08\n1 2022-01-14 2022-03-15\n2 2022-01-21 2022-03-22\n3 2022-01-28 2022-03-29\n4 2022-02-04 2022-04-05\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6330675/"
] |
74,586,332
|
<p>I am trying to make put command line arguments by the user into an array but I am unsure how to approach it.</p>
<p>For example say I ran my program like this.</p>
<p>./program 1,2,3,4,5</p>
<p>How would I store 1 2 3 4 5 without the commas, and allow it to be passed to other functions to be used. I'm sure this has to do with using argv.</p>
<p>PS: NO space-separated, I want the numbers to parse into integers, I have an array of 200, and I want these numbers to be stored in the array as, arr[0] = 1, arr[1] = 2....</p>
<p>store 1 2 3 4 5 without the commas, and allow it to be passed to other functions to be used.</p>
|
[
{
"answer_id": 74586443,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 3,
"selected": true,
"text": "atoi ./program 1 2 3 4 5 argv argv atoi #include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[]) {\n for(int i = 1; i < argc; i++) {\n int num = atoi(argv[i]);\n printf(\"%d: %d\\n\", i, num);\n }\n}\n strtok atoi #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main(int argc, char *argv[]) {\n char *token = strtok(argv[1], \",\");\n while(token) {\n int num = atoi(token);\n printf(\"%d\\n\", num);\n token = strtok(NULL, \",\");\n }\n}\n ./program 1, 2, 3, 4, 5 1"
},
{
"answer_id": 74586734,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "strtol() strtok() atoi() long int INT_MAX INT_MIN int strtol() LONG_MIN LONG_MAX ./csa43 '1, 2, -3, 4, 5' read_value() read_value() #include <errno.h>\n#include <limits.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic int read_val(const char *str, char **eov, long *value)\n{\n errno = 0;\n char *eon;\n if (*str == '\\0')\n return -1;\n long val = strtol(str, &eon, 0);\n\n if (eon == str || (*eon != '\\0' && *eon != ',') ||\n ((val == LONG_MIN || val == LONG_MAX) && errno == ERANGE))\n {\n fprintf(stderr, \"Could not convert '%s' to an integer \"\n \"(the leftover string is '%s')\\n\", str, eon);\n return -1;\n }\n *value = val;\n *eov = eon;\n return 0;\n}\n\nint main(int argc, char **argv)\n{\n if (argc != 2)\n {\n fprintf(stderr, \"Usage: %s n1,n2,n3,...\\n\", argv[0]);\n exit(EXIT_FAILURE);\n }\n enum { NUM_ARRAY = 200 };\n long array[NUM_ARRAY];\n size_t nvals = 0;\n\n char *str = argv[1];\n char *eon;\n long val;\n while (read_val(str, &eon, &val) == 0 && nvals < NUM_ARRAY)\n {\n array[nvals++] = val;\n str = eon;\n if (str[0] == ',' && str[1] == '\\0')\n {\n fprintf(stderr, \"%s: trailing comma in number string\\n\", argv[1]);\n exit(EXIT_FAILURE);\n }\n else if (str[0] == ',')\n str++;\n }\n\n for (size_t i = 0; i < nvals; i++)\n printf(\"[%zu] = %ld\\n\", i, array[i]);\n\n return 0;\n}\n csa43 csa43.c $ csa43 1,2,3,4,5\n[0] = 1\n[1] = 2\n[2] = 3\n[3] = 4\n[4] = 5\n$\n"
},
{
"answer_id": 74586884,
"author": "David C. Rankin",
"author_id": 3422102,
"author_profile": "https://Stackoverflow.com/users/3422102",
"pm_score": 0,
"selected": false,
"text": "atoi() atoi (\"my-cow\"); 0 strtol() strtol() endptr ',' strtol() endptr nptr == endptr errno long int int #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <errno.h>\n\n#define NELEM 200 /* if you need a constant, #define one (or more) */\n\nint main (int argc, char **argv) {\n \n int arr[NELEM] = {0}, ndx = 0; /* array and index */\n char *nptr = argv[1], *endptr = nptr; /* nptr and endptr */\n \n if (argc < 2) { /* if no argument, handle error */\n fputs (\"error: no argument provided.\\n\", stderr);\n return 1;\n }\n else if (argc > 2) { /* warn on more than 2 arguments */\n fputs (\"warning: more than one argument provided.\\n\", stdout);\n }\n \n while (ndx < NELEM) { /* loop until all ints processed or arr full */\n int error = 0; /* flag indicating error occured */\n long tmp = 0; /* temp var to hold strtol return */\n char *onerr = NULL; /* pointer to next comma after error */\n errno = 0; /* reset errno */\n \n tmp = strtol (nptr, &endptr, 0); /* attempt conversion to long */\n \n if (nptr == endptr) { /* no digits converted */\n fputs (\"error: no digits converted.\\n\", stderr);\n error = 1;\n onerr = strchr (endptr, ',');\n }\n else if (errno) { /* overflow in conversion */\n perror (\"strtol conversion error\");\n error = 1;\n onerr = strchr (endptr, ',');\n }\n else if (tmp < INT_MIN || INT_MAX < tmp) { /* check in range of int */\n fputs (\"error: value outside range of int.\\n\", stderr);\n error = 1;\n onerr = strchr (endptr, ',');\n }\n \n if (!error) { /* error flag not set */\n arr[ndx++] = tmp; /* assign integer to arr, advance index */\n }\n else if (onerr) { /* found next ',' update endptr to next ',' */\n endptr = onerr;\n }\n else { /* no next ',' after error, break */\n break;\n }\n \n /* if at end of string - done, break loop */\n if (!*endptr) {\n break;\n }\n \n nptr = endptr + 1; /* update nptr to 1-past ',' */\n }\n \n for (int i = 0; i < ndx; i++) { /* output array content */\n printf (\" %d\", arr[i]);\n }\n putchar ('\\n'); /* tidy up with newline */\n}\n $ ./bin/argv1csvints 1,2,3,4,5\n 1 2 3 4 5\n $ ./bin/argv1csvints 1,my-cow,3,my-cat,5\nerror: no digits converted.\nerror: no digits converted.\n 1 3 5\n $ ./bin/argv1csvints my-cow\nerror: no digits converted.\n $ ./bin/argv1csvints\nerror: no argument provided.\n $ ./bin/argv1csvints 1,2,3,4,5 6,7,8\nwarning: more than one argument provided.\n 1 2 3 4 5\n strtok() strchr() strspn() strcspn() sscanf() \"%d%n\" strtol()"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19235554/"
] |
74,586,347
|
<p>I am having trouble understanding how to return <strong>null</strong> using: orElse: () => null
My method is the following:</p>
<pre><code>@override
Future<People> searchPeople({required String email}) async {
var user = auth.FirebaseAuth.instance.currentUser;
final docs = await FirebaseFirestore.instance
.collection('users')
.doc(user!.email)
.collection('people')
.where('hunting', isEqualTo: email)
.get();
final docData = docs.docs.map((doc) {
return People.fromSnapshot(doc);
});
var res = docData.firstWhere(
(element) => element.hunting == email,
orElse: () => null, // The return type 'Null' isn't a 'People', as required by the closure's
);
print(res);
return res;
}
</code></pre>
<p>The problem is that it throws the error: "<em>The return type 'Null' isn't a 'People', as required by the closure's</em>"</p>
<p>I have already read many answers here but all examples and answers apply only to return type string, int, etc... How to handle null when a type is an object (People)?
Already tried to use collection: firstWhereOrNull but the error persists...</p>
<p>Is something that I should change in my model?</p>
<pre><code>class People extends Equatable {
String? hunting;
String? username;
String? persona;
People({
this.hunting,
this.username,
this.persona,
});
@override
List<Object?> get props => [hunting, username, persona];
static People fromSnapshot(DocumentSnapshot snapshot) {
People people = People(
hunting: snapshot['hunting'],
username: snapshot['username'],
persona: snapshot['persona'],
);
return people;
}
Map<String, dynamic> toMap() {
return {
'hunter': hunting,
'username': username,
'persona': persona,
};
}
}
</code></pre>
<p>Thanks for any help!</p>
|
[
{
"answer_id": 74586384,
"author": "Oreofe Solarin",
"author_id": 13501704,
"author_profile": "https://Stackoverflow.com/users/13501704",
"pm_score": 2,
"selected": true,
"text": "var res = docData.firstWhere((element) => element.hunting == email, orElse: () => People(username: 'Not Found', hunting: 'Not Found', persona: 'Not Found'));\n"
},
{
"answer_id": 74586769,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 2,
"selected": false,
"text": "Iterable<E>.firstWhere E firstWhere(bool test(E element), {E orElse()?})\n Iterable<E>.firstWhere E E? E .firstWhere null null .firstWhere firstWhereOrNull package:collection searchPeople Future<People> Future<People?> firstWhereOrNull searchPeople null searchPeople null"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16515304/"
] |
74,586,356
|
<p>I have a Nifi Groovy Script. Assigns fields to nifi attributes but it define null if json values are empty. if json value is null I want to define attribute empty.</p>
<p>null attributes look like this ;</p>
<p><a href="https://i.stack.imgur.com/NW44r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NW44r.png" alt="enter image description here" /></a></p>
<p>I want to like this ;</p>
<p><a href="https://i.stack.imgur.com/52Pgo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/52Pgo.png" alt="enter image description here" /></a></p>
<p>this is the script i use ;</p>
<pre><code>import org.apache.commons.io.IOUtils
import java.nio.charset.*
def flowFile = session.get();
if (flowFile == null) {
return;
}
def slurper = new groovy.json.JsonSlurper()
def attrs = [:] as Map<String,String>
session.read(flowFile,
{ inputStream ->
def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
def obj = slurper.parseText(text)
obj.each {k,v ->
attrs[k] = v.toString()
}
} as InputStreamCallback)
flowFile = session.putAllAttributes(flowFile, attrs)
session.transfer(flowFile, REL_SUCCESS)
</code></pre>
|
[
{
"answer_id": 74586384,
"author": "Oreofe Solarin",
"author_id": 13501704,
"author_profile": "https://Stackoverflow.com/users/13501704",
"pm_score": 2,
"selected": true,
"text": "var res = docData.firstWhere((element) => element.hunting == email, orElse: () => People(username: 'Not Found', hunting: 'Not Found', persona: 'Not Found'));\n"
},
{
"answer_id": 74586769,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 2,
"selected": false,
"text": "Iterable<E>.firstWhere E firstWhere(bool test(E element), {E orElse()?})\n Iterable<E>.firstWhere E E? E .firstWhere null null .firstWhere firstWhereOrNull package:collection searchPeople Future<People> Future<People?> firstWhereOrNull searchPeople null searchPeople null"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8052213/"
] |
74,586,402
|
<p>Warning: Received <code>true</code> for a non-boolean attribute <code>show</code>.</p>
<p>If you want to write it to the DOM, pass a string instead: show="true" or show={value.toString()}.</p>
<pre><code>import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Container } from "react-bootstrap";
const FormTiket = () => {
const [show, setShow] = useState(true);
return (
<div className="bgForm">
<main className="py-5 px-5">
<Container>
<div className="parent">
<div className="div1 d-flex justify-content-center">
<h3 className="text-light">Booking</h3>
</div>
<div className="div2">
<a href="/login">
<h5>Login</h5>
</a>
</div>
<div className="div3 ">
<label className="form-label" htmlFor="typeDriver">
Dari
</label>
<div className="input-group mb-3">
<select
id="supir"
name="supir"
className="form-select bg-transparent border-dark"
>
<option value="">Pilih Tipe Driver</option>
<option value="true">Dengan Sopir</option>
<option value="false">Tanpa Sopir (Lepas Tangan)</option>
</select>
</div>
</div>
<div className="div4">
<label className="form-label" htmlFor="typeDriver">
Dari
</label>
<div className="input-group mb-3">
<select
id="supir"
name="supir"
className="form-select bg-transparent border-dark"
>
<option value="">Pilih Tipe Driver</option>
<option value="true">Dengan Sopir</option>
<option value="false">Tanpa Sopir (Lepas Tangan)</option>
</select>
</div>
</div>
<div className="div5">
<div className="d-flex">
<div className="form-check">
<input
onClick={() => setShow(true)}
className="form-check-input"
type="radio"
name="flexRadioDefault"
id="flexRadioDefault1"
/>
<label className="form-check-label" htmlFor="flexRadioDefault1">
Sekali Jalan
</label>
</div>
<div className="form-check">
<input
onClick={() => setShow(false)}
className="form-check-input"
type="radio"
name="flexRadioDefault"
id="flexRadioDefault1"
/>
<label className="form-check-label" htmlFor="flexRadioDefault1">
Pulang Pergi
</label>
</div>
</div>
<label className="form-label" htmlFor="typeDriver">
Date :
</label>
<div className="input-group mb-3">
<input
show={show}
type="date"
name="date"
id="date"
className="form-control bg-transparent border-dark"
placeholder="Pilih Tanggal"
/>
{!show && (
<input
type="date"
name="date"
id="date"
className="form-control bg-transparent border-dark"
placeholder="Pilih Tanggal"
/>
)}
</div>
</div>
<div className="div6">
<label className="form-label" htmlFor="tipeDriver">
Penumpang
</label>
<input
type="number"
name="penumpang"
id="penumpang"
className="form-control bg-transparent border-dark"
placeholder="Jumlah Penumpang"
/>
</div>
<div className="div7">
<label className="form-label" htmlFor="typeDriver">
Class
</label>
<div className="input-group mb-3">
<select
id="supir"
name="supir"
className="form-select bg-transparent border-dark"
>
<option value="">Pilih Tipe Driver</option>
<option value="true">Dengan Sopir</option>
<option value="false">Tanpa Sopir (Lepas Tangan)</option>
</select>
</div>
</div>
<div className="div8 d-grid">
<div
className="d-grid gap-2"
style={{ position: "relative", top: "30px" }}
>
<button
className="btn btn-light shadow py-2 mb-5 bg-body rounded"
type="submit"
>
<b>Cari Tiket</b>
</button>
</div>
</div>
</div>
</Container>
</main>
</div>
);
};
export default FormTiket;
</code></pre>
<p>id do something like this but still wrong idk why</p>
<pre><code> <input
show="true
type="date"
name="date"
id="date"
className="form-control bg-transparent border-dark"
placeholder="Pilih Tanggal"
/>
{show == false && (
<input
type="date"
name="date"
id="date"
className="form-control bg-transparent border-dark"
placeholder="Pilih Tanggal"
/>
)}
</div>
</code></pre>
|
[
{
"answer_id": 74586384,
"author": "Oreofe Solarin",
"author_id": 13501704,
"author_profile": "https://Stackoverflow.com/users/13501704",
"pm_score": 2,
"selected": true,
"text": "var res = docData.firstWhere((element) => element.hunting == email, orElse: () => People(username: 'Not Found', hunting: 'Not Found', persona: 'Not Found'));\n"
},
{
"answer_id": 74586769,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 2,
"selected": false,
"text": "Iterable<E>.firstWhere E firstWhere(bool test(E element), {E orElse()?})\n Iterable<E>.firstWhere E E? E .firstWhere null null .firstWhere firstWhereOrNull package:collection searchPeople Future<People> Future<People?> firstWhereOrNull searchPeople null searchPeople null"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20542112/"
] |
74,586,431
|
<p>I have created the following example function:</p>
<pre><code>my_function <- function(input_1, input_2){
a <- input_1*2
b <- input_2*3
c <- input_2*10
return(list(a = a, b = b, c = c))
}
</code></pre>
<p>How can I save all the elements of the resultant list to the working environment without doing so manually? To do it by brute force, I would just do:</p>
<pre><code>func_list <- my_function(input_1 = 5, input_2 = 6)
a <- func_list$a
b <- func_list$b
c <- func_list$c
</code></pre>
<p>In the project I'm working on, I need to return a lot of objects into the environment (either the global environment or in a function), so doing so manually every time is not feasible. Is there a way to return all the items at once? Would it be possible, also, to return all objects created within the function itself (and not have to make a return list that specifies every object)?</p>
|
[
{
"answer_id": 74586384,
"author": "Oreofe Solarin",
"author_id": 13501704,
"author_profile": "https://Stackoverflow.com/users/13501704",
"pm_score": 2,
"selected": true,
"text": "var res = docData.firstWhere((element) => element.hunting == email, orElse: () => People(username: 'Not Found', hunting: 'Not Found', persona: 'Not Found'));\n"
},
{
"answer_id": 74586769,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 2,
"selected": false,
"text": "Iterable<E>.firstWhere E firstWhere(bool test(E element), {E orElse()?})\n Iterable<E>.firstWhere E E? E .firstWhere null null .firstWhere firstWhereOrNull package:collection searchPeople Future<People> Future<People?> firstWhereOrNull searchPeople null searchPeople null"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13894990/"
] |
74,586,446
|
<p>I have a Spring REST project that is redirecting all requests to error page, even if they are mapped in the controller.</p>
<p>I reduced the code to the smallest possible version that produces the error:</p>
<p>Here is the project structure:</p>
<p><a href="https://i.stack.imgur.com/lEYg9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lEYg9.png" alt="enter image description here" /></a></p>
<p>Here is the Application class (The imports are removed to make the thread easier to read):</p>
<pre><code>package com.example.demo;
@Controller
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping("/greeting")
@ResponseBody
public String greeting() {
return "greeting";
}
}
</code></pre>
<p>Originally I hade a sperate controller from the App class, but moved the controller code to the app class to make sure that this is not a project structure problem
Here is the controller code (Tried with and without it, and received the same error):</p>
<pre><code>@Controller
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping("/hello")
@ResponseBody
public String greeting() {
return "greeting";
}
}
</code></pre>
<p>(Both http://localhost:8080/greeting as well as well http://localhost:8080/hello return the same error page)</p>
<p>Dependencies and plugins from the pom file:</p>
<pre><code> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</code></pre>
<p>(Tried with and without tomcat as dependency and nothing changed)</p>
<p>And lastly here is the error message I receive in the browser when I visit the links (http://localhost:8080/greeting and http://localhost:8080/hello):</p>
<pre><code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Nov 27 00:16:08 CET 2022
There was an unexpected error (type=Not Found, status=404).
</code></pre>
<p><strong>Edit:</strong>
After setting debug to true in project.properties, here is the error message I see in console (Worth mentioning that the project ran with no issues when I tried it on another system (Same OS)):</p>
<pre><code> GET "/greeting", parameters={}
Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]]
Resource not found
Completed 404 NOT_FOUND
"ERROR" dispatch for GET "/error", parameters={}
</code></pre>
<p>(Timestamps are removed to make reading easier)</p>
|
[
{
"answer_id": 74586384,
"author": "Oreofe Solarin",
"author_id": 13501704,
"author_profile": "https://Stackoverflow.com/users/13501704",
"pm_score": 2,
"selected": true,
"text": "var res = docData.firstWhere((element) => element.hunting == email, orElse: () => People(username: 'Not Found', hunting: 'Not Found', persona: 'Not Found'));\n"
},
{
"answer_id": 74586769,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 2,
"selected": false,
"text": "Iterable<E>.firstWhere E firstWhere(bool test(E element), {E orElse()?})\n Iterable<E>.firstWhere E E? E .firstWhere null null .firstWhere firstWhereOrNull package:collection searchPeople Future<People> Future<People?> firstWhereOrNull searchPeople null searchPeople null"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11342145/"
] |
74,586,478
|
<p>I'm using Google cloud build for CI/CD for my django app, and one requirement I have is to set my <code>GOOGLE_APPLICATION_CREDENTIALS</code> so I can perform authenticated actions in my Docker build. For example, I need to run <code>RUN python manage.py collectstatic --noinput</code> which requires access to my Google cloud storage buckets.</p>
<p>I've generated the credentials and it works well when simply including it in my (currently private) repo as a .json file, so it gets pulled into my Docker container with the <code>COPY . .</code> command and setting the env variable with <code>ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json</code>. Ultimately, I want to grab the credential value from secret manager and create the credentials file during the build stage, so I can completely remove the credentials from the repo. I tried doing this with editing <code>cloudbuild.yaml</code> (referencing <a href="https://cloud.google.com/build/docs/securing-builds/use-secrets" rel="nofollow noreferrer">this doc</a>) with various implementations of the <code>availableSecrets</code> config, <code>$$SECRET</code> syntax, and <code>build-args</code> in the docker build command and trying to access in Dockerfile with</p>
<pre><code>ARG GOOGLE_BUILD_CREDS
RUN echo "$GOOGLE_BUILD_CREDS" >> credentials.json
ENV GOOGLE_APPLICATION_CREDENTIALS=credentials.json
</code></pre>
<p>with no success.</p>
<p>If someone could advise me how to implement this in my cloudbuild.yaml and Dockerfile if its possible, or if there's another better solution altogether, would be much appreciated.</p>
<p>This is the relevant part of my <code>cloudbuild.yaml</code></p>
<pre><code>steps:
- name: gcr.io/cloud-builders/docker
args:
- build
- '--no-cache'
- '-t'
- '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
- .
- '-f'
- Dockerfile
id: Build
availableSecrets:
secretManager:
- versionName: projects/PROJECT_ID/secrets/CREDENTIALS/versions/latest
env: 'CREDENTIALS'
</code></pre>
|
[
{
"answer_id": 74586384,
"author": "Oreofe Solarin",
"author_id": 13501704,
"author_profile": "https://Stackoverflow.com/users/13501704",
"pm_score": 2,
"selected": true,
"text": "var res = docData.firstWhere((element) => element.hunting == email, orElse: () => People(username: 'Not Found', hunting: 'Not Found', persona: 'Not Found'));\n"
},
{
"answer_id": 74586769,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 2,
"selected": false,
"text": "Iterable<E>.firstWhere E firstWhere(bool test(E element), {E orElse()?})\n Iterable<E>.firstWhere E E? E .firstWhere null null .firstWhere firstWhereOrNull package:collection searchPeople Future<People> Future<People?> firstWhereOrNull searchPeople null searchPeople null"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15068475/"
] |
74,586,510
|
<p>I'm trying to create a <code>DelayedValue</code> future that resolves to a value after a certain time period has elapsed. To do this I simply wanted to wrap the <a href="https://docs.rs/tokio/latest/tokio/time/struct.Sleep.html" rel="nofollow noreferrer"><code>Sleep</code></a> future from <code>tokio</code> crate. But I get errors relating to <code>Pin</code> and no matter what I do I can't seem to call the <code>poll</code> method on the underlying <code>Sleep</code> member.</p>
<p>For reference here is a full program which fails to compile but should illustrate what I want:</p>
<pre><code>use futures::task::{Context, Poll};
use futures::Future;
use std::pin::Pin;
use tokio::time::{sleep, Sleep, Duration};
struct DelayedValue<T> {
value: T,
sleep: Sleep,
}
impl<T> Future for DelayedValue<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match &mut self.sleep.poll(cx) {
Poll::Ready(()) => Poll::Ready(self.value),
x => x,
}
}
}
#[tokio::main]
async fn main() {
let dv = DelayedValue {
value: 10_u8,
sleep: sleep(Duration::from_millis(5000)),
};
println!("waiting for delayed value");
let v = dv.await;
println!("delayed value: {}", v);
}
</code></pre>
<p>There is also a playground link: <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d573d8dcbbef5c99314d98cacc3d6c92" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d573d8dcbbef5c99314d98cacc3d6c92</a></p>
|
[
{
"answer_id": 74586555,
"author": "Chayim Friedman",
"author_id": 7884305,
"author_profile": "https://Stackoverflow.com/users/7884305",
"pm_score": 3,
"selected": true,
"text": "pin-project pin-project-lite pin_project_lite::pin_project! {\n struct DelayedValue<T> {\n value: Option<T>,\n #[pin]\n sleep: Sleep,\n }\n}\n\nimpl<T> Future for DelayedValue<T> {\n type Output = T;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n let this = self.project();\n match this.sleep.poll(cx) {\n Poll::Ready(()) => Poll::Ready(this.value.take().unwrap()),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n"
},
{
"answer_id": 74586716,
"author": "John Smith",
"author_id": 19495580,
"author_profile": "https://Stackoverflow.com/users/19495580",
"pm_score": 0,
"selected": false,
"text": "pin-project #[derive(Debug)]\npub struct DelayedValue<T: Copy> {\n value: T,\n sleep: Sleep,\n}\n\nimpl<T: Copy> DelayedValue<T> {\n pub fn new(value: T, sleep: Sleep) -> DelayedValue<T> {\n DelayedValue {value, sleep}\n }\n}\n\nimpl<T: Copy> Future for DelayedValue<T> {\n type Output = T;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n let x = self.value;\n let s = unsafe { self.map_unchecked_mut(|s| &mut s.sleep) };\n\n match &mut s.poll(cx) {\n Poll::Ready(()) => Poll::Ready(x),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n"
},
{
"answer_id": 74590417,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 0,
"selected": false,
"text": "map Sleep use futures::FutureExt;\nuse tokio::time::{ Duration, sleep };\n\n#[tokio::main]\nasync fn main() {\n let dv = sleep (Duration::from_millis (5000)).map (|_| { 10_u8 });\n\n println!(\"waiting for delayed value\");\n \n let v = dv.await;\n println!(\"delayed value: {}\", v);\n}\n"
}
] |
2022/11/26
|
[
"https://Stackoverflow.com/questions/74586510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19495580/"
] |
74,586,518
|
<p>The original list is:
<code>[['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]</code></p>
<p>I want to turn the list into a dictionary that look like this:
<code>{'James': ['100.00', '90.00', '85.50'], 'Nick': ['78.00', '85.00', '80.50'], 'William': ['95.50', '92.00', '100.00']}</code></p>
<p>Could anyone please tell me how to get the output for this?</p>
|
[
{
"answer_id": 74586535,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": -1,
"selected": false,
"text": "inp = [['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]\nd = {x[0]: x[1:4] for x in inp}\nprint(d)\n {'James': ['100.00', '90.00', '85.50'],\n 'Nick': ['78.00', '85.00', '80.50'],\n 'William': ['95.50', '92.00', '100.00']}\n"
},
{
"answer_id": 74586537,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 0,
"selected": false,
"text": "d = {}\nfor sublist in orig_list:\n new_key, new_value = sublist[0], sublist[1:]\n d[new_key] = new_value\n d = {sublist[0]: sublist[1:] for sublist in orig_list}\n"
},
{
"answer_id": 74586847,
"author": "hafshahfitri",
"author_id": 20576855,
"author_profile": "https://Stackoverflow.com/users/20576855",
"pm_score": -1,
"selected": false,
"text": "list1 = [\n ['James', '100.00', '90.00', '85.50'],\n ['Nick', '78.00', '85.00', '80.50'],\n ['William', '95.50', '92.00', '100.00']\n]\n\nlist1_to_dict = dict((x[0], x[1:]) for x in list1)\nprint(list1_to_dict)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20610291/"
] |
74,586,539
|
<p>required is not working. I have tried using required="required" or required={true}.</p>
<p>Can someone explain why or how to easily fix that?</p>
<pre><code>import React, { useState } from 'react';
export const Login = () => {
const [username, setUsername] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
console.log("test")
}
return(
<form className={styles["form-parent"]}>
{/* Title */}
<h1 className={styles["form-title"]}>Login</h1>
{/* Username */}
<div className={styles["form-input-group"]}>
<label> <b>Username:</b></label>
<input className={styles["form-input"]} type="text" name="username"
title="Enter your username in this field" required
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
{/* Login button */}
<div className={styles["form-input-group"]}>
<input className={styles["form-button"]} type="submit" value="Log In"
title="Click here to login"
onClick={(e) => handleSubmit(e)}
/>
</div>
</form>
);
}
</code></pre>
<p>I have been struggling on this for past 2 days now and internet has not been of much help.</p>
|
[
{
"answer_id": 74586535,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": -1,
"selected": false,
"text": "inp = [['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]\nd = {x[0]: x[1:4] for x in inp}\nprint(d)\n {'James': ['100.00', '90.00', '85.50'],\n 'Nick': ['78.00', '85.00', '80.50'],\n 'William': ['95.50', '92.00', '100.00']}\n"
},
{
"answer_id": 74586537,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 0,
"selected": false,
"text": "d = {}\nfor sublist in orig_list:\n new_key, new_value = sublist[0], sublist[1:]\n d[new_key] = new_value\n d = {sublist[0]: sublist[1:] for sublist in orig_list}\n"
},
{
"answer_id": 74586847,
"author": "hafshahfitri",
"author_id": 20576855,
"author_profile": "https://Stackoverflow.com/users/20576855",
"pm_score": -1,
"selected": false,
"text": "list1 = [\n ['James', '100.00', '90.00', '85.50'],\n ['Nick', '78.00', '85.00', '80.50'],\n ['William', '95.50', '92.00', '100.00']\n]\n\nlist1_to_dict = dict((x[0], x[1:]) for x in list1)\nprint(list1_to_dict)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12009093/"
] |
74,586,557
|
<p>I am creating a NodeJS boilerplate, as it was a framework, and I want to "register" the routes or endpoints when the application starts. I want to have an array of route classes and then instantiate them. Similar to what NestJs does with their <code>Controllers</code>. Then I want to loop through the collection and create instances of each <code>Route</code> passed in the array.
Something as the following:</p>
<pre><code>class RegisterRoutes() {
routes: [FirstRoute, SecondRoute];
instatiateRoutes() {
for (route in routes) {
new route()
}
}
}
</code></pre>
<p>Is this a good practice?</p>
|
[
{
"answer_id": 74586535,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": -1,
"selected": false,
"text": "inp = [['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]\nd = {x[0]: x[1:4] for x in inp}\nprint(d)\n {'James': ['100.00', '90.00', '85.50'],\n 'Nick': ['78.00', '85.00', '80.50'],\n 'William': ['95.50', '92.00', '100.00']}\n"
},
{
"answer_id": 74586537,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 0,
"selected": false,
"text": "d = {}\nfor sublist in orig_list:\n new_key, new_value = sublist[0], sublist[1:]\n d[new_key] = new_value\n d = {sublist[0]: sublist[1:] for sublist in orig_list}\n"
},
{
"answer_id": 74586847,
"author": "hafshahfitri",
"author_id": 20576855,
"author_profile": "https://Stackoverflow.com/users/20576855",
"pm_score": -1,
"selected": false,
"text": "list1 = [\n ['James', '100.00', '90.00', '85.50'],\n ['Nick', '78.00', '85.00', '80.50'],\n ['William', '95.50', '92.00', '100.00']\n]\n\nlist1_to_dict = dict((x[0], x[1:]) for x in list1)\nprint(list1_to_dict)\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2151892/"
] |
74,586,576
|
<p>I have a simple form that I have made with HTML and CSS. I want to validate it so that if a user is attempting to sign up they will get an error message underneath the input value if they make a mistake. I have already made a validation function for email but when I tried to test it out it did not display the error message at all.The error messages are in a span with class error and are set to <code>display: hidden</code> I wish for them to be revealed when the conditions are met.
Kindly help me out.</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>//variables declaration
const form = document.querySelector('form');
const emailField = form.querySelector('.emailField');
const emailInput = emailField.querySelector('email');
const usernameField = form.querySelector('.usernameField');
const usernameInput = usernameField.querySelector('username');
const schoolField = form.querySelector('.schoolField');
const schoolInput = schoolField.querySelector('school');
const passwordField = form.querySelector('.passwordField');
const passwordInput = passwordField.querySelector('password');
//Email validation
function checkEmail() {
const emaiPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!emailInput.value.classList.add(emaiPattern)) {
return emailInput.classList.add("invalid"); //Add invalid class if email value does not match
}
emailField.classList.remove("invalid"); //remove invalid class if email value does not match
}
//Calling function on form submit
form.addEventListener('submit', (e) => {
e.preventDefault(); //Preventing form submit
checkEmail();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Color Variables */
:root {
--blue: rgb(40,56,144);
--yellow: rgb(254,213,0);
--white: rgb(255,255,255);
}
/* page styles */
body
{
box-sizing: border-box;
background-color: rgb(40,56,144);
}
form button {
background-color: var(--blue) !important;
}
#logBtn {
background-color: var(--blue) !important;
color: var(--white) !important;
}
#signBtn {
background-color: var(--blue) !important;
color: var(--white) !important;
}
.column .error {
display: flex;
justify-content: left;
color: red;
margin-top: 6px;
display: none;
}
.column .error-icon {
margin-right: 6px;
font-size: 15px;
margin-top: 5px;
}
.invalid .error {
display: flex;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Website</title>
<link rel="stylesheet" href="style.css">
<link rel="icon" href="./favicon.ico" type="image/x-icon">
<!-- Form icons -->
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
</head>
<body>
<main>
<!-- Sign Up -->
<section>
<form method="/">
<div class="hero is-fullheight">
<div class="hero-body is-justify-content-center is-align-items-center">
<div class="columns is-flex is-flex-direction-column box">
<h1 class="title">Please enter your credentials</h1>
<div class="column emailField">
<label for="email">School Email</label>
<div class = "inputField">
<input id="signup-email" class="input is-primary email" type="text" placeholder="Email address" required>
</div>
<span class = "error email-error">
<i class='bx bx-error-circle error-icon'></i>
<p class = "error-text">Please enter a valid email</p></span>
</div>
<div class="column usernameField">
<label for="Name">Username</label>
<input id="signup-user" class="input is-primary username" type="username" placeholder="Username" required>
<span class = "error username-error">
<i class='bx bx-error-circle error-icon'></i>
<p class = "error-text">Please enter only alphabetical letters</p>
</span>
</div>
<div class="column schoolField">
<label for="Name">School ID</label>
<input id="signup-id" class="input is-primary schoolID" type="text" placeholder="School ID" required>
<span class = "error schoolID-error">
<i class='bx bx-error-circle error-icon'></i>
<p class = "error-text">School ID should only contain digits</p>
</span>
</div>
<div class="column passwordField">
<label for="Name">Password</label>
<input id="signup-pwd" class="input is-primary password" type="password" placeholder="Password" required>
<span class = "error password-error">
<i class='bx bx-error-circle error-icon'></i>
<p class = "error-text">Please enter at least 8 characters with a number, symbol<br> and uppercase and lowercase character</p>
</span>
<a href="#navbar" class="is-size-7 has-text-primary">forget password?</a>
</div>
<div class="column">
<button id="signup" class="button is-primary is-fullwidth" type="submit">Sign Up</button>
</div>
<div class="has-text-centered">
<p class="is-size-7"> Already have an account? <a href="login.html" class="has-text-primary">Login
</a>
</p>
</div>
</div>
</div>
</div>
</form>
</section>
</main>
<!-- <script type="module" src="index.js"></script> -->
<script src="main.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74586624,
"author": "Roby Raju Oommen",
"author_id": 14399782,
"author_profile": "https://Stackoverflow.com/users/14399782",
"pm_score": -1,
"selected": false,
"text": "if (!emailInput.value.match(emaiPattern)) {\n return emailInput.classList.add(\"invalid\"); //Add invalid class if email value does not match \n}\n"
},
{
"answer_id": 74586649,
"author": "Rocky Sims",
"author_id": 4123400,
"author_profile": "https://Stackoverflow.com/users/4123400",
"pm_score": 2,
"selected": true,
"text": "//<-- const emailInput = emailField.querySelector('email'); . !emailInput.value.classList.add(emaiPattern) return emailInput.classList.add(\"invalid\") invalid emailInput emailField //variables declaration\nconst form = document.querySelector('form');\nconst emailField = form.querySelector('.emailField');\nconst emailInput = emailField.querySelector('.email'); //<--\nconst usernameField = form.querySelector('.usernameField');\nconst usernameInput = usernameField.querySelector('username');\nconst schoolField = form.querySelector('.schoolField');\nconst schoolInput = schoolField.querySelector('school');\nconst passwordField = form.querySelector('.passwordField');\nconst passwordInput = passwordField.querySelector('password');\n\n\n//Email validation\nfunction checkEmail() {\n const emaiPattern = /^[^ ]+@[^ ]+\\.[a-z]{2,3}$/;\n if (!emailInput.value.match(emaiPattern)) { //<--\n //Add invalid class if email value does not match \n return emailField.classList.add(\"invalid\"); //<--\n }\n //remove invalid class if email value does not match \n emailField.classList.remove(\"invalid\");\n}\n//Calling function on form submit\nform.addEventListener('submit', (e) => {\n e.preventDefault(); //Preventing form submit\n checkEmail();\n});\n\n//<--\n//Calling function on email input text changes\nemailInput.addEventListener('input', () => {\n checkEmail();\n}); /* Color Variables */\n:root {\n --blue: rgb(40,56,144);\n --yellow: rgb(254,213,0);\n --white: rgb(255,255,255);\n}\n\n/* page styles */\nbody\n {\n box-sizing: border-box;\n background-color: rgb(40,56,144);\n}\n\nform button {\n background-color: var(--blue) !important;\n}\n\n#logBtn {\n background-color: var(--blue) !important;\n color: var(--white) !important;\n}\n\n#signBtn {\n background-color: var(--blue) !important;\n color: var(--white) !important;\n}\n\n.column .error {\n display: flex;\n justify-content: left;\n color: red;\n margin-top: 6px;\n display: none;\n}\n\n.column .error-icon {\n margin-right: 6px;\n font-size: 15px;\n margin-top: 5px;\n}\n\n.invalid .error {\n display: flex;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css\">\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <title>My Website</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"icon\" href=\"./favicon.ico\" type=\"image/x-icon\">\n <!-- Form icons -->\n <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>\n</head>\n\n<body>\n <main>\n <!-- Sign Up -->\n <section>\n <form method=\"/\">\n <div class=\"hero is-fullheight\">\n <div class=\"hero-body is-justify-content-center is-align-items-center\">\n <div class=\"columns is-flex is-flex-direction-column box\">\n <h1 class=\"title\">Please enter your credentials</h1>\n <div class=\"column emailField\">\n <label for=\"email\">School Email</label>\n <div class = \"inputField\">\n <input id=\"signup-email\" class=\"input is-primary email\" type=\"text\" placeholder=\"Email address\" required>\n </div>\n <span class = \"error email-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">Please enter a valid email</p></span>\n </div>\n <div class=\"column usernameField\">\n <label for=\"Name\">Username</label>\n <input id=\"signup-user\" class=\"input is-primary username\" type=\"username\" placeholder=\"Username\" required>\n <span class = \"error username-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">Please enter only alphabetical letters</p>\n </span>\n </div>\n <div class=\"column schoolField\">\n <label for=\"Name\">School ID</label>\n <input id=\"signup-id\" class=\"input is-primary schoolID\" type=\"text\" placeholder=\"School ID\" required>\n <span class = \"error schoolID-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">School ID should only contain digits</p>\n </span>\n </div>\n <div class=\"column passwordField\">\n <label for=\"Name\">Password</label>\n <input id=\"signup-pwd\" class=\"input is-primary password\" type=\"password\" placeholder=\"Password\" required>\n <span class = \"error password-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">Please enter at least 8 characters with a number, symbol<br> and uppercase and lowercase character</p>\n </span>\n <a href=\"#navbar\" class=\"is-size-7 has-text-primary\">forget password?</a>\n </div>\n <div class=\"column\">\n <button id=\"signup\" class=\"button is-primary is-fullwidth\" type=\"submit\">Sign Up</button>\n </div>\n <div class=\"has-text-centered\">\n <p class=\"is-size-7\"> Already have an account? <a href=\"login.html\" class=\"has-text-primary\">Login\n </a>\n </p>\n </div>\n </div>\n </div>\n </div>\n </form>\n </section>\n </main>\n <!-- <script type=\"module\" src=\"index.js\"></script> -->\n <script src=\"main.js\"></script>\n</body>\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13911746/"
] |
74,586,586
|
<p><strong>Condition:</strong> I have a model, created an empty table in the database, and I'm trying to create an html form that will fill in the fields of the corresponding columns of the table.
And here's what my app looks like:</p>
<p><strong>models.py</strong></p>
<pre><code>from django.db import models
class Cities(models.Model):
city = models.CharField(max_length=100)
def __str__(self):
return self.state
class Routes(models.Model):
route_name = models.CharField(max_length=50, default='Route')
lvl = models.IntegerField(default=0)
about = models.TextField(max_length=1500)
total_distance = models.IntegerField(default=0)
city = models.ForeignKey(Cities, on_delete=models.CASCADE)
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>from django.forms import ModelForm
from .models import Routes
class RouteForm(ModelForm):
class Meta:
model = Routes
fields = '__all__'
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from routes_form.forms import RouteForm
def getAbout(request):
if request.method == 'POST':
form = RouteForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'routes_form/form_page.html', {'form': form})
</code></pre>
<p><strong>form.html</strong></p>
<pre><code><form method="post">
{% csrf_token %}
<legend>
<h2>About</h2>
</legend>
{{ form }}
<input type="text" placeholder="Write more about the route: about waypoints, points of interest and warnings.">
<input type="submit" value="Send route">
</form>
</code></pre>
<p>I have already tried to do everything as indicated in the Django Forms documentation. But still something is wrong. Even at the moment of starting the server, it writes an error:</p>
<pre><code>cannot access local variable 'form' where it is not associated with a value
</code></pre>
|
[
{
"answer_id": 74586624,
"author": "Roby Raju Oommen",
"author_id": 14399782,
"author_profile": "https://Stackoverflow.com/users/14399782",
"pm_score": -1,
"selected": false,
"text": "if (!emailInput.value.match(emaiPattern)) {\n return emailInput.classList.add(\"invalid\"); //Add invalid class if email value does not match \n}\n"
},
{
"answer_id": 74586649,
"author": "Rocky Sims",
"author_id": 4123400,
"author_profile": "https://Stackoverflow.com/users/4123400",
"pm_score": 2,
"selected": true,
"text": "//<-- const emailInput = emailField.querySelector('email'); . !emailInput.value.classList.add(emaiPattern) return emailInput.classList.add(\"invalid\") invalid emailInput emailField //variables declaration\nconst form = document.querySelector('form');\nconst emailField = form.querySelector('.emailField');\nconst emailInput = emailField.querySelector('.email'); //<--\nconst usernameField = form.querySelector('.usernameField');\nconst usernameInput = usernameField.querySelector('username');\nconst schoolField = form.querySelector('.schoolField');\nconst schoolInput = schoolField.querySelector('school');\nconst passwordField = form.querySelector('.passwordField');\nconst passwordInput = passwordField.querySelector('password');\n\n\n//Email validation\nfunction checkEmail() {\n const emaiPattern = /^[^ ]+@[^ ]+\\.[a-z]{2,3}$/;\n if (!emailInput.value.match(emaiPattern)) { //<--\n //Add invalid class if email value does not match \n return emailField.classList.add(\"invalid\"); //<--\n }\n //remove invalid class if email value does not match \n emailField.classList.remove(\"invalid\");\n}\n//Calling function on form submit\nform.addEventListener('submit', (e) => {\n e.preventDefault(); //Preventing form submit\n checkEmail();\n});\n\n//<--\n//Calling function on email input text changes\nemailInput.addEventListener('input', () => {\n checkEmail();\n}); /* Color Variables */\n:root {\n --blue: rgb(40,56,144);\n --yellow: rgb(254,213,0);\n --white: rgb(255,255,255);\n}\n\n/* page styles */\nbody\n {\n box-sizing: border-box;\n background-color: rgb(40,56,144);\n}\n\nform button {\n background-color: var(--blue) !important;\n}\n\n#logBtn {\n background-color: var(--blue) !important;\n color: var(--white) !important;\n}\n\n#signBtn {\n background-color: var(--blue) !important;\n color: var(--white) !important;\n}\n\n.column .error {\n display: flex;\n justify-content: left;\n color: red;\n margin-top: 6px;\n display: none;\n}\n\n.column .error-icon {\n margin-right: 6px;\n font-size: 15px;\n margin-top: 5px;\n}\n\n.invalid .error {\n display: flex;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css\">\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <title>My Website</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"icon\" href=\"./favicon.ico\" type=\"image/x-icon\">\n <!-- Form icons -->\n <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>\n</head>\n\n<body>\n <main>\n <!-- Sign Up -->\n <section>\n <form method=\"/\">\n <div class=\"hero is-fullheight\">\n <div class=\"hero-body is-justify-content-center is-align-items-center\">\n <div class=\"columns is-flex is-flex-direction-column box\">\n <h1 class=\"title\">Please enter your credentials</h1>\n <div class=\"column emailField\">\n <label for=\"email\">School Email</label>\n <div class = \"inputField\">\n <input id=\"signup-email\" class=\"input is-primary email\" type=\"text\" placeholder=\"Email address\" required>\n </div>\n <span class = \"error email-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">Please enter a valid email</p></span>\n </div>\n <div class=\"column usernameField\">\n <label for=\"Name\">Username</label>\n <input id=\"signup-user\" class=\"input is-primary username\" type=\"username\" placeholder=\"Username\" required>\n <span class = \"error username-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">Please enter only alphabetical letters</p>\n </span>\n </div>\n <div class=\"column schoolField\">\n <label for=\"Name\">School ID</label>\n <input id=\"signup-id\" class=\"input is-primary schoolID\" type=\"text\" placeholder=\"School ID\" required>\n <span class = \"error schoolID-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">School ID should only contain digits</p>\n </span>\n </div>\n <div class=\"column passwordField\">\n <label for=\"Name\">Password</label>\n <input id=\"signup-pwd\" class=\"input is-primary password\" type=\"password\" placeholder=\"Password\" required>\n <span class = \"error password-error\">\n <i class='bx bx-error-circle error-icon'></i>\n <p class = \"error-text\">Please enter at least 8 characters with a number, symbol<br> and uppercase and lowercase character</p>\n </span>\n <a href=\"#navbar\" class=\"is-size-7 has-text-primary\">forget password?</a>\n </div>\n <div class=\"column\">\n <button id=\"signup\" class=\"button is-primary is-fullwidth\" type=\"submit\">Sign Up</button>\n </div>\n <div class=\"has-text-centered\">\n <p class=\"is-size-7\"> Already have an account? <a href=\"login.html\" class=\"has-text-primary\">Login\n </a>\n </p>\n </div>\n </div>\n </div>\n </div>\n </form>\n </section>\n </main>\n <!-- <script type=\"module\" src=\"index.js\"></script> -->\n <script src=\"main.js\"></script>\n</body>\n</html>"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20610312/"
] |
74,586,601
|
<p>I am trying to recreate a chart that is similar to this one using <code>ggplot2</code>, which categorizes historical yields (or spreads) into quartiles and presented in a stacked barchart.</p>
<p><a href="https://i.stack.imgur.com/2bOFZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2bOFZ.png" alt="enter image description here" /></a></p>
<p>I have the following dataset and code. The issue with my chart is that I think <code>geom_bar</code> is summing up all of the percentage values in the <code>Percent</code> column in my case as opposed to displaying it as a range.</p>
<pre><code>library(tidyverse)
data <- structure(list(date = structure(c(19307, 19310, 19311, 19312,
19313, 19314, 19317, 19318, 19319, 19321, 19307, 19310, 19311,
19312, 19313, 19314, 19317, 19318, 19319, 19321), class = "Date"),
Key = c("10 Year", "10 Year", "10 Year", "10 Year", "10 Year",
"10 Year", "10 Year", "10 Year", "10 Year", "10 Year", "30 Year",
"30 Year", "30 Year", "30 Year", "30 Year", "30 Year", "30 Year",
"30 Year", "30 Year", "30 Year"), Percent = c(3.813, 3.865,
3.799, 3.692, 3.775, 3.818, 3.825, 3.758, 3.706, 3.691, 4.058,
4.058, 3.982, 3.86, 3.89, 3.927, 3.905, 3.83, 3.739, 3.751
), Quartile = structure(c(3L, 4L, 2L, 1L, 2L, 3L, 4L, 2L,
1L, 1L, 4L, 4L, 3L, 2L, 2L, 3L, 2L, 1L, 1L, 1L), levels = c("1",
"2", "3", "4"), class = "factor")), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L), groups = structure(list(
Key = c("10 Year", "30 Year"), .rows = structure(list(1:10,
11:20), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))
data %>% {
ggplot(., aes(x = Key, y = Percent, fill = Quartile)) +
geom_bar(stat = 'identity', position = position_stack())
}
</code></pre>
<p><a href="https://i.stack.imgur.com/BGy6M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BGy6M.png" alt="enter image description here" /></a></p>
<p>A <code>geom_boxplot</code> would display it as a range, however the box only covers the interquartile range as opposed to the full min and max range like in the chart that I'm trying to recreate. Also, filling the boxplot by <code>Quartile</code> is much trickier.</p>
<pre><code>data %>% {
ggplot(., aes(x = Key, y = Percent)) +
geom_boxplot()
}
</code></pre>
<p><a href="https://i.stack.imgur.com/YebqH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YebqH.png" alt="enter image description here" /></a></p>
<p>Any ideas on how to go about getting this right?</p>
|
[
{
"answer_id": 74586940,
"author": "stomper",
"author_id": 9227264,
"author_profile": "https://Stackoverflow.com/users/9227264",
"pm_score": 3,
"selected": true,
"text": "df <- data %>%\n group_by(Key, Quartile) %>%\n mutate(min = min(Percent), max = max(Percent)) %>%\n arrange(Key, Quartile) %>%\n slice(1) %>%\n select(Key, Quartile, min, max) %>%\n ungroup() %>%\n mutate(Key = factor(Key))\n Key Quartile min max\n <fct> <fct> <dbl> <dbl>\n1 10 Year 1 3.69 3.71\n2 10 Year 2 3.76 3.80\n3 10 Year 3 3.81 3.82\n4 10 Year 4 3.82 3.86\n5 30 Year 1 3.74 3.83\n6 30 Year 2 3.86 3.90\n7 30 Year 3 3.93 3.98\n8 30 Year 4 4.06 4.06\n ggplot(df) +\n geom_rect(aes(xmin = (as.numeric(Key) -0.25), xmax = (as.numeric(Key) + 0.25), ymin = min, ymax = max, fill = Quartile)) +\n scale_x_continuous(breaks = seq(from = min(as.numeric(df$Key)), to = max(as.numeric(df$Key))), labels = unique(df$Key)) +\n theme_bw() +\n theme(panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank())\n"
},
{
"answer_id": 74587296,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "Percent Key Quartile geom_tile() Quartile fill Quartile color data <- data %>%\n group_by(Key, Quartile) %>%\n summarize(\n yrange = max(Percent) - min(Percent),\n Percent = median(Percent), \n .groups = \"drop\"\n )\n\nggplot(data) +\n geom_tile(\n aes(Key, Percent, width = .9, height = yrange, fill = Quartile, color = Quartile),\n size = 1\n ) +\n scale_fill_brewer(palette = \"RdBu\", aesthetics = c(\"fill\", \"color\")) +\n theme_classic() +\n theme(legend.position = \"bottom\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388534/"
] |
74,586,603
|
<pre><code>app-main-folder
/local
/__init__.py
/run.py
constants.py
</code></pre>
<p>I am trying to import from constants in <code>run.py</code> it's throwing this error</p>
<pre><code>Traceback (most recent call last):
File "local/run.py", line 4, in <module>
from init import app
File "/home/manavarthivenkat/ANUESERVICES--BACKEND/local/init.py", line 5, in <module>
from constants import BaseConstants
ModuleNotFoundError: No module named 'constants'
</code></pre>
|
[
{
"answer_id": 74586940,
"author": "stomper",
"author_id": 9227264,
"author_profile": "https://Stackoverflow.com/users/9227264",
"pm_score": 3,
"selected": true,
"text": "df <- data %>%\n group_by(Key, Quartile) %>%\n mutate(min = min(Percent), max = max(Percent)) %>%\n arrange(Key, Quartile) %>%\n slice(1) %>%\n select(Key, Quartile, min, max) %>%\n ungroup() %>%\n mutate(Key = factor(Key))\n Key Quartile min max\n <fct> <fct> <dbl> <dbl>\n1 10 Year 1 3.69 3.71\n2 10 Year 2 3.76 3.80\n3 10 Year 3 3.81 3.82\n4 10 Year 4 3.82 3.86\n5 30 Year 1 3.74 3.83\n6 30 Year 2 3.86 3.90\n7 30 Year 3 3.93 3.98\n8 30 Year 4 4.06 4.06\n ggplot(df) +\n geom_rect(aes(xmin = (as.numeric(Key) -0.25), xmax = (as.numeric(Key) + 0.25), ymin = min, ymax = max, fill = Quartile)) +\n scale_x_continuous(breaks = seq(from = min(as.numeric(df$Key)), to = max(as.numeric(df$Key))), labels = unique(df$Key)) +\n theme_bw() +\n theme(panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank())\n"
},
{
"answer_id": 74587296,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "Percent Key Quartile geom_tile() Quartile fill Quartile color data <- data %>%\n group_by(Key, Quartile) %>%\n summarize(\n yrange = max(Percent) - min(Percent),\n Percent = median(Percent), \n .groups = \"drop\"\n )\n\nggplot(data) +\n geom_tile(\n aes(Key, Percent, width = .9, height = yrange, fill = Quartile, color = Quartile),\n size = 1\n ) +\n scale_fill_brewer(palette = \"RdBu\", aesthetics = c(\"fill\", \"color\")) +\n theme_classic() +\n theme(legend.position = \"bottom\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11876237/"
] |
74,586,667
|
<p>I am trying to find the substring between the first 'a' char in email column before '@',</p>
<p>i have written the below sql-query ,</p>
<p>but i think i can do it in better way .</p>
<pre><code>SELECT
email,
CASE
WHEN
LENGTH(SUBSTR(email, 0, POSITION('@' IN email))) - LENGTH(REPLACE(SUBSTR(email, 0, POSITION('@' IN email)),
'a',
'')) > 1
THEN
SUBSTR(email,
POSITION('a' IN email) + 1,
POSITION('a' IN SUBSTR(email,
POSITION('a' IN email) + 1)) - 1)
ELSE ''
END AS deelstring
FROM
persoon
</code></pre>
<p>correction for the sql-query</p>
|
[
{
"answer_id": 74586940,
"author": "stomper",
"author_id": 9227264,
"author_profile": "https://Stackoverflow.com/users/9227264",
"pm_score": 3,
"selected": true,
"text": "df <- data %>%\n group_by(Key, Quartile) %>%\n mutate(min = min(Percent), max = max(Percent)) %>%\n arrange(Key, Quartile) %>%\n slice(1) %>%\n select(Key, Quartile, min, max) %>%\n ungroup() %>%\n mutate(Key = factor(Key))\n Key Quartile min max\n <fct> <fct> <dbl> <dbl>\n1 10 Year 1 3.69 3.71\n2 10 Year 2 3.76 3.80\n3 10 Year 3 3.81 3.82\n4 10 Year 4 3.82 3.86\n5 30 Year 1 3.74 3.83\n6 30 Year 2 3.86 3.90\n7 30 Year 3 3.93 3.98\n8 30 Year 4 4.06 4.06\n ggplot(df) +\n geom_rect(aes(xmin = (as.numeric(Key) -0.25), xmax = (as.numeric(Key) + 0.25), ymin = min, ymax = max, fill = Quartile)) +\n scale_x_continuous(breaks = seq(from = min(as.numeric(df$Key)), to = max(as.numeric(df$Key))), labels = unique(df$Key)) +\n theme_bw() +\n theme(panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank())\n"
},
{
"answer_id": 74587296,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "Percent Key Quartile geom_tile() Quartile fill Quartile color data <- data %>%\n group_by(Key, Quartile) %>%\n summarize(\n yrange = max(Percent) - min(Percent),\n Percent = median(Percent), \n .groups = \"drop\"\n )\n\nggplot(data) +\n geom_tile(\n aes(Key, Percent, width = .9, height = yrange, fill = Quartile, color = Quartile),\n size = 1\n ) +\n scale_fill_brewer(palette = \"RdBu\", aesthetics = c(\"fill\", \"color\")) +\n theme_classic() +\n theme(legend.position = \"bottom\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17177669/"
] |
74,586,703
|
<p>I have a query where I filter a column based on a <code>where</code> clause, like so:</p>
<pre><code>select * from table where col = val
</code></pre>
<p>What value do I set for <code>val</code> so that there is no filtering in the <code>where</code> clause (in which case the <code>where</code> clause is redundant)?</p>
|
[
{
"answer_id": 74586940,
"author": "stomper",
"author_id": 9227264,
"author_profile": "https://Stackoverflow.com/users/9227264",
"pm_score": 3,
"selected": true,
"text": "df <- data %>%\n group_by(Key, Quartile) %>%\n mutate(min = min(Percent), max = max(Percent)) %>%\n arrange(Key, Quartile) %>%\n slice(1) %>%\n select(Key, Quartile, min, max) %>%\n ungroup() %>%\n mutate(Key = factor(Key))\n Key Quartile min max\n <fct> <fct> <dbl> <dbl>\n1 10 Year 1 3.69 3.71\n2 10 Year 2 3.76 3.80\n3 10 Year 3 3.81 3.82\n4 10 Year 4 3.82 3.86\n5 30 Year 1 3.74 3.83\n6 30 Year 2 3.86 3.90\n7 30 Year 3 3.93 3.98\n8 30 Year 4 4.06 4.06\n ggplot(df) +\n geom_rect(aes(xmin = (as.numeric(Key) -0.25), xmax = (as.numeric(Key) + 0.25), ymin = min, ymax = max, fill = Quartile)) +\n scale_x_continuous(breaks = seq(from = min(as.numeric(df$Key)), to = max(as.numeric(df$Key))), labels = unique(df$Key)) +\n theme_bw() +\n theme(panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank())\n"
},
{
"answer_id": 74587296,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "Percent Key Quartile geom_tile() Quartile fill Quartile color data <- data %>%\n group_by(Key, Quartile) %>%\n summarize(\n yrange = max(Percent) - min(Percent),\n Percent = median(Percent), \n .groups = \"drop\"\n )\n\nggplot(data) +\n geom_tile(\n aes(Key, Percent, width = .9, height = yrange, fill = Quartile, color = Quartile),\n size = 1\n ) +\n scale_fill_brewer(palette = \"RdBu\", aesthetics = c(\"fill\", \"color\")) +\n theme_classic() +\n theme(legend.position = \"bottom\")\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3294195/"
] |
74,586,753
|
<p>After catching an exception, how do I continue the execution of a Java program?</p>
<p>So I made a program to insert or delete nodes from specific positions in Doubly Linked List. Those 2 methods throw exception.</p>
<p>In main method, I have started to insert some int values to positions. If I entered wrong pos value insert method throws an error and catch block handle.</p>
<ol>
<li>If I have entered 30 nodes and insert them to the correct positions except 1 Node.
-After false entry (i.e in the middle of the insertions) how can I continue to insert the rest?</li>
</ol>
<pre><code> public static void main(String[] args) {
LinkedList myList = new LinkedList();
try {
myList.Insert(1, 0);
myList.Insert(5, 54); // this is the false entry
myList.Insert(1, 0);
myList.Insert(1, 0);
} catch (Exception ex) {
System.out.println(ex.toString());
}
myList.Out();
myList.ReverseOutput();
}
}
</code></pre>
<pre><code>
So after execution, the output is 1. How can I make it [1 , 1 , 1]?
</code></pre>
|
[
{
"answer_id": 74586783,
"author": "Geoff",
"author_id": 9407148,
"author_profile": "https://Stackoverflow.com/users/9407148",
"pm_score": 1,
"selected": false,
"text": "int[] numsToInsert = new int[] {1, 0, 5, 54, 1, 0, 1, 0};\n\nfor(int i = 0; i < 8; i += 2){\n try {\n myList.Insert(numsToInsert[i], numsToInsert[i + 1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n"
},
{
"answer_id": 74586785,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 2,
"selected": false,
"text": "myList.insert static void insertAndIgnoreException(LinkedList list, int position, int value) {\n try {\n list.Insert(position, value);\n } catch (LinkedListInsertionException e) {\n System.out.println(e.getMessage());\n }\n}\n public static void main(String[] args) {\n LinkedList myList = new LinkedList();\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(5, 54); // this is the false entry\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(1, 0);\n\n myList.Out();\n myList.ReverseOutput(); \n\n }\n LinkedListInsertionException Exception NullPointerException insert Insert MyLinkedList LinkedList"
},
{
"answer_id": 74586946,
"author": "Jefferey Cave",
"author_id": 1961413,
"author_profile": "https://Stackoverflow.com/users/1961413",
"pm_score": 0,
"selected": false,
"text": " try {\n myList.Insert(1, 0);\n myList.Insert(5, 54); // this is the false entry\n \n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n myList.Insert(1, 0);\n myList.Insert(1, 0);\n myList.Out();\n myList.ReverseOutput(); \n try try try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(5, 54); // this is the false entry\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n int values[4][2] = {\n {1,0},\n {5,54},\n {1,0},\n {1,0}\n};\n\nfor(int v[2] : values){\n try {\n myList.Insert(v[0], v[1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n function TryInsert(list,pos,val){\n try {\n list.Insert(pos, val);\n return true;\n } catch (Exception ex) {\n System.out.println(ex.toString());\n return false;\n }\n}\n\n...\n\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 5, 54); // this is the false entry\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 1, 0);\n myList Insert Insert myList.TryInsert(1, 0);\nmyList.TryInsert(5, 54); // this is the false entry\nmyList.TryInsert(1, 0);\nmyList.TryInsert(1, 0);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13555930/"
] |
74,586,794
|
<p>I'm creating a plugin with Spiggot that every time you break a certain block or kill and entity it expands the border(The border is gonna start of being small). I have realised that after someone breaking a block they can replace in and repeat meaning the border will become infinite does anyone know a way I can prevent this I thought about using persistent variables inside the items but they were blocks that had been broken not items so I couldn't I don't think this question needs any code but for some reason if you need the main part here it is:</p>
<pre><code>@EventHandler
public void onBlockBreak(BlockBreakEvent e)
{
if (e.getBlock().getType() == Material.DIAMOND_ORE)
{
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "worldborder add 6 1");
}
if (e.getBlock().getType() == Material.IRON_ORE)
{
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "worldborder add 0.5 1");
}
if (e.getBlock().getType() == Material.GOLD_ORE)
{
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "worldborder add 1 1");
}
if (e.getBlock().getType() == Material.ANCIENT_DEBRIS)
{
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "worldborder add 0.5 1");
}
}
</code></pre>
|
[
{
"answer_id": 74586783,
"author": "Geoff",
"author_id": 9407148,
"author_profile": "https://Stackoverflow.com/users/9407148",
"pm_score": 1,
"selected": false,
"text": "int[] numsToInsert = new int[] {1, 0, 5, 54, 1, 0, 1, 0};\n\nfor(int i = 0; i < 8; i += 2){\n try {\n myList.Insert(numsToInsert[i], numsToInsert[i + 1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n"
},
{
"answer_id": 74586785,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 2,
"selected": false,
"text": "myList.insert static void insertAndIgnoreException(LinkedList list, int position, int value) {\n try {\n list.Insert(position, value);\n } catch (LinkedListInsertionException e) {\n System.out.println(e.getMessage());\n }\n}\n public static void main(String[] args) {\n LinkedList myList = new LinkedList();\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(5, 54); // this is the false entry\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(1, 0);\n\n myList.Out();\n myList.ReverseOutput(); \n\n }\n LinkedListInsertionException Exception NullPointerException insert Insert MyLinkedList LinkedList"
},
{
"answer_id": 74586946,
"author": "Jefferey Cave",
"author_id": 1961413,
"author_profile": "https://Stackoverflow.com/users/1961413",
"pm_score": 0,
"selected": false,
"text": " try {\n myList.Insert(1, 0);\n myList.Insert(5, 54); // this is the false entry\n \n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n myList.Insert(1, 0);\n myList.Insert(1, 0);\n myList.Out();\n myList.ReverseOutput(); \n try try try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(5, 54); // this is the false entry\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n int values[4][2] = {\n {1,0},\n {5,54},\n {1,0},\n {1,0}\n};\n\nfor(int v[2] : values){\n try {\n myList.Insert(v[0], v[1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n function TryInsert(list,pos,val){\n try {\n list.Insert(pos, val);\n return true;\n } catch (Exception ex) {\n System.out.println(ex.toString());\n return false;\n }\n}\n\n...\n\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 5, 54); // this is the false entry\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 1, 0);\n myList Insert Insert myList.TryInsert(1, 0);\nmyList.TryInsert(5, 54); // this is the false entry\nmyList.TryInsert(1, 0);\nmyList.TryInsert(1, 0);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19808007/"
] |
74,586,815
|
<p>I am having an issue with a fill-in-the-code digital textbook problem. All the code is permanent and cannot be changed, so the problem can only be solved by using the area that states //Write code here.</p>
<p>The problem asks to implement the removeOdd method.</p>
<pre><code>import java.util.Arrays;
public class RemoveTester
{
public static int removeOdd(int[] values, int size)
{
//Write code here
}
public static void main(String[] args)
{
int[] a = { 22, 98, 95, 46, 31, 53, 82, 24, 11, 19 };
int sizeBefore = 8;
int sizeAfter = removeOdd(a, sizeBefore);
System.out.print("a: [ ");
for (int i = 0; i < sizeAfter; i++)
{
System.out.print(a[i] + " ");
}
System.out.println("]");
System.out.println("Expected: [ 22 98 46 82 24 ]");
int[] b = { 23, 97, 95, 45, 31, 53, 81, 24, 11, 19 };
sizeBefore = 7;
sizeAfter = removeOdd(b, sizeBefore);
System.out.print("b: [ ");
for (int i = 0; i < sizeAfter; i++)
{
System.out.print(b[i] + " ");
}
System.out.println("]");
System.out.println("Expected: [ ]");
}
}
</code></pre>
<p>The way I tried to implement removeOdd is by doing:</p>
<pre><code>int evenCount = 0;
for(int i = 0; i<size; i++){
if(values[i]%2==0){
evenCount++;
}
}
int[] newValues = new int[evenCount];
int newCount =0;
for(int i = 0; i<evenCount; i++){
if(values[i]%2==0){
newValues[newCount] = values[i];
newCount++;
}
}
values = newValues;
return evenCount;
</code></pre>
<p>When the program is compiled and ran, main prints the beginning of the original a or b arrays instead of only the even elements in a or b. I cannot find a way to alter the original arrays within the method removeOdd into the new arrays with only their even elements. I can't think of any other way to do this either. Any help would be greatly appreciated!</p>
|
[
{
"answer_id": 74586783,
"author": "Geoff",
"author_id": 9407148,
"author_profile": "https://Stackoverflow.com/users/9407148",
"pm_score": 1,
"selected": false,
"text": "int[] numsToInsert = new int[] {1, 0, 5, 54, 1, 0, 1, 0};\n\nfor(int i = 0; i < 8; i += 2){\n try {\n myList.Insert(numsToInsert[i], numsToInsert[i + 1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n"
},
{
"answer_id": 74586785,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 2,
"selected": false,
"text": "myList.insert static void insertAndIgnoreException(LinkedList list, int position, int value) {\n try {\n list.Insert(position, value);\n } catch (LinkedListInsertionException e) {\n System.out.println(e.getMessage());\n }\n}\n public static void main(String[] args) {\n LinkedList myList = new LinkedList();\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(5, 54); // this is the false entry\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(1, 0);\n\n myList.Out();\n myList.ReverseOutput(); \n\n }\n LinkedListInsertionException Exception NullPointerException insert Insert MyLinkedList LinkedList"
},
{
"answer_id": 74586946,
"author": "Jefferey Cave",
"author_id": 1961413,
"author_profile": "https://Stackoverflow.com/users/1961413",
"pm_score": 0,
"selected": false,
"text": " try {\n myList.Insert(1, 0);\n myList.Insert(5, 54); // this is the false entry\n \n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n myList.Insert(1, 0);\n myList.Insert(1, 0);\n myList.Out();\n myList.ReverseOutput(); \n try try try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(5, 54); // this is the false entry\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n int values[4][2] = {\n {1,0},\n {5,54},\n {1,0},\n {1,0}\n};\n\nfor(int v[2] : values){\n try {\n myList.Insert(v[0], v[1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n function TryInsert(list,pos,val){\n try {\n list.Insert(pos, val);\n return true;\n } catch (Exception ex) {\n System.out.println(ex.toString());\n return false;\n }\n}\n\n...\n\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 5, 54); // this is the false entry\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 1, 0);\n myList Insert Insert myList.TryInsert(1, 0);\nmyList.TryInsert(5, 54); // this is the false entry\nmyList.TryInsert(1, 0);\nmyList.TryInsert(1, 0);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20610572/"
] |
74,586,816
|
<p>How to get specific word from string array ?</p>
<pre><code>let array= [
'age 19 - Donna',
'age 20 - James'
];
let getNumber = [] //19 and 20
let getName= [] // Donna and James
for(let i = 0; i < array.length; i++){
getNumber[i] = text[i].split(" ", 2)[1];
getName[i] = text[i].split(",", 5);
}
document.getElementById("demo").innerHTML = getNumber;
document.getElementById("demo2").innerHTML = getName;
</code></pre>
<p>current result:</p>
<blockquote>
<p>19,20</p>
<p>age 19 - Donna,age 20 - James</p>
</blockquote>
<p>desired result:</p>
<blockquote>
<p>19,20</p>
<p>Donna,James</p>
</blockquote>
|
[
{
"answer_id": 74586783,
"author": "Geoff",
"author_id": 9407148,
"author_profile": "https://Stackoverflow.com/users/9407148",
"pm_score": 1,
"selected": false,
"text": "int[] numsToInsert = new int[] {1, 0, 5, 54, 1, 0, 1, 0};\n\nfor(int i = 0; i < 8; i += 2){\n try {\n myList.Insert(numsToInsert[i], numsToInsert[i + 1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n"
},
{
"answer_id": 74586785,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 2,
"selected": false,
"text": "myList.insert static void insertAndIgnoreException(LinkedList list, int position, int value) {\n try {\n list.Insert(position, value);\n } catch (LinkedListInsertionException e) {\n System.out.println(e.getMessage());\n }\n}\n public static void main(String[] args) {\n LinkedList myList = new LinkedList();\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(5, 54); // this is the false entry\n insertAndIgnoreException(1, 0);\n insertAndIgnoreException(1, 0);\n\n myList.Out();\n myList.ReverseOutput(); \n\n }\n LinkedListInsertionException Exception NullPointerException insert Insert MyLinkedList LinkedList"
},
{
"answer_id": 74586946,
"author": "Jefferey Cave",
"author_id": 1961413,
"author_profile": "https://Stackoverflow.com/users/1961413",
"pm_score": 0,
"selected": false,
"text": " try {\n myList.Insert(1, 0);\n myList.Insert(5, 54); // this is the false entry\n \n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n myList.Insert(1, 0);\n myList.Insert(1, 0);\n myList.Out();\n myList.ReverseOutput(); \n try try try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(5, 54); // this is the false entry\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n try {\n myList.Insert(1, 0);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n int values[4][2] = {\n {1,0},\n {5,54},\n {1,0},\n {1,0}\n};\n\nfor(int v[2] : values){\n try {\n myList.Insert(v[0], v[1]);\n } catch (Exception ex) {\n System.out.println(ex.toString());\n }\n}\n function TryInsert(list,pos,val){\n try {\n list.Insert(pos, val);\n return true;\n } catch (Exception ex) {\n System.out.println(ex.toString());\n return false;\n }\n}\n\n...\n\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 5, 54); // this is the false entry\nTryInsert(mylist, 1, 0);\nTryInsert(mylist, 1, 0);\n myList Insert Insert myList.TryInsert(1, 0);\nmyList.TryInsert(5, 54); // this is the false entry\nmyList.TryInsert(1, 0);\nmyList.TryInsert(1, 0);\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20577523/"
] |
74,586,825
|
<p>Here's the script I'm using to find all the matching rows from <code>mSheet</code> with the values of <code>searchText</code> and insert <code>value1</code> in all the matching rows in column(B) and that is working really good.<br />
So what I'm trying to do is also insert the <code>value</code> from <code>value2</code> on the same matching rows in column(M) I've tried different ways but just can't seem to get it right.</p>
<pre><code>function insert(){
var mSheet = SpreadsheetApp.openById('1rAQ0t--PPK0-wovqdc')
var ss = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var searchText = ss.getRange('A1').getValue()
var value1 = ss.getRange('B1').getValue()
var value2 = ss.getRange('C1').getValue()
var sheet = mSheet.getSheetByName('Data');
if(searchText!=''){
var rangeList = sheet
.getRange('C1:C')
.createTextFinder(searchText)
.matchEntireCell(true)
.findAll()
.map((r) => r.offset(0, -1).getA1Notation());
sheet.getRangeList(rangeList).setValue(value1);
console.log(searchText,value1,rangeList);
}
}
</code></pre>
|
[
{
"answer_id": 74586912,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": false,
"text": " var rangeList2 = rangeList.map((n) => n.replace('B','M'))\n sheet.getRangeList(rangeList2).setValue(value2);\n"
},
{
"answer_id": 74586972,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 1,
"selected": true,
"text": "M if(searchText!=''){\n var rangeList = sheet\n .getRange('C1:C')\n .createTextFinder(searchText)\n .matchEntireCell(true)\n .findAll();\n //Creates two range lists.\n var list1 = rangeList.map(r => r.offset(0, -1).getA1Notation());\n var list2 = rangeList.map(r => r.offset(0, 10).getA1Notation());\n sheet.getRangeList(list1).setValue(value1);\n sheet.getRangeList(list2).setValue(value2);\n console.log(searchText,value1,rangeList);\n }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244713/"
] |
74,586,850
|
<p>what I want to do is get network data by firebase AddSnapshotListener, store it in room database and get data from room database</p>
<p>so what I done is down here...</p>
<pre><code>// in dataSource
fun getNetworkData(id : String) = callbackFlow<Data> {
....
streamingApi.get{
trySend(it)
}
...
}
//in repository
fun insertData(id : String) = getNetworkData(id).map{
roomDao.insert(it)
}
fun getRoomData() = roomDao.get()
// viewmodel
viewmodelScope.launch{
repository.insertData(id).collect()
repository.getRoomData().onEach{
updateUi()
...
}
}
</code></pre>
<p>but is it possible collect at once like this?</p>
<pre><code>fun insertAndGet() = flow{
insertData().collect()
getRoomData().collect()
}
</code></pre>
<p>and is it right way collect flow in repository?</p>
|
[
{
"answer_id": 74586912,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": false,
"text": " var rangeList2 = rangeList.map((n) => n.replace('B','M'))\n sheet.getRangeList(rangeList2).setValue(value2);\n"
},
{
"answer_id": 74586972,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 1,
"selected": true,
"text": "M if(searchText!=''){\n var rangeList = sheet\n .getRange('C1:C')\n .createTextFinder(searchText)\n .matchEntireCell(true)\n .findAll();\n //Creates two range lists.\n var list1 = rangeList.map(r => r.offset(0, -1).getA1Notation());\n var list2 = rangeList.map(r => r.offset(0, 10).getA1Notation());\n sheet.getRangeList(list1).setValue(value1);\n sheet.getRangeList(list2).setValue(value2);\n console.log(searchText,value1,rangeList);\n }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16266635/"
] |
74,586,859
|
<p>I'm looking for a method that would allow me to wait for the network idle after clicking a button or some action.
there is a way to wait for the network idle after clicking?
<code>page.locator("text=Click").click() //some method that wait network is idle after clicking the button</code></p>
<p>I tried waitForLoadState works only if there is navigation.
waitForResponse works on specific requests but it's not good for me.</p>
|
[
{
"answer_id": 74586912,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": false,
"text": " var rangeList2 = rangeList.map((n) => n.replace('B','M'))\n sheet.getRangeList(rangeList2).setValue(value2);\n"
},
{
"answer_id": 74586972,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 1,
"selected": true,
"text": "M if(searchText!=''){\n var rangeList = sheet\n .getRange('C1:C')\n .createTextFinder(searchText)\n .matchEntireCell(true)\n .findAll();\n //Creates two range lists.\n var list1 = rangeList.map(r => r.offset(0, -1).getA1Notation());\n var list2 = rangeList.map(r => r.offset(0, 10).getA1Notation());\n sheet.getRangeList(list1).setValue(value1);\n sheet.getRangeList(list2).setValue(value2);\n console.log(searchText,value1,rangeList);\n }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20610644/"
] |
74,586,876
|
<p>Good evening. I have one GameObject, and I need to change its pitch (and do not impact on its yaw and roll). I have a quaternion which stores rotation from which I need to get the needed pitch and set to my game object. But the operation of cast from a Quaternion to Euler angles is not unique (one quaternion can be reperesented as multiple triples of Euler angles). Is it possible to do this without cast to Euler angles?</p>
|
[
{
"answer_id": 74586912,
"author": "Martín",
"author_id": 20363318,
"author_profile": "https://Stackoverflow.com/users/20363318",
"pm_score": 2,
"selected": false,
"text": " var rangeList2 = rangeList.map((n) => n.replace('B','M'))\n sheet.getRangeList(rangeList2).setValue(value2);\n"
},
{
"answer_id": 74586972,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 1,
"selected": true,
"text": "M if(searchText!=''){\n var rangeList = sheet\n .getRange('C1:C')\n .createTextFinder(searchText)\n .matchEntireCell(true)\n .findAll();\n //Creates two range lists.\n var list1 = rangeList.map(r => r.offset(0, -1).getA1Notation());\n var list2 = rangeList.map(r => r.offset(0, 10).getA1Notation());\n sheet.getRangeList(list1).setValue(value1);\n sheet.getRangeList(list2).setValue(value2);\n console.log(searchText,value1,rangeList);\n }\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17752003/"
] |
74,586,878
|
<p>I would like to exchange all NA values in the columns for the respective medians</p>
<pre><code>id <- c(1,2,3,4,5,6,7,8,9,10)
varA <- c(15,10,8,19,7,5,NA,11,12,NA)
varB <- c(NA,1,2,3,4,3,3,2,1,NA)
df <- data.frame(id, varA,varB)
median(df$varA, na.rm=TRUE)
median(df$varB, na.rm=TRUE)
df1 <- df
# Columns to be modified with Median in place of the NA
col <- c("varA", "varB")
df1[col] <- sapply(df1[col],
function(x) replace(x, x %in% is.na(df1), median[col]))
df1
</code></pre>
<p>Error in <code>[.default</code>(df1, col) : invalid subscript type 'closure'</p>
|
[
{
"answer_id": 74586897,
"author": "Giulio Centorame",
"author_id": 10798015,
"author_profile": "https://Stackoverflow.com/users/10798015",
"pm_score": 1,
"selected": false,
"text": "dplyr tidyr library(dplyr)\nlibrary(tidyr)\n\ndf %>% \nmutate(varA = replace_na(varA, median(varA, na.rm = TRUE)),\n varB = replace_na(varB, median(varB, na.rm = TRUE)))\n"
},
{
"answer_id": 74586903,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "library(zoo)\ndf[col] <- na.aggregate(df[col], FUN = median)\n"
},
{
"answer_id": 74587093,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 0,
"selected": false,
"text": "df1[col] <- apply(df1[col], 2, \\(x) ifelse(is.na(x), median(x, na.rm = TRUE), x) ) \ndf1\n#> id varA varB\n#> 1 1 15.0 2.5\n#> 2 2 10.0 1.0\n#> 3 3 8.0 2.0\n#> 4 4 19.0 3.0\n#> 5 5 7.0 4.0\n#> 6 6 5.0 3.0\n#> 7 7 10.5 3.0\n#> 8 8 11.0 2.0\n#> 9 9 12.0 1.0\n#> 10 10 10.5 2.5\n"
}
] |
2022/11/27
|
[
"https://Stackoverflow.com/questions/74586878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17564379/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.