qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,659,092
|
<p>I'm trying to write a bioinformatics code that will check for certain repeats in a given string of nucleotides. The user inputs a certain patter, and the program outputs how many times something is repeated, or even highlights where they are. I've gotten a good start on it, but could use some help.</p>
<p>Below is my code so far.</p>
<pre><code>while True:
text = 'AGACGCCTGGGAACTGCGGCCGCGGGCTCGCGCTCCTCGCCAGGCCCTGCCGCCGGGCTGCCATCCTTGCCCTGCCATGTCTCGCCGGAAGCCTGCGTCGGGCGGCCTCGCTGCCTCCAGCTCAGCCCCTGCGAGGCAAGCGGTTTTGAGCCGATTCTTCCAGTCTACGGGAAGCCTGAAATCCACCTCCTCCTCCACAGGTGCAGCCGACCAGGTGGACCCTGGCGCTgcagcggctgcagcggccgcagcggccgcagcgCCCCCAGCGCCCCCAGCTCCCGCCTTCCCGCCCCAGCTGCCGCCGCACATA'
print ("Input Pattern:")
pattern = input("")
def pattern_count(text, pattern):
count = 0
for i in range(len(text) - len(pattern) + 1):
if text[i: i + len(pattern)] == pattern:
count = count + 1
return count
print(pattern_count(text, pattern))
</code></pre>
<p>The issue lies in in the fact that I can only put the input from the beginning (ex. AGA or AGAC) to get an output. Any help or recommendations would be greatly appreciated. Thank you so much!</p>
|
[
{
"answer_id": 74659139,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 1,
"selected": true,
"text": "def pattern_count(text, pattern):\n count = 0\n for i in range(len(text) - len(pattern) + 1):\n if text[i: i + len(pattern)] == pattern:\n count = count + 1\n return count\n\nwhile True:\n print(\"Input the string of nucleotides:\")\n text = input()\n\n print(\"Input the pattern to search for:\")\n pattern = input()\n\n count = pattern_count(text, pattern)\n print(\"The pattern appears {} times in the string.\".format(count))\n def pattern_count(text, pattern):\n return text.count(pattern)\n\nwhile True:\n print(\"Input the string of nucleotides:\")\n text = input()\n\n print(\"Input the pattern to search for:\")\n pattern = input()\n\n count = pattern_count(text, pattern)\n print(\"The pattern appears {} times in the string.\".format(count))\n"
},
{
"answer_id": 74660171,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 1,
"selected": false,
"text": "re.findall import re\ntext = 'AGACGCCTGGGAACTGCGGCCGCGGGCTCGCGCTCCTCGCCAGGCCCTGCCGCCGGGCTGCCATCCTTGCCCTGCCATGTCTCGCCGGAAGCCTGCGTCGGGCGGCCTCGCTGCCTCCAGCTCAGCCCCTGCGAGGCAAGCGGTTTTGAGCCGATTCTTCCAGTCTACGGGAAGCCTGAAATCCACCTCCTCCTCCACAGGTGCAGCCGACCAGGTGGACCCTGGCGCTgcagcggctgcagcggccgcagcggccgcagcgCCCCCAGCGCCCCCAGCTCCCGCCTTCCCGCCCCAGCTGCCGCCGCACATA'\npattern = \"CCT\"\ncount = sum(1 for _ in re.findall(pattern, text))\n sum(1 for ...)"
},
{
"answer_id": 74661886,
"author": "GAP2002",
"author_id": 14608493,
"author_profile": "https://Stackoverflow.com/users/14608493",
"pm_score": 0,
"selected": false,
"text": "def pattern_count(text, pattern):\n count = 0\n for i in range(len(text) - len(pattern) + 1):\n if text[i: i + len(pattern)] == pattern:\n count += 1\n return count\n\n\nwhile True:\n text = 'AGACGCCTGGGAACTGCGGCCGCGGGCTCGCGCTCCTCGCCAGGCCCTGCCGCCGGGCTGCCATCCTTGCCCTGCCATGTCTCGCCGGAAGCCTGCGTCGGGCGGCCTCGCTGCCTCCAGCTCAGCCCCTGCGAGGCAAGCGGTTTTGAGCCGATTCTTCCAGTCTACGGGAAGCCTGAAATCCACCTCCTCCTCCACAGGTGCAGCCGACCAGGTGGACCCTGGCGCTgcagcggctgcagcggccgcagcggccgcagcgCCCCCAGCGCCCCCAGCTCCCGCCTTCCCGCCCCAGCTGCCGCCGCACATA'\n print(\"Input Pattern:\")\n pattern = input(\"\")\n\n print(pattern_count(text, pattern))\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20160057/"
] |
74,659,098
|
<p>I am studing Java, i have simple Array linked to ArrayList, it is fixed size i can change values inside array or list without change length.
So i tried to change all elements of the Array to see changes into ArrayList (it doesn't work). I saw that if i change single value into Array my list would change too (it works).
If i change my List values into array wuold changed.
If i change List or Array length would throw exception.</p>
<pre><code> String[] nameListLinkedToArrayFixedSize = {"Jhonny","Joe","Jhoseph"};
List<String> nameListLinkedToArray = Arrays.asList(nameListLinkedToArrayFixedSize);
nameListLinkedToArrayFixedSize[1] = "J.Joe"; // this change my list
nameListLinkedToArrayFixedSize = new String[]{"ead","sda","eps"}; //change my array but non change my list
System.out.println(nameListLinkedToArray) // is same as first array why?
nameListLinkedToArray.set(2, "J.Jhoseph"); //[Jhonny, J.Joe, J.Jhoseph]
</code></pre>
<p>I need to understand how works linked arrays, i suppose this is not go well without point new array to new linked list?<br />
Why single operation on array change list?
What is pointer of linked list after i change all element of array?
Why my list continues update old values of array?
Where to find specific documentation?</p>
|
[
{
"answer_id": 74659938,
"author": "pfurbacher",
"author_id": 1271785,
"author_profile": "https://Stackoverflow.com/users/1271785",
"pm_score": 0,
"selected": false,
"text": "Arrays.asList() import java.util.Arrays;\nimport java.util.List;\n\npublic class ArraysAsListSideEffects {\n\n public static void main(String[] args) {\n\n codeWithSideEffects();\n\n codeWithoutSideEffects();\n }\n\n private static void codeWithoutSideEffects() {\n System.out.println(\"\\n\\nCode without side effects: \");\n\n String[] originalArray = { \"Jhonny\", \"Joe\", \"Jhoseph\" };\n List<String> listFromArray = List.of(originalArray);\n System.out.println(listFromArray);\n\n originalArray[1] = \"J.Joe\";\n System.out.println(\"After updating original array: \" + listFromArray);\n }\n\n protected static void codeWithSideEffects() {\n System.out.println(\"Side effects of using Arrays.asList()\");\n String[] originalArray = { \"Jhonny\", \"Joe\", \"Jhoseph\" };\n List<String> listFromArray = Arrays.asList(originalArray);\n\n // Because Arrays.asList uses your original array as the\n // backing store, changing an element in the original\n // array changes the element in the list.\n originalArray[1] = \"J.Joe\"; // this change my list\n\n // change my array but non change my list\n originalArray = new String[] { \"ead\", \"sda\", \"eps\" };\n // Since you assigned original array to a new array,\n // changes to it will not affect the backing store reference\n // used by listFromArray.\n\n System.out.println(listFromArray); // is same as first array why?\n // Yes because Arrays.asList stores a reference to that\n // list.\n\n listFromArray.set(2, \"J.Jhoseph\"); // [Jhonny, J.Joe, J.Jhoseph]} \n // This is correct because of how Arrays.asList\n // creates an ArrayList with your original array\n // as backing store.\n System.out.println(listFromArray);\n }\n}\n Side effects of using Arrays.asList()\n[Jhonny, J.Joe, Jhoseph]\n[Jhonny, J.Joe, J.Jhoseph]\n\n\nCode without side effects: \n[Jhonny, Joe, Jhoseph]\nAfter updating original array: [Jhonny, Joe, Jhoseph]\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372657/"
] |
74,659,104
|
<p>I've a function like:</p>
<pre><code>function myFunction(params) {
// TODO: something
console.log(params.message)
}
</code></pre>
<p>And I need to know all the keys that the myFunction function expects in the params object. Is this possible?</p>
<p>I've tried using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments</a> but it didn't work</p>
|
[
{
"answer_id": 74659938,
"author": "pfurbacher",
"author_id": 1271785,
"author_profile": "https://Stackoverflow.com/users/1271785",
"pm_score": 0,
"selected": false,
"text": "Arrays.asList() import java.util.Arrays;\nimport java.util.List;\n\npublic class ArraysAsListSideEffects {\n\n public static void main(String[] args) {\n\n codeWithSideEffects();\n\n codeWithoutSideEffects();\n }\n\n private static void codeWithoutSideEffects() {\n System.out.println(\"\\n\\nCode without side effects: \");\n\n String[] originalArray = { \"Jhonny\", \"Joe\", \"Jhoseph\" };\n List<String> listFromArray = List.of(originalArray);\n System.out.println(listFromArray);\n\n originalArray[1] = \"J.Joe\";\n System.out.println(\"After updating original array: \" + listFromArray);\n }\n\n protected static void codeWithSideEffects() {\n System.out.println(\"Side effects of using Arrays.asList()\");\n String[] originalArray = { \"Jhonny\", \"Joe\", \"Jhoseph\" };\n List<String> listFromArray = Arrays.asList(originalArray);\n\n // Because Arrays.asList uses your original array as the\n // backing store, changing an element in the original\n // array changes the element in the list.\n originalArray[1] = \"J.Joe\"; // this change my list\n\n // change my array but non change my list\n originalArray = new String[] { \"ead\", \"sda\", \"eps\" };\n // Since you assigned original array to a new array,\n // changes to it will not affect the backing store reference\n // used by listFromArray.\n\n System.out.println(listFromArray); // is same as first array why?\n // Yes because Arrays.asList stores a reference to that\n // list.\n\n listFromArray.set(2, \"J.Jhoseph\"); // [Jhonny, J.Joe, J.Jhoseph]} \n // This is correct because of how Arrays.asList\n // creates an ArrayList with your original array\n // as backing store.\n System.out.println(listFromArray);\n }\n}\n Side effects of using Arrays.asList()\n[Jhonny, J.Joe, Jhoseph]\n[Jhonny, J.Joe, J.Jhoseph]\n\n\nCode without side effects: \n[Jhonny, Joe, Jhoseph]\nAfter updating original array: [Jhonny, Joe, Jhoseph]\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16052906/"
] |
74,659,122
|
<p>I am wondering how to replace values from second row onwards in a pipe method (connecting to the rest of steps).</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"Date": ["2020-01-01", "2021-01-01", "2022-01-01"],
"Pop": [90, 70, 60],
}
)
Date Pop
0 2020-01-01 90
1 2021-01-01 70
2 2022-01-01 60
</code></pre>
<p>Current solution</p>
<pre><code>df.iloc[1:] = np.nan
</code></pre>
<p>Expected output</p>
<pre><code> Date Pop
0 2020-01-01 90
1 2021-01-01 NaN
2 2022-01-01 NaN
</code></pre>
|
[
{
"answer_id": 74659327,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(\n {\n \"Date\": [\"2020-01-01\", \"2021-01-01\", \"2022-01-01\"],\n \"Pop\": [90, 70, 60],\n }\n)\n\n# Use the `pipe` method to apply a function to your DataFrame\ndf = df.pipe(lambda x: x.iloc[1:]).replace(np.nan)\n\nprint(df)\n Date Pop\n0 2021-01-01 NaN\n1 2022-01-01 NaN\n import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(\n {\n \"Date\": [\"2020-01-01\", \"2021-01-01\", \"2022-01-01\"],\n \"Pop\": [90, 70, 60],\n }\n)\n\n# Make a copy of the original DataFrame\ndf_copy = df.copy()\n\n# Use the `pipe` method to apply a function to your DataFrame\ndf_copy = df_copy.pipe(lambda x: x.iloc[1:]).replace(np.nan)\n\nprint(df_copy)\n"
},
{
"answer_id": 74659495,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 3,
"selected": true,
"text": "assign df.assign(Pop=df.loc[[0], 'Pop'])\n Date Pop\n0 2020-01-01 90.0\n1 2021-01-01 NaN\n2 2022-01-01 NaN\n assign"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13236293/"
] |
74,659,126
|
<p>I'm writing a program in Python that looks at an XML file that I get from an API and should return a list of users' initials to a list for later use. My XML file looks like this with about 60 users:</p>
<pre><code><ArrayOfuser xmlns="WebsiteWhereDataComesFrom.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<user>
<active>true</active>
<datelastlogin>8/21/2019 9:16:30 PM</datelastlogin>
<dept>3</dept>
<email>useremail</email>
<firstname>userfirstname</firstname>
<lastname>userlastname</lastname>
<lastupdated>2/6/2019 11:10:29 PM</lastupdated>
<lastupdatedby>lastupdateduserinitials</lastupdatedby>
<loginemail>userloginemail</loginemail>
<phone1>userphone</phone1>
<phone2/>
<rep>userinitials1</rep>
</user>
<user>
<active>true</active>
<datelastlogin>12/1/2022 3:31:25 PM</datelastlogin>
<dept>5</dept>
<email>useremail</email>
<firstname>userfirstname</firstname>
<lastname>userlastname</lastname>
<lastupdated>4/8/2020 3:02:08 PM</lastupdated>
<lastupdatedby>lastupdateduserinitials</lastupdatedby>
<loginemail>userloginemail</loginemail>
<phone1>userphone</phone1>
<phone2/>
<rep>userinitials2</rep>
</user>
...
...
...
</ArrayOfuser>
</code></pre>
<p>I'm trying to use an XML parser to return the text in the <code><rep></code> tag for each user to a list. I would also love to have it sorted by date of last login, but that's not something I need and I'll just alphabetize the list if sorting by date overcomplicates this process.</p>
<p>The code below shows my attempt at just printing the data without saving it to a list, but the output is unexpected as shown below as well.
Code I tried:</p>
<pre><code>#load file
activeusers = etree.parse("activeusers.xml")
#declare namespaces
ns = {'xx': 'http://schemas.datacontract.org/2004/07/IQWebAPI.Users'}
#locate rep tag and print (saving to list once printing shows expected output)
targets = activeusers.xpath('//xx:user[xx:rep]',namespaces=ns)
for target in targets:
print(target.attrib)
</code></pre>
<p>Output:</p>
<pre><code>{}
{}
</code></pre>
<p>I'm expecting the output to look like the below codeblock. Once it looks something like that I should be able to change the print statement to instead save to a list.</p>
<pre><code>{userinitials1}
{userinitials2}
</code></pre>
<p>I think my issue comes from what's inside my print statement with printing the attribute. I tried this with variations of <code>target.getparent()</code> with <code>keys()</code>, <code>items()</code>, and <code>get()</code> as well and they all seem to show the same empty output when printed.</p>
<p><strong>EDIT:</strong> I found a post from someone with a similar problem that had been solved and the solution was to use this code but I changed filenames to suit my need:</p>
<pre><code>root = (etree.parse("activeusers.xml"))
values = [s.find('rep').text for s in root.findall('.//user') if s.find('rep') is not None]
print(values)
</code></pre>
<p>Again, the expected output was a populated list but when printed the list is empty. I think now my issue may have to do with the fact that my document contains namespaces. For my use, I may just delete them since I don't think these will end up being required so please correct me if namespaces are more important than I realize.</p>
<p><strong>SECOND EDIT:</strong> I also realized the API can send me this data in a JSON format and not just XML so that file would look like the below codeblock. Any solution that can append the text in the "rep" child of each user to a list in JSON format or XML is perfect and would be greatly appreciated since once I have this list, I will not need to use the XML or JSON file for any other use.</p>
<pre><code>[
{
"active": true,
"datelastlogin": "8/21/2019 9:16:30 PM",
"dept": 3,
"email": "useremail",
"firstname": "userfirstname",
"lastname": "userlastname",
"lastupdated": "2/6/2019 11:10:29 PM",
"lastupdatedby": "lastupdateduserinitials",
"loginemail": "userloginemail",
"phone1": "userphone",
"phone2": "",
"rep": "userinitials1"
},
{
"active": true,
"datelastlogin": "12/1/2022 3:31:25 PM",
"dept": 5,
"email": "useremail",
"firstname": "userfirstname",
"lastname": "userlastname",
"lastupdated": "4/8/2020 3:02:08 PM",
"lastupdatedby": "lastupdateduserinitials",
"loginemail": "userloginemail",
"phone1": "userphone",
"phone2": "",
"rep": "userinitials2"
}
]
</code></pre>
|
[
{
"answer_id": 74659388,
"author": "simpleApp",
"author_id": 15568504,
"author_profile": "https://Stackoverflow.com/users/15568504",
"pm_score": 1,
"selected": false,
"text": "import xml.etree.ElementTree as ET\nroot = ET.fromstring(xml_in_qes)\nmy_ns = {'root': 'WebsiteWhereDataComesFrom.com'}\nmyUser=[]\nfor eachUser in root.findall('root:user',my_ns):\n rep=eachUser.find(\"root:rep\",my_ns)\n print(rep.text)\n myUser.append(rep.text)\n ('root:user',my_ns): root"
},
{
"answer_id": 74659439,
"author": "Rathish Kumar B",
"author_id": 2156784,
"author_profile": "https://Stackoverflow.com/users/2156784",
"pm_score": 1,
"selected": true,
"text": "import xml.etree.ElementTree as ET\nxmlstring = '''\n<ArrayOfuser>\n <user>\n <active>true</active>\n <datelastlogin>8/21/2019 9:16:30 PM</datelastlogin>\n <dept>3</dept>\n <email>useremail</email>\n <firstname>userfirstname</firstname>\n <lastname>userlastname</lastname>\n <lastupdated>2/6/2019 11:10:29 PM</lastupdated>\n <lastupdatedby>lastupdateduserinitials</lastupdatedby>\n <loginemail>userloginemail</loginemail>\n <phone1>userphone</phone1>\n <phone2/>\n <rep>userinitials1</rep>\n </user>\n <user>\n <active>true</active>\n <datelastlogin>8/21/2019 9:16:30 PM</datelastlogin>\n <dept>3</dept>\n <email>useremail</email>\n <firstname>userfirstname</firstname>\n <lastname>userlastname</lastname>\n <lastupdated>2/6/2019 11:10:29 PM</lastupdated>\n <lastupdatedby>lastupdateduserinitials</lastupdatedby>\n <loginemail>userloginemail</loginemail>\n <phone1>userphone</phone1>\n <phone2/>\n <rep>userinitials2</rep>\n </user>\n <user>\n <active>true</active>\n <datelastlogin>8/21/2019 9:16:30 PM</datelastlogin>\n <dept>3</dept>\n <email>useremail</email>\n <firstname>userfirstname</firstname>\n <lastname>userlastname</lastname>\n <lastupdated>2/6/2019 11:10:29 PM</lastupdated>\n <lastupdatedby>lastupdateduserinitials</lastupdatedby>\n <loginemail>userloginemail</loginemail>\n <phone1>userphone</phone1>\n <phone2/>\n <rep>userinitials3</rep>\n </user>\n</ArrayOfuser>\n'''\n\nuser_array = ET.fromstring(xmlstring)\n\nreplist = []\nfor users in user_array.findall('user'):\n replist.append((users.find('rep').text))\n\nprint(replist)\n ['userinitials1', 'userinitials2', 'userinitials3']\n userlist = [\n {\n \"active\": \"true\",\n \"datelastlogin\": \"8/21/2019 9:16:30 PM\",\n \"dept\": 3,\n \"email\": \"useremail\",\n \"firstname\": \"userfirstname\",\n \"lastname\": \"userlastname\",\n \"lastupdated\": \"2/6/2019 11:10:29 PM\",\n \"lastupdatedby\": \"lastupdateduserinitials\",\n \"loginemail\": \"userloginemail\",\n \"phone1\": \"userphone\",\n \"phone2\": \"\",\n \"rep\": \"userinitials1\"\n },\n {\n \"active\": \"true\",\n \"datelastlogin\": \"12/1/2022 3:31:25 PM\",\n \"dept\": 5,\n \"email\": \"useremail\",\n \"firstname\": \"userfirstname\",\n \"lastname\": \"userlastname\",\n \"lastupdated\": \"4/8/2020 3:02:08 PM\",\n \"lastupdatedby\": \"lastupdateduserinitials\",\n \"loginemail\": \"userloginemail\",\n \"phone1\": \"userphone\",\n \"phone2\": \"\",\n \"rep\": \"userinitials2\"\n },\n {\n \"active\": \"true\",\n \"datelastlogin\": \"12/1/2022 3:31:25 PM\",\n \"dept\": 5,\n \"email\": \"useremail\",\n \"firstname\": \"userfirstname\",\n \"lastname\": \"userlastname\",\n \"lastupdated\": \"4/8/2020 3:02:08 PM\",\n \"lastupdatedby\": \"lastupdateduserinitials\",\n \"loginemail\": \"userloginemail\",\n \"phone1\": \"userphone\",\n \"phone2\": \"\",\n \"rep\": \"userinitials3\"\n }\n]\n\nreplist = []\nfor user in userlist:\n replist.append(user[\"rep\"])\n\nprint(replist)\n ['userinitials1', 'userinitials2', 'userinitials3']\n"
},
{
"answer_id": 74661238,
"author": "Hermann12",
"author_id": 12621346,
"author_profile": "https://Stackoverflow.com/users/12621346",
"pm_score": 0,
"selected": false,
"text": "import xml.etree.ElementTree as ET\nimport pandas as pd\n\ntree = ET.parse(\"activeusers.xml\")\nroot = tree.getroot()\n\nnamespaces = {\"xmlns\":\"WebsiteWhereDataComesFrom.com\" , \"xmlns:i\":\"http://www.w3.org/2001/XMLSchema-instance\"}\n\ncolumns =[\"rep\", \"datelastlogin\"]\nlogin = []\nusr = []\nfor user in root.findall(\"xmlns:user\", namespaces):\n for lastlog in user.findall(\"xmlns:datelastlogin\", namespaces):\n login.append(lastlog.text)\n \n for activ in user.findall(\"xmlns:rep\", namespaces):\n usr.append(activ.text)\n \ndata = list(zip(usr, login))\n\n\ndf = pd.DataFrame(data, columns=columns)\ndf[\"datelastlogin\"] = df[\"datelastlogin\"].astype('datetime64[ns]')\ndf = df.sort_values(by='datelastlogin', ascending = False)\nprint(df.to_string())\n rep datelastlogin\n1 userinitials2 2022-12-01 15:31:25\n0 userinitials1 2019-08-21 21:16:30\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683235/"
] |
74,659,143
|
<p>I have a data frame looking like this :</p>
<pre><code>> df <- data.frame(x = c(1,0,2,0,1,3,1),
+ y = c("lima","chicago","new york","Miami","havana","Colon","la paz"))
> df
x y
1 1 lima
2 0 chicago
3 2 new york
4 0 Miami
5 1 havana
6 3 Colon
7 1 la paz
</code></pre>
<p>I would like to find a way to insert blank N rows depending on the value of column <code>x</code>
so if <code>x</code> is 1, 1 blank row would be inserted above, if <code>x</code> is 3, 3 blank rows would be inserted above. The desired output for the data frame above should be this:</p>
<pre><code>> df
x y
1 NA <NA>
2 1 lima
3 0 chicago
4 NA <NA>
5 NA <NA>
6 2 new york
7 0 Miami
8 NA <NA>
9 1 havana
10 NA <NA>
11 NA <NA>
12 NA <NA>
13 3 Colon
14 NA <NA>
15 1 la paz
</code></pre>
|
[
{
"answer_id": 74659240,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\n\ndf %>% \n group_by(ID = row_number()) %>% \n summarise(cur_data()[seq(x+1),]) %>% \n arrange(!is.na(x), x, .by_group = TRUE) %>% \n ungroup() %>% \n select(-ID)\n x y \n <dbl> <chr> \n 1 NA NA \n 2 1 lima \n 3 0 chicago \n 4 NA NA \n 5 NA NA \n 6 2 new york\n 7 0 Miami \n 8 NA NA \n 9 1 havana \n10 NA NA \n11 NA NA \n12 NA NA \n13 3 Colon \n14 NA NA \n15 1 la paz \n"
},
{
"answer_id": 74659249,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "do.call(rbind, c(make.row.names=FALSE, lapply(split(df, df$y), function(z){\n x <- y <- rep(NA, z$x)\n rbind(cbind(x, y), z)\n}) ))\n x y\n1 0 chicago\n2 NA <NA>\n3 NA <NA>\n4 NA <NA>\n5 3 Colon\n6 NA <NA>\n7 1 havana\n8 NA <NA>\n9 1 la paz\n10 NA <NA>\n11 1 lima\n12 0 Miami\n13 NA <NA>\n14 NA <NA>\n15 2 new york\n"
},
{
"answer_id": 74660615,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "base R i1 <-with(df, rep(seq_along(x), ifelse(x >0, x + 1, 1)))\nout <- df[NA^(duplicated(i1, fromLast = TRUE)) * i1,]\nrow.names(out) <- NULL\n > out\n x y\n1 NA <NA>\n2 1 lima\n3 0 chicago\n4 NA <NA>\n5 NA <NA>\n6 2 new york\n7 0 Miami\n8 NA <NA>\n9 1 havana\n10 NA <NA>\n11 NA <NA>\n12 NA <NA>\n13 3 Colon\n14 NA <NA>\n15 1 la paz\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453570/"
] |
74,659,144
|
<p>I want to create a DataFrame to which I want to import data from a class. I mean, I type <code>t1 = Transaction("20221128", "C1", 14)</code> and I want a DataFrame to show data like:</p>
<ol>
<li>Column 1: Date</li>
<li>Column 2: Concept</li>
<li>Column 3: Amount</li>
</ol>
<p>The code where I want to implement this is:</p>
<pre><code>class Transactions:
num_of_transactions = 0
amount = 0
def __init__(self, date, concept, amount):
self.date = date
self.concept = concept
self.amount = amount
Transaction.add_transaction()
Transaction.add_money(self)
@classmethod
def number_of_transactions(cls):
return cls.num_of_transactions
@classmethod
def add_transaction(cls):
cls.num_of_transactions += 1
@classmethod
def amount_of_money(cls):
return cls.amount
@classmethod
def add_money(cls, self):
cls.amount += self.amount
t1 = Transaction("20221128", "C1", 14)
t2 = Transaction("20221129", "C2", 30)
t3 = Transaction("20221130", "3", 14)
</code></pre>
<p>I tried:</p>
<pre><code>def DataFrame(self):
df = pd.DataFrame(self.date self.concept, self.amount)
</code></pre>
<p>But looking at pandas documentation, I have seen it is not a valid way.</p>
<p>Any help on that? Thank you!</p>
|
[
{
"answer_id": 74659240,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\n\ndf %>% \n group_by(ID = row_number()) %>% \n summarise(cur_data()[seq(x+1),]) %>% \n arrange(!is.na(x), x, .by_group = TRUE) %>% \n ungroup() %>% \n select(-ID)\n x y \n <dbl> <chr> \n 1 NA NA \n 2 1 lima \n 3 0 chicago \n 4 NA NA \n 5 NA NA \n 6 2 new york\n 7 0 Miami \n 8 NA NA \n 9 1 havana \n10 NA NA \n11 NA NA \n12 NA NA \n13 3 Colon \n14 NA NA \n15 1 la paz \n"
},
{
"answer_id": 74659249,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "do.call(rbind, c(make.row.names=FALSE, lapply(split(df, df$y), function(z){\n x <- y <- rep(NA, z$x)\n rbind(cbind(x, y), z)\n}) ))\n x y\n1 0 chicago\n2 NA <NA>\n3 NA <NA>\n4 NA <NA>\n5 3 Colon\n6 NA <NA>\n7 1 havana\n8 NA <NA>\n9 1 la paz\n10 NA <NA>\n11 1 lima\n12 0 Miami\n13 NA <NA>\n14 NA <NA>\n15 2 new york\n"
},
{
"answer_id": 74660615,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "base R i1 <-with(df, rep(seq_along(x), ifelse(x >0, x + 1, 1)))\nout <- df[NA^(duplicated(i1, fromLast = TRUE)) * i1,]\nrow.names(out) <- NULL\n > out\n x y\n1 NA <NA>\n2 1 lima\n3 0 chicago\n4 NA <NA>\n5 NA <NA>\n6 2 new york\n7 0 Miami\n8 NA <NA>\n9 1 havana\n10 NA <NA>\n11 NA <NA>\n12 NA <NA>\n13 3 Colon\n14 NA <NA>\n15 1 la paz\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18685243/"
] |
74,659,146
|
<p>I'm using C# with the .NET 6 framework. I have a class called
<code>Message</code> and another called <code>TaggedMessage</code> which inherits from <code>Message</code>.</p>
<p>The idea is simple. A function receives an object of type Message and then adds several Tags to it and returns it as a TaggedMessage. A list of TaggedMessage objects is later displayed in a table. For databinding to remain nice and easy I want TaggedMessage to not contain nested properties. So it shouldn't hold an instance of Message for example. Instead it should contain all the properties from Message plus additional ones.</p>
<p>So I thought it should inherit from Message. However I cannot find a way to instantiate TaggedMessage from Message unless I specifically assign every column from Message to TaggedMessage in its constructor. Which seems overly difficult and would mean everytime I add a property to Message, I would have to revisit the constructor of TaggedMessage. Exmaple (obviously the real thing is more complex)</p>
<pre><code> public class Message
{
public string MessageID { get; set; } = "5";
public string Subject{ get; set; } = "Test";
}
Public class TaggedMessage : Message
{
public string MyTag { get; set; }
}
Message m = new Message();
TaggedMessage t = TaggedMessage;
t = (TaggedMessage)m; //This ovbiously doesn't work
t.Tag = "Nature";
</code></pre>
<p>Now the casting doesn't work because I'm casting a base class in a derived class. But then, how to I get the values from m into t? Let's assume m has 50 properties and they could change in the future. How can get an object t that has all the values m had, but with extra tags added? There must be a more elegant way than assigning all 50 properties in the constructor!? I feel like I'm missing a simple solution here.</p>
|
[
{
"answer_id": 74660080,
"author": "Viachaslau S",
"author_id": 17292083,
"author_profile": "https://Stackoverflow.com/users/17292083",
"pm_score": 3,
"selected": true,
"text": "Message TaggedMessage static void Main()\n {\n var config = new MapperConfiguration(cfg =>\n {\n cfg.CreateMap<Message, TaggedMessage>()\n .IncludeAllDerived();\n });\n\n var mapper = config.CreateMapper();\n\n var m = new Message() { MessageID = \"SomeMessageID\", Subject = \"SomeSubject\" };\n var t = mapper.Map<TaggedMessage>(m);\n t.MyTag = \"MyTag\";\n Console.WriteLine(t.MessageID);\n Console.WriteLine(t.Subject);\n Console.WriteLine(t.MyTag);\n }\n"
},
{
"answer_id": 74660163,
"author": "eduherminio",
"author_id": 5459321,
"author_profile": "https://Stackoverflow.com/users/5459321",
"pm_score": 1,
"selected": false,
"text": " var message = new Message();\n var str = System.Text.Json.JsonSerializer.Serialize(message);\n var taggedMessage = System.Text.Json.JsonSerializer.Deserialize<TaggedMessage>(str);\n taggedMessage.MyTag = \"Nature\";\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2696330/"
] |
74,659,156
|
<p>I want to test whether a type can be passed to some function, but I'd like to use ADL on the function lookup and include a function from a certain namespace.</p>
<p>Consider this code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <utility>
#include <vector>
template<class T>
concept Swappable = requires(T& a, T& b)
{
swap(a,b);
};
static_assert(Swappable<std::vector<int>>); // #1
static_assert(Swappable<int>); // #2
</code></pre>
<p>#1 succeeds, it finds <code>std::swap</code> because <code>std</code> is an associated namespace of <code>std::vector<int></code>. But #2 fails, a built-in type has no associated namespace.</p>
<p>How would I write something like:</p>
<pre class="lang-cpp prettyprint-override"><code>template<class T>
concept Swappable = requires(T& a, T& b)
{
using std::swap; // illegal
swap(a,b);
};
</code></pre>
<p>AFAIK, you're not allowed to use a using-declaration inside a requires-expression.</p>
<p><strong>(NOTE</strong> Although there is a perfectly fine standard C++ concept for this, <code>std::swappable</code>, this example uses <code>swap</code> for exposition only. I'm not particularly looking to test whether something is actually swappable, I'm just trying to find a way to implement such a concept where a customization function has a default implementation in a known namespace, but might have overloads in an associated namespace.<strong>)</strong></p>
<p><strong>EDIT</strong> As a workaround, I can implement the concept in a separate namespace where the names are pulled in. Not too happy about it but it works.</p>
<pre class="lang-cpp prettyprint-override"><code>namespace detail
{
using std::swap;
template<class T>
concept Swappable = requires(T& a, T& b)
{
swap(a,b);
};
}
// and then either use it
using detail::Swappable;
// or redefine it
template<class T>
concept Swappable = detail::Swappable<T>;
</code></pre>
|
[
{
"answer_id": 74659272,
"author": "Nicol Bolas",
"author_id": 734069,
"author_profile": "https://Stackoverflow.com/users/734069",
"pm_score": 3,
"selected": false,
"text": "using ranges::swap using operator() using using ranges::swap"
},
{
"answer_id": 74659822,
"author": "Artyer",
"author_id": 5754656,
"author_profile": "https://Stackoverflow.com/users/5754656",
"pm_score": 5,
"selected": true,
"text": "template<class T>\nconcept Swappable = []{\n using std::swap;\n return requires(T& a, T& b) { swap(a, b); };\n}();\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8951473/"
] |
74,659,167
|
<p>Let's assume I have the code:</p>
<pre><code>// Android ViewModel
class MyVM(val dao: MyDao) : ViewModel() {
fun onButtonInsert() {
// point 1
viewModelScope.launch {
// point 2
dao.insert_SuspendFun(MyData(id=1, "hello, it works"))
// point 3
dao.insert_NOT_SuspendFun(MyData(id=2, "hello, it fails"))
// point 4
}
}
}
// Room DAO
@Dao
interface MyDao {
@Insert
suspend fun insert_SuspendFun(md: MyData)
@Insert
fun insert_NOT_SuspendFun(md: MyData)
}
</code></pre>
<p>Now when <code>fun onButtonInsert</code> runs then:<br />
1st line works:</p>
<pre><code>dao.insert_SuspendFun(MyData(id=1, "hello, it works"))
</code></pre>
<p>but 2nd line:</p>
<pre><code>dao.insert_NOT_SuspendFun(MyData(id=2, "hello, it fails"))
</code></pre>
<p>fails with the exception:</p>
<pre><code>java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
</code></pre>
<p>"The only difference" is that <code>fun insert_NOT_SuspendFun</code> has no <code>suspend</code> keyword.</p>
<p>Both methods run in <strong>the same coroutine</strong>.</p>
<p>Can someone explain what happens under the hood?<br />
How are threads working in this coroutine?<br />
Why does 1st call use non-UI thread but 2nd uses UI thread?</p>
<p>Thanks! ;]</p>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367449/"
] |
74,659,179
|
<p>i'm having a bit of a headache with VBA which i haven't used since 2006.</p>
<p>I have my destination excel file where I need to import 3 predefined sheets from another excel file of the user's choice.</p>
<p>After selecting the source file to import I would like to perform a check, IF the "Cover" sheet exists THEN copy it to the target workbook ELSE print an error message in the excel file in order to have a log, once this is done I have to do the same check for the "Functional" and "Batch" sheets.</p>
<p>Before inserting the IFs, I was able to import the sheets but I didn't have control over whether they existed or not, "Cover" is mandatory while "Functional" and "Batch" I need at least one of the two to be able to proceed with the next steps.</p>
<p>Now I can check if the "Cover" sheet exists and import it ELSE I exit the Sub, after which I should check if the other sheets also exist and import them but I immediately get the "absent sheet" error.</p>
<p>Below is the code I am getting stuck with:</p>
<pre><code>Sub Import()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim TargetWorkbook As Workbook
Dim SourceWorkbook As Workbook
Dim OpenFileName
Set TargetWorestBookkbook = ActiveWorkbook
'Select and Open Source workbook
OpenFileName = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*")
If OpenFileName = False Then
MsgBox "Nessun file Source selezionato. Impossibile procedere."
Exit Sub
End If
On Error GoTo exit_
Set SourceWorkbook = Workbooks.Open(OpenFileName)
'Import sheets
' if the sheet doesn't exist an error will occur here
If WorksheetExists("Cover e Legenda") Then
SourceWorkbook.Sheets("Cover e Legenda").Copy _
after:=TargetWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Application.CutCopyMode = False
SourceWorkbook.Close False
Else
MsgBox ("Cover assente. Impossibile proseguire.")
Exit Sub
End If
If WorksheetExists("Test Funzionali") Then
SourceWorkbook.Sheets("Test Funzionali").Copy _
after:=TargetWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Application.CutCopyMode = False
SourceWorkbook.Close False
Else
MsgBox ("Test Funzionali assente.")
End If
If WorksheetExists("Test Batch") Then
SourceWorkbook.Sheets("Test Batch").Copy _
after:=TargetWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Application.CutCopyMode = False
SourceWorkbook.Close False
Else
MsgBox ("Test Batch assente.")
End If
'Next Sheet
Application.ScreenUpdating = True
Application.DisplayAlerts = True
SourceWorkbook.Close SaveChanges:=False
MsgBox ("Importazione completata.")
TargetWorkbook.Activate
exit_:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Err Then MsgBox Err.Description, vbCritical, "Error"
End Sub
</code></pre>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6358335/"
] |
74,659,190
|
<p>I can't understand why my script is not working..I don't get why this is wrong..this is my script code below.</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class k : MonoBehaviour
{
void OnTriggerEnter(Collider collider)
{
if(collider.gameObject.name == "holms")
{
GameVariables.keyCount+=2;
Destroy(gameobject);
}
}
}
</code></pre>
<p>I was searching the internet to find similar issue and I find similar threads but not similar to this. It different from the other post here or in google search.</p>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18125145/"
] |
74,659,214
|
<p>Im using this code(C#NETCORE5.0) to return a model:</p>
<pre class="lang-cs prettyprint-override"><code> [HttpPost]
[Authorize(AuthenticationSchemes = "Bearer")]
public IActionResult GetTablero(GenericStringModel item){
TableroVentasManager mng = new TableroVentasManager();
TablaGeneralVentasModel response = mng.getTotalTable(item.zona);
return response != null ? Ok(response) : BadRequest();
}
</code></pre>
<p>I want to reduce the size of the response (16.6mb actual) I have use</p>
<pre><code>string ignored = JsonConvert.SerializeObject(response,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
</code></pre>
<p>but the size increase to 24mb</p>
<p>But if I only return the model, the size is 16.6MB theres a way to ignore null values to reduce the size?</p>
<p>Actual:</p>
<pre><code>{
"zona": "Z305",
"companyId": "C018763",
"formaEnvio": "CCI FORANEO",
"mov": "salesorder",
"tranId": 1193156,
"subTotal": 164.8800,
"consolidado": null,
"nombre": "Ingresado",
"fechaIngreso": "2022-12-02T10:39:56",
"fechaLiberado": null,
"fechaProceso": null,
"fechaCancelado": null,
"consolidado2": 0.0,
"empacado": 0
}
</code></pre>
<p>Desired:</p>
<pre><code> {
"zona": "Z305",
"companyId": "C018763",
"formaEnvio": "CCI FORANEO",
"mov": "salesorder",
"tranId": 1193156,
"subTotal": 164.8800,
"nombre": "Ingresado",
"fechaIngreso": "2022-12-02T10:39:56",
"consolidado2": 0.0,
"empacado": 0
}
</code></pre>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615105/"
] |
74,659,222
|
<pre><code>type here
</code></pre>
<p>Hi
I want to convert html to pdf in angular using jspdf and send to nodejs server</p>
<p>Can anyone help me?</p>
<p>Or give me advice please</p>
<p>I have this code saved in the browser and I want to send it to the nodejs server</p>
<pre><code>public openPDF(): void {
let DATA: any = document.getElementById('content');
html2canvas(DATA).then((canvas) => {
let fileWidth = 208;
let fileHeight = (canvas.height * fileWidth) / canvas.width;
const FILEURI = canvas.toDataURL('image/png');
let PDF = new jsPDF('p', 'mm', 'a4');
let position = 0;
PDF.addImage(FILEURI, 'PNG', 0, position, fileWidth, fileHeight);
PDF.save();
});
}
</code></pre>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20666289/"
] |
74,659,233
|
<p>I want to reemit the last value of my observable at a fix interval, to I tried</p>
<pre><code>obs.pipe(repeat({delay:1000})).subscribe(x => console.log('Emitted', x));
</code></pre>
<p>but it did not work. after looking into this, my observable is in fact a BehaviorSubject.</p>
<p>So my Question is Why does the 1st emits every second</p>
<pre><code>of('Observable').pipe(repeat({ delay: 1000 })).subscribe(x => console.log(x));
</code></pre>
<p>but not the this?</p>
<pre><code>var bs = new BehaviorSubject('BehaviorSubject');
bs.pipe(repeat({ delay: 1000 })).subscribe(x => console.log(x));
</code></pre>
<p>How to do it with my BehaviorSubject?</p>
<p><strong>Edit</strong></p>
<p>And I would also like to reset my timer when the subject emits a new value.</p>
<p>the solution I found is</p>
<pre><code>var bs = new BehaviorSubject('BehaviorSubject');
bs.pipe(switchMap(x => timer(0,1000).pipe(map => () => x)).subscribe(x => console.log(x));
</code></pre>
<p>but it feels ugly.</p>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76209/"
] |
74,659,242
|
<p>I open a modal in Blazor (Server App) that contains an array of strings. Everything is working code wise, but I have to click in the first element to set focus (these are serial numbers and are read with a scanner). After that, as scanning continues the focus moves after each scan. I would like the first element to be focused when the modal opens so scanning can start without having to click in the first element.</p>
<p>Here is the modal setup"</p>
<pre><code><Modal @ref="modalMultipleSerialNumbers" Title="Add/Change Multiple Serial Numbers" UseStaticBackdrop="true" Size="ModalSize.ExtraLarge">
<BodyTemplate>
@for (var i = 0; i < SD.MaxNumberOfMultiples; i++)
{
var count = i; // using i doesn't work. Has to be stored in a local variable to use bind.'
<input @bind="@MulipleSerialNumbers[count]" class="col-4 m-1" />
}
</BodyTemplate>
<FooterTemplate>
<Button Color="ButtonColor.Secondary" @onclick="OnClearModalClick">Clear list of Serial Numbers</Button>
<Button Color="ButtonColor.Primary" @onclick="OnSaveModalClick">Save list of Serial Numbers</Button>
</FooterTemplate>
</code></pre>
<p>I did try:</p>
<pre><code><input @bind="@MulipleSerialNumbers[count]" autofocus="true" class="col-4 m-1" />
</code></pre>
<p>but it didn't change anything.</p>
<p>Thanks for looking!</p>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812535/"
] |
74,659,294
|
<p>I have an array (<code>$datas</code>) with subs arrays like this :</p>
<p><a href="https://i.stack.imgur.com/sFKXA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sFKXA.png" alt="array" /></a></p>
<p><a href="https://i.stack.imgur.com/a9c1y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a9c1y.png" alt="enter image description here" /></a></p>
<p>I need to remove subs arrays with same [0] value.
But i can't do it.</p>
<p>I tested with <code>array_unique()</code> and many <code>foreach</code> in another <code>foreach</code> but i don't understand the methodology(correct in english?).</p>
<p>Any suggestion are welcome !</p>
|
[
{
"answer_id": 74659438,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "suspend viewmodelscope.launch(dispatchers.io)\n"
},
{
"answer_id": 74660561,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "withContext coroutineScope suspendCoroutine suspendCancellableCoroutine suspendCancellableCoroutine withContext(Dispatchers.IO) viewModelScope launch withContext"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20260243/"
] |
74,659,302
|
<p>I want to know if there is a better and cleaner way of printing the 3rd step of a generator function.
Currently I have written the following code</p>
<pre><code>def imparesgen():
n = 0
while n<200:
n=n+2
yield n
gen = imparesgen()
y = 0
for x in gen:
y+=1
if y == 3:
print(x)
</code></pre>
<p>This worked, but, is there maybe a simpler way of doing this? Without the use of a list.</p>
|
[
{
"answer_id": 74659400,
"author": "Pranav Hosangadi",
"author_id": 843953,
"author_profile": "https://Stackoverflow.com/users/843953",
"pm_score": 0,
"selected": false,
"text": "zip gen gen = imparesgen()\nfor _, item in zip(range(3), gen):\n pass\n\n# Now, item is the third element\nprint(item)\n next() gen = imparesgen()\nnext(gen)\nnext(gen)\nitem = next(gen)\nprint(item)\n next gen = imparesgen()\nfor _ in range(3):\n item = next(gen)\n\nprint(item)\n"
},
{
"answer_id": 74659406,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 3,
"selected": true,
"text": "def nth(iterable, n, default=None):\n \"Returns the nth item or a default value\"\n return next(islice(iterable, n, None), default)\n import itertools\n\ndef imparesgen():\n n = 0\n while n<200:\n n=n+2\n yield n\n\ngen = imparesgen()\n\nprint(next(itertools.islice(gen, 3, None)))\n"
},
{
"answer_id": 74659445,
"author": "Lenormju",
"author_id": 11384184,
"author_profile": "https://Stackoverflow.com/users/11384184",
"pm_score": -1,
"selected": false,
"text": "next third = next(next(next(gen)))\n"
},
{
"answer_id": 74659500,
"author": "Tim-Schaeffer_Crown",
"author_id": 20660203,
"author_profile": "https://Stackoverflow.com/users/20660203",
"pm_score": 0,
"selected": false,
"text": "from itertools import islice\n\ndef imparesgen():\n n = 0\n while n<200: \n n=n+2\n yield n\n\ngen = imparesgen()\n\nthird = list(islice(gen, 2, 3))[0] # -> 6\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668655/"
] |
74,659,310
|
<p>I have a dataframe where the rows contain NaN values. The df contains <strong>original columns</strong> namely <strong>Heading 1 Heading 2 and Heading 3</strong> and <strong>extra columns</strong> called <strong>Unnamed: 1 Unnamed: 2 and Unnamed: 3</strong> as shown:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
<th>Unnamed: 1</th>
<th>Unnamed: 2</th>
<th>Unnamed: 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>NaN</td>
<td>34</td>
<td>24</td>
<td>45</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>NaN</td>
<td>24</td>
<td>45</td>
<td>11</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>45</td>
<td>45</td>
<td>33</td>
</tr>
<tr>
<td>4</td>
<td>NaN</td>
<td>24</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>NaN</td>
<td>4</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>34</td>
<td>24</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>22</td>
<td>34</td>
<td>24</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>NaN</td>
<td>34</td>
<td>NaN</td>
<td>45</td>
<td>NaN</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
<p>I want to <strong>iterate through each row</strong> and find out the amount of <strong>leading NaN values</strong> in <strong>original columns (Heading 1 Heading 2 and Heading 3)</strong> and the amount of <strong>non NaN values</strong> in the <strong>extra columns (Unnamed: 1 Unnamed: 2 and Unnamed: 3)</strong>. For each and every row this should be calculated and <strong>returned in a dictionary</strong> where the key is the index of the row and the value for that key is a list containing the amount of <strong>leading NaN values</strong> in <strong>original columns</strong> (Heading 1 Heading 2 and Heading 3) and the second element of the list would the amount of <strong>non NaN values</strong> in the <strong>extra columns</strong> (Unnamed: 1 Unnamed: 2 and Unnamed: 3).</p>
<p>So the result for the above dataframe would be:</p>
<pre><code>{0 : [1, 1],
1 : [2, 2],
2 : [3, 3],
3 : [0, 0],
4 : [2, 0],
5 : [1, 0],
6 : [0, 0],
7 : [1, 1]}
</code></pre>
<p><strong>Notice how in row 3 and row 7 the original columns contain 1 and 2 NaN respectively but only the leading NaN's are counted and not the in between ones!</strong></p>
<p><strong>Thank you!</strong></p>
|
[
{
"answer_id": 74659400,
"author": "Pranav Hosangadi",
"author_id": 843953,
"author_profile": "https://Stackoverflow.com/users/843953",
"pm_score": 0,
"selected": false,
"text": "zip gen gen = imparesgen()\nfor _, item in zip(range(3), gen):\n pass\n\n# Now, item is the third element\nprint(item)\n next() gen = imparesgen()\nnext(gen)\nnext(gen)\nitem = next(gen)\nprint(item)\n next gen = imparesgen()\nfor _ in range(3):\n item = next(gen)\n\nprint(item)\n"
},
{
"answer_id": 74659406,
"author": "treuss",
"author_id": 19838568,
"author_profile": "https://Stackoverflow.com/users/19838568",
"pm_score": 3,
"selected": true,
"text": "def nth(iterable, n, default=None):\n \"Returns the nth item or a default value\"\n return next(islice(iterable, n, None), default)\n import itertools\n\ndef imparesgen():\n n = 0\n while n<200:\n n=n+2\n yield n\n\ngen = imparesgen()\n\nprint(next(itertools.islice(gen, 3, None)))\n"
},
{
"answer_id": 74659445,
"author": "Lenormju",
"author_id": 11384184,
"author_profile": "https://Stackoverflow.com/users/11384184",
"pm_score": -1,
"selected": false,
"text": "next third = next(next(next(gen)))\n"
},
{
"answer_id": 74659500,
"author": "Tim-Schaeffer_Crown",
"author_id": 20660203,
"author_profile": "https://Stackoverflow.com/users/20660203",
"pm_score": 0,
"selected": false,
"text": "from itertools import islice\n\ndef imparesgen():\n n = 0\n while n<200: \n n=n+2\n yield n\n\ngen = imparesgen()\n\nthird = list(islice(gen, 2, 3))[0] # -> 6\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15320579/"
] |
74,659,333
|
<p>I have a fixed size <code>u8</code> array of size <code>2048</code>, which gets filled from a network data of varying lengths. I need to copy this data to a <code>vec</code> of <code>u8</code> of size equal to received length.</p>
<p>This is how I used to do in c++</p>
<pre><code>char buff[2048];
ssize_t data_len = recvfrom(socket, buff, sizeof(buff), 0, nullptr, nullptr);
std::vector<char> vec_buff(buff, buff + data_len)
</code></pre>
<p>I know <code>Vec<T></code> impls <code>From<[T; N]></code> and it can be created from an array by using the <code>From::from()</code> method, but this takes the entire size of <code>2048</code> but I want only <code>data_len</code> bytes.</p>
|
[
{
"answer_id": 74659381,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 4,
"selected": true,
"text": "let vec = buff[..data_len].to_vec();\n Clone buff[..data_len] data_len to_vec Vec let vec = buff.into_iter().take(data_len).collect::<Vec<_>>();\n"
},
{
"answer_id": 74659385,
"author": "Emoun",
"author_id": 8171453,
"author_profile": "https://Stackoverflow.com/users/8171453",
"pm_score": 0,
"selected": false,
"text": "Iterator::take let array: [u8;2048] = ..;\nlet data_vec: Vec<_> = array.iter().cloned().take(data_len).collect();\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3938402/"
] |
74,659,344
|
<p>I would like to match 10 characters after the second pattern:</p>
<p>My String:</p>
<pre><code>www.mysite.de/ep/3423141549/ep/B104RHWZZZ?something
</code></pre>
<p>What I want to be matched:</p>
<pre><code>B104RHWZZZ
</code></pre>
<p>What the regex currently matches:</p>
<pre><code>B104RHWZZZ?something
</code></pre>
<p>Currently, my Regex looks like this:</p>
<pre><code>(?<=\/ep\/)(?:(?!\/ep\/).)*$.
</code></pre>
<p>Could someone help me to change the regex that it only matches 10 characters after the second "/ep/" ("B104RHWZZZ")?</p>
|
[
{
"answer_id": 74659381,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 4,
"selected": true,
"text": "let vec = buff[..data_len].to_vec();\n Clone buff[..data_len] data_len to_vec Vec let vec = buff.into_iter().take(data_len).collect::<Vec<_>>();\n"
},
{
"answer_id": 74659385,
"author": "Emoun",
"author_id": 8171453,
"author_profile": "https://Stackoverflow.com/users/8171453",
"pm_score": 0,
"selected": false,
"text": "Iterator::take let array: [u8;2048] = ..;\nlet data_vec: Vec<_> = array.iter().cloned().take(data_len).collect();\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14171427/"
] |
74,659,373
|
<p>Working on a django web app and running into an issue with my javascript. The web application is multiple different html pages, so the elements my js code is searching for are present on some pages but not others. If the second line is not present on the current page, the script stops running and the final function will not work. I have a "plan" page where you can add additional tags to your plan and then a separate page to filter results. If I'm on the plan page then the "#filterBtn" element is not present so my createNewTagField function doesn't work. If I switch the two lines of code, the opposite happens. I can't get them both to work since the elements javascript is searching for are on two different pages and not present at the same time.</p>
<p>These are the lines causing problems.</p>
<pre><code>document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#mobile-menu').onclick = toggleMobileMenu;
document.querySelector('#filterBtn').onclick = toggleFiltersMenu;
document.querySelector('#addTag').onclick = createNewTagField;
});
</code></pre>
<p>I've rearranged the lines of code and it just fixes it for one page while still having the problem on the other page. I'm thinking it needs to be something like if null then continue to the next line, but haven't been able to find the right code from my searching.</p>
|
[
{
"answer_id": 74659381,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 4,
"selected": true,
"text": "let vec = buff[..data_len].to_vec();\n Clone buff[..data_len] data_len to_vec Vec let vec = buff.into_iter().take(data_len).collect::<Vec<_>>();\n"
},
{
"answer_id": 74659385,
"author": "Emoun",
"author_id": 8171453,
"author_profile": "https://Stackoverflow.com/users/8171453",
"pm_score": 0,
"selected": false,
"text": "Iterator::take let array: [u8;2048] = ..;\nlet data_vec: Vec<_> = array.iter().cloned().take(data_len).collect();\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668723/"
] |
74,659,409
|
<p>My table structure is like this:</p>
<pre><code>+----------+------------+---------------+
| id | manager_id | restaurant_id |
+----------+------------+---------------+
| 1 | 1 | 1001 |
| 2 | 1 | 1002 |
| 3 | 2 | 1003 |
| 4 | 2 | 1004 |
| 5 | 2 | 1005 |
| 6 | 3 | 1006 |
+----------+------------+---------------+
</code></pre>
<p>I want to retrieve all the <code>restaurant_id</code> aggregated per <code>manager_id</code>, Additionally, I also need to filter per manager's <code>count(restaurant_id)</code>: returning only restaurants of managers that have more than one restaurant, and less than 3.</p>
<p>Edit: this is an oversimplified version of the real data, my actual use case must cover <code>more than one</code> to <code>5</code> (included).</p>
<p>So that in the end, the result would be</p>
<pre><code>+---------------+------------+
| restaurant_id | manager_id |
+---------------+------------+
| 1001 | 1 |
| 1002 | 1 |
+---------------+------------+
</code></pre>
<p>I tried something similar to:</p>
<pre><code>SELECT
restaurant_id,
manager_id,
COUNT(*) AS restaurant_count
FROM
Manager_Restaurant
GROUP BY
manager_id
HAVING
restaurant_count > 1 and
restaurant_count < 3;
</code></pre>
<p>But this return only one line per manager because of the grouping and I want all the restaurants.</p>
|
[
{
"answer_id": 74659381,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 4,
"selected": true,
"text": "let vec = buff[..data_len].to_vec();\n Clone buff[..data_len] data_len to_vec Vec let vec = buff.into_iter().take(data_len).collect::<Vec<_>>();\n"
},
{
"answer_id": 74659385,
"author": "Emoun",
"author_id": 8171453,
"author_profile": "https://Stackoverflow.com/users/8171453",
"pm_score": 0,
"selected": false,
"text": "Iterator::take let array: [u8;2048] = ..;\nlet data_vec: Vec<_> = array.iter().cloned().take(data_len).collect();\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/954777/"
] |
74,659,435
|
<p>I am trying to create a django view which will let users to create a new product on the website.</p>
<pre><code>class CreateProductView(APIView):
serializer_class = CreateProductSerializer
def post(self, request, format = None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.data.name
content = serializer.data.content
category = serializer.data.category
product = Product(name=name, content=content, category=category)
product.save()
return Response(ProductSerializer(product).data, status=status.HTTP_201_CREATED)
</code></pre>
<p>But it is giving this error:</p>
<pre><code>UnboundLocalError at /api/create-product
local variable 'product' referenced before assignment
Request Method: POST
Request URL: http://127.0.0.1:8000/api/create-product
Django Version: 4.0.5
Exception Type: UnboundLocalError
Exception Value:
local variable 'product' referenced before assignment
Exception Location: H:\Extension Drive (H)\My Software Applications\DeCluttered_Life\declutterd_life\api\views.py, line 42, in post
Python Executable: C:\Python310\python.exe
Python Version: 3.10.5
Python Path:
['H:\\Extension Drive (H)\\My Software '
'Applications\\DeCluttered_Life\\declutterd_life',
'C:\\Python310\\python310.zip',
'C:\\Python310\\DLLs',
'C:\\Python310\\lib',
'C:\\Python310',
'C:\\Python310\\lib\\site-packages']
Server time: Fri, 02 Dec 2022 17:26:24 +0000
</code></pre>
<p>I tried to look other issues similar to this, but couldn't find the solution.</p>
|
[
{
"answer_id": 74659381,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 4,
"selected": true,
"text": "let vec = buff[..data_len].to_vec();\n Clone buff[..data_len] data_len to_vec Vec let vec = buff.into_iter().take(data_len).collect::<Vec<_>>();\n"
},
{
"answer_id": 74659385,
"author": "Emoun",
"author_id": 8171453,
"author_profile": "https://Stackoverflow.com/users/8171453",
"pm_score": 0,
"selected": false,
"text": "Iterator::take let array: [u8;2048] = ..;\nlet data_vec: Vec<_> = array.iter().cloned().take(data_len).collect();\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16137730/"
] |
74,659,436
|
<p>I'm trying to batch merge to create multiple nodes. Using the below code,</p>
<pre><code>def test_batches(tx,user_batch):
result= tx.run(f"Unwind {user_batch} as user\
MERGE (n:User {{id: user.id, name: user.name, username: user.username }})")
</code></pre>
<p>However I am getting this error.
Note I'm passing in a list of dictionaries.</p>
<pre><code>CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '[': expected "+" or "-" (line 1, column 8 (offset: 7))
"Unwind [{'id': 1596859520977969156, 'name': 'Bigspuds', 'username': 'bigspuds777'}, {'id': 1596860505662144513, 'name': 'JOHN VIEIRA', 'username': 'JOHNVIE67080352'}, {'id': 1596860610905448449, 'name': 'biru nkumat', 'username': 'NkumatB'}, {'id': 1513497734711738374, 'name': 'elfiranda Hakim', 'username': 'Kidonk182'}, {'id': 1596836234860859392, 'name': 'Ecat Miao', 'username': 'sylvanasMa'}] as user MERGE (n:User {id: user.id, name: user.name, username: user.username })"
^}
</code></pre>
<p>I have no idea why this is happening any help is greatly appreciated.</p>
|
[
{
"answer_id": 74659636,
"author": "Frederik Bruun",
"author_id": 6172247,
"author_profile": "https://Stackoverflow.com/users/6172247",
"pm_score": 0,
"selected": false,
"text": "def test_batches(tx,user_batch):\n result = tx.run(f\"UNWIND {user_batch} as user\n MERGE (n:User {{id: user.id, name: user.name, username: user.username }})\n ON CREATE SET n = user\n ON MATCH SET n += user\")\n"
},
{
"answer_id": 74660881,
"author": "jose_bacoy",
"author_id": 7371893,
"author_profile": "https://Stackoverflow.com/users/7371893",
"pm_score": 2,
"selected": true,
"text": "from neo4j import GraphDatabase\n\nuri = \"neo4j://localhost:7687\"\ndriver = GraphDatabase.driver(uri, auth=(\"neo4j\", \"awesomepassword\"))\n\ndef test_batches(tx, user_batch):\n tx.run(\"UNWIND $user_batch as user \\\n MERGE (n:User {id: user.id, name: user.name, username: user.username})\", user_batch=user_batch)\n \nwith driver.session() as session:\n user_batch = [\n {'id': 1596859520977969156, 'name': 'Bigspuds', 'username': 'bigspuds777'}, \n {'id': 1596860505662144513, 'name': 'JOHN VIEIRA', 'username': 'JOHNVIE67080352'}, \n {'id': 1596860610905448449, 'name': 'biru nkumat', 'username': 'NkumatB'}, \n {'id': 1513497734711738374, 'name': 'elfiranda Hakim', 'username': 'Kidonk182'}, \n {'id': 1596836234860859392, 'name': 'Ecat Miao', 'username': 'sylvanasMa'}]\n session.write_transaction(test_batches, user_batch) \n\ndriver.close()\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20321674/"
] |
74,659,463
|
<p>I have a NextJS app that I am using Jest and React Testing Library to test. I have a card component that is passed data (id, image url, text, and name) that is rendered on the card. This works correctly on the webpage. When I run the test, the test cannot find any text on the page.</p>
<p>Here is the component:</p>
<pre><code>import React from "react";
import Image from "next/image";
import styles from "./testCard.module.css";
export default function TestCard(data) {
const card = data.data;
return (
<>
<div className={styles.cardContainer}>
<div className={styles.cardTop}>
<div className={styles.cardImg}>
<Image
src={card.imgUrl}
alt=""
height={150}
width={150}
loading="lazy"
className={styles.circular}
/>
</div>
</div>
<div className={styles.cardBottom}>
<div className={styles.cardText}>
<p>&quot;{card.text}&quot;</p>
</div>
<div className={styles.cardName}>
<p>-{card.name}</p>
</div>
</div>
</div>
</>
);
}
</code></pre>
<p>Here is the test file:</p>
<pre><code>import React from "react";
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import TestCard from "./testCard";
import { testimonialMock } from "../../__mocks__/next/testimonialMock";
describe("TestCard Component", () => {
it("renders the component", () => {
render(<TestCard data={testimonialMock} />);
});
it("renders the component unchanged", () => {
const { containter } = render(<TestCard data={testimonialMock} />);
expect(containter).toMatchSnapshot();
});
it("renders the passed in data", () => {
render(<TestCard data={testimonialMock} />);
screen.getByRole('p', {name: /test text/i});
});
});
</code></pre>
<p>And here is the testimonialMock.js file:</p>
<pre><code>export const testimonialMock = [
{
id: 0,
imgUrl: "/img/mock.png",
text: "test text",
name: "test name",
},
];
</code></pre>
<p>Here is the result I am getting:</p>
<pre><code>TestCard Component
✓ renders the component (12 ms)
✓ renders the component unchanged (5 ms)
✕ renders the passed in data (15 ms)
● TestCard Component › renders the passed in data
TestingLibraryElementError: Unable to find an element with the text: test text. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, script, style
<body>
<div>
<div
class="cardContainer"
>
<div
class="cardTop"
>
<div
class="cardImg"
/>
</div>
<div
class="cardBottom"
>
<div
class="cardText"
>
<p>
"
"
</p>
</div>
<div
class="cardName"
>
<p>
-
</p>
</div>
</div>
</div>
</div>
</body>
17 | it("renders the passed in data", () => {
18 | render(<TestCard data={testimonialMock} />);
> 19 | expect(screen.getByText("test text")).toBeInTheDocument();
| ^
20 | });
21 | });
22 |
at Object.getElementError (node_modules/.pnpm/@testing-library+dom@8.19.0/node_modules/@testing-library/dom/dist/config.js:40:19)
at node_modules/.pnpm/@testing-library+dom@8.19.0/node_modules/@testing-library/dom/dist/query-helpers.js:90:38
at node_modules/.pnpm/@testing-library+dom@8.19.0/node_modules/@testing-library/dom/dist/query-helpers.js:62:17
at node_modules/.pnpm/@testing-library+dom@8.19.0/node_modules/@testing-library/dom/dist/query-helpers.js:111:19
at Object.getByText (components/testCard/testCard.test.js:19:19)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 2 passed, 3 total
Snapshots: 1 passed, 1 total
Time: 0.725 s, estimated 1 s
Ran all test suites matching /testCard.test.js/i.
</code></pre>
<p>I have tried using different forms of passing in the data and different queries, all to no avail.</p>
|
[
{
"answer_id": 74659636,
"author": "Frederik Bruun",
"author_id": 6172247,
"author_profile": "https://Stackoverflow.com/users/6172247",
"pm_score": 0,
"selected": false,
"text": "def test_batches(tx,user_batch):\n result = tx.run(f\"UNWIND {user_batch} as user\n MERGE (n:User {{id: user.id, name: user.name, username: user.username }})\n ON CREATE SET n = user\n ON MATCH SET n += user\")\n"
},
{
"answer_id": 74660881,
"author": "jose_bacoy",
"author_id": 7371893,
"author_profile": "https://Stackoverflow.com/users/7371893",
"pm_score": 2,
"selected": true,
"text": "from neo4j import GraphDatabase\n\nuri = \"neo4j://localhost:7687\"\ndriver = GraphDatabase.driver(uri, auth=(\"neo4j\", \"awesomepassword\"))\n\ndef test_batches(tx, user_batch):\n tx.run(\"UNWIND $user_batch as user \\\n MERGE (n:User {id: user.id, name: user.name, username: user.username})\", user_batch=user_batch)\n \nwith driver.session() as session:\n user_batch = [\n {'id': 1596859520977969156, 'name': 'Bigspuds', 'username': 'bigspuds777'}, \n {'id': 1596860505662144513, 'name': 'JOHN VIEIRA', 'username': 'JOHNVIE67080352'}, \n {'id': 1596860610905448449, 'name': 'biru nkumat', 'username': 'NkumatB'}, \n {'id': 1513497734711738374, 'name': 'elfiranda Hakim', 'username': 'Kidonk182'}, \n {'id': 1596836234860859392, 'name': 'Ecat Miao', 'username': 'sylvanasMa'}]\n session.write_transaction(test_batches, user_batch) \n\ndriver.close()\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15061254/"
] |
74,659,476
|
<p>I have a text file with over 250 million lines. Each line has a 3 digit area code followed by a comma and a 7 digit number.</p>
<p>Sample Input File:<br />
201,2220000<br />
201,5551212<br />
310,5552481<br />
376,1239876<br />
443,0002222<br />
572,8880099<br />
...</p>
<p>I would like to generate an output file which lists each unique area code and the number of occurrences of that area code (only looking at the first 3 characters of each line).</p>
<p>Example output (area code, count):<br />
201, 44556<br />
202, 34529<br />
...</p>
<p>I am working in a Windows 10 environment.</p>
<p>After considerable research, I was able to use the Switch function with <a href="/questions/tagged/regex" class="post-tag" title="show questions tagged 'regex'" aria-label="show questions tagged 'regex'" rel="tag" aria-labelledby="regex-container">regex</a> in PowerShell to achieve something very close. The problem with this solution is that I need to know which area codes I am looking for (and I don't know all the area codes listed in this file).</p>
<p>I would like to modify the solution such that it finds all unique area codes and then run the code.</p>
<p>Here's what I have tried:</p>
<hr />
<ol>
<li>Say, I want to search for the following four area codes: 201,202,203,205</li>
<li>My text file is datafile.txt</li>
</ol>
<pre><code>$count1 = 0
$count2 = 0
$count3 = 0
$count4 = 0
switch -File C:\datafile.txt -Exact -Regex { '201\S{8}' { ++$count1 } }
Write-Output "Area Code 201: $($count1)" | Format-Table | Out-File "C:\summary.txt" -append
switch -File C:\datafile.txt -Exact -Regex { '202\S{8}' { ++$count2 } }
Write-Output "Area Code 202: $($count2)" | Format-Table | Out-File "C:\summary.txt" -append
switch -File C:\datafile.txt -Exact -Regex { '203\S{8}' { ++$count3 } }
Write-Output "Area Code 203: $($count3)" | Format-Table | Out-File "C:\summary.txt" -append
switch -File C:\datafile.txt -Exact -Regex { '205\S{8}' { ++$count4 } }
Write-Output "Area Code 204: $($count4)" | Format-Table | Out-File "C:\summary.txt" -append
</code></pre>
<p>This code generates the file summary.txt and appends the counts to the area codes. However, I think this is inefficient as:</p>
<ol>
<li>I need to know all the area codes that are in this datafile.</li>
<li>I have to add 3 lines of code for every additional area code.</li>
</ol>
<p>Would appreciate any help improving this code or for using an alternate solution (I found a thread on Stackoverflow that uses grep <a href="https://www.stackoverflow.com/">https://stackoverflow.com/questions/61229157/using-regex-in-grep-for-windows-command-line</a>, but it has the same limitation - you need to know what string you are searching for.</p>
|
[
{
"answer_id": 74659596,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 3,
"selected": true,
"text": ".SubString(0, 3) switch -File File.ReadLines $map = @{ }\nswitch -File path\\to\\source\\file.txt {\n Default {\n $map[$_.Substring(0, 3)] += 1\n }\n}\n\n$map.GetEnumerator() | ForEach-Object {\n [pscustomobject]@{\n Code = $_.Key\n Count = $_.Value\n }\n} | Export-Csv path\\to\\resultOfUniqueCodes.csv -NoTypeInformation\n"
},
{
"answer_id": 74659606,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 0,
"selected": false,
"text": "$input = @\"\narea,number\n201,44556\n202,34529\n201,44556\n202,34529\n201,44556\n202,34529\n201,44556\n202,34529\n\"@\n\n$table = $input | ConvertFrom-Csv\n$table | Format-Table\n\n$groups = $table | Group-Object {$_.area}\n\n$outputTable = [System.Collections.ArrayList]::new()\nforeach($group in $groups)\n{\n$group | Format-Table\n\n $newRow = New-Object -TypeName psobject\n $newRow | Add-Member -NotePropertyName area -NotePropertyValue $group.Name\n\n $newRow | Add-Member -NotePropertyName count -NotePropertyValue $group.Count\n\n $outputTable.Add($newRow) | Out-Null\n}\n$outputTable | Format-Table\n"
},
{
"answer_id": 74660210,
"author": "zett42",
"author_id": 7571258,
"author_profile": "https://Stackoverflow.com/users/7571258",
"pm_score": 1,
"selected": false,
"text": "ForEach-Object pscustomobject Export-Csv # Create a scriptblock to be able to pipe output of foreach loop\n& { \n foreach( $line in [IO.File]::ReadLines( 'input.txt' ) ) { \n $line.Substring( 0, 3 )\n }\n} | Group-Object -NoElement | & {\n begin {\n 'Code,Count'\n }\n process {\n '{0},{1}' -f $_.Name, $_.Count\n }\n} | Set-Content output.csv\n foreach( $line in [IO.File]::ReadLines( 'input.txt' ) ) ReadLines foreach ReadLines Group-Object -NoElement Group-Object ForEach-Object Export-Csv Set-Content"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14714446/"
] |
74,659,502
|
<p>I'm trying to get this loop to continue. So far, when input is not matched to my REGEX, "input not valid" gets displayed but loop won't continue. What am I missing here?</p>
<p>Apreciate your help!</p>
<pre><code>import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input;
//some variables
Pattern pattern = Pattern.compile(REGEX);
Scanner scn = new Scanner(System.in);
boolean found = false;
do {
System.out.println("ask user for input");
input = scn.next();
Matcher matcher = pattern.matcher(input);
try {
matcher.find();
//some Code
found = true;
scn.close();
} catch (IllegalStateException e) {
System.out.println("input not valid."); //stuck here
scn.next();
continue;
}
} while (!found);
// some more Code
}
}
</code></pre>
|
[
{
"answer_id": 74659632,
"author": "Sam Cousins",
"author_id": 19152535,
"author_profile": "https://Stackoverflow.com/users/19152535",
"pm_score": 0,
"selected": false,
"text": "scn.next()"
},
{
"answer_id": 74659680,
"author": "horcrux",
"author_id": 4607733,
"author_profile": "https://Stackoverflow.com/users/4607733",
"pm_score": 2,
"selected": true,
"text": "IllegalStateException matcher.find() found = matcher.find() scn.next(); boolean found = false; boolean found; continue; boolean found;\n do {\n System.out.println(\"ask user for input\");\n input = scn.next();\n found = pattern.matcher(input).find();\n if (!found) {\n System.out.println(\"input not valid.\");\n }\n } while (!found);\n scn.close();\n"
},
{
"answer_id": 74659753,
"author": "igobr",
"author_id": 20085654,
"author_profile": "https://Stackoverflow.com/users/20085654",
"pm_score": 0,
"selected": false,
"text": "import java.util.Scanner;\nimport java.util.regex.Pattern;\n\npublic class Main {\n private static final Pattern pattern = Pattern.compile(\"^[a-zA-Z0-9 ]+$\");\n\n public static void main(String[] args) {\n Scanner scn = new Scanner(System.in);\n boolean valid;\n String value;\n do {\n System.out.println(\"ask user for input\");\n value = scn.next();\n valid = pattern.matcher(value).matches();\n if (!valid) System.out.println(\"input not valid.\");\n } while (!valid);\n\n System.out.printf(\"Valid input is %s\", value);\n }\n}\n ask user for input\n123-abc\ninput not valid.\nask user for input\nqwerty58\nValid input is qwerty58\nProcess finished with exit code 0\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668683/"
] |
74,659,510
|
<p>I have to make a recursive function that counts how many negative values there are in a given list, but I can't figure out what I am supposed to return for each conditional.</p>
<pre><code>def countNegatives(list):
"""Takes in a list of numbers and
returns the number of negative numbers
that are inside the list."""
count = 0
if len(list) == 0:
return 0
else:
if list[0] < 0:
return count + 1
else:
return countNegatives(list[1:])
print(countNegatives([0, 1, -1, 3, -5, 6])) # should output 2 but gives me 1
print(countNegatives([-1, -3, 50,-4, -5, 1])) #should output 4 but gives me 1
</code></pre>
|
[
{
"answer_id": 74659572,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 0,
"selected": false,
"text": "list[0] < 0 return count + 1\n return 1 + countNegatives(list[1:])\n"
},
{
"answer_id": 74659599,
"author": "Random Davis",
"author_id": 6273251,
"author_profile": "https://Stackoverflow.com/users/6273251",
"pm_score": 0,
"selected": false,
"text": "def countNegatives(list):\n #if the list length is zero, we are done\n if len(list) == 0:\n return 0\n\n # Get the count of this iteration\n count = 1 if list[0] < 0 else 0\n # sum the count of this iteration with the count of all subsequent iterations\n return count + countNegatives(list[1:])\n return 0 + countNegatives([1, -1, 3, -5, 6])\nreturn 0 + countNegatives([-1, 3, -5, 6])\nreturn 1 + countNegatives([3, -5, 6])\nreturn 0 + countNegatives([-5, 6])\nreturn 1 + countNegatives([6])\nreturn 0 + countNegatives([])\nreturn 0\n return 0 + 0 + 1 + 0 + 1 + 0 + 0 \n"
},
{
"answer_id": 74659669,
"author": "Pankaj Chandravanshi",
"author_id": 17743521,
"author_profile": "https://Stackoverflow.com/users/17743521",
"pm_score": -1,
"selected": false,
"text": "count + 1 count def countNegatives(lst):\n \"\"\"Takes in a list of numbers and\n returns the number of negative numbers\n that are inside the list.\"\"\"\n count = 0\n if len(lst) == 0:\n return 0\n else:\n if lst[0] < 0:\n count += 1\n count += countNegatives(lst[1:])\n return count\n\nprint(countNegatives([0, 1, -1, 3, -5, 6])) # Output: 2\nprint(countNegatives([-1, -3, 50, -4, -5, 1])) # Output: 4\n list lst list"
},
{
"answer_id": 74659731,
"author": "tdelaney",
"author_id": 642070,
"author_profile": "https://Stackoverflow.com/users/642070",
"pm_score": -1,
"selected": false,
"text": "count def countNegatives(list, count=0):\n \"\"\"Takes in a list of numbers and\n returns the number of negative numbers\n that are inside the list.\"\"\"\n if len(list):\n count += list[0] < 0\n return countNegatives(list[1:], count)\n else:\n return count\n\nresult = countNegatives([1,99, -3, 6, -66, -7, 12, -1, -1])\nprint(result)\nassert result == 5\n \n"
},
{
"answer_id": 74666990,
"author": "Mulan",
"author_id": 633183,
"author_profile": "https://Stackoverflow.com/users/633183",
"pm_score": 0,
"selected": false,
"text": "0 def countNegatives(t):\n if not t: return 0 # 1\n elif t[0] < 0: return 1 + countNegatives(t[1:]) # 2\n else: return 0 + countNegatives(t[1:]) # 3\n def countNegatives(t):\n match t:\n case []: #1\n return 0\n case [n, *next] if n < 0: #2\n return 1 + countNegatives(next)\n case [_, *next]: #3\n return 0 + countNegatives(next)\n"
},
{
"answer_id": 74668378,
"author": "pjs",
"author_id": 2166798,
"author_profile": "https://Stackoverflow.com/users/2166798",
"pm_score": 1,
"selected": true,
"text": "print(countNegatives([i-5000 for i in range(10000)]))\n def countNegatives(lst):\n size = len(lst) # evaluate len() only once\n if size > 1:\n mid = size // 2 # find midpoint of lst\n return countNegatives(lst[:mid]) + countNegatives(lst[mid:])\n if size == 1 and lst[0] < 0:\n return 1\n return 0\n\nprint(countNegatives([0, 1, -1, 3, -5, 6])) # 2\nprint(countNegatives([-1, -3, 50, -4, -5, 1])) # 4\nprint(countNegatives([i - 5000 for i in range(10000)])) # 5000\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20662448/"
] |
74,659,522
|
<p>I'm still a newbie in React and I've been struggling for some time with the topic mentioned above. I've got a state which looks like this:</p>
<pre><code>const [questions, setQuestions] = React.useState([])
React.useEffect(()=>{
fetch('https://the-trivia-api.com/api/questions?limit=5&difficulty=medium').then((response)=>response.json()).then((data)=>{
let questionsData = data.map((item) => {
return {
id: nanoid(),
questionText: item.question,
answerOptions: [
{id: nanoid(), answerText: item.correctAnswer, isCorrect: true, selected: false,},
{id: nanoid(), answerText: item.incorrectAnswers[0], isCorrect: false, selected: false,},
{id: nanoid(), answerText: item.incorrectAnswers[1], isCorrect: false, selected: false,},
{id: nanoid(), answerText: item.incorrectAnswers[2], isCorrect: false, selected: false,},
].sort(()=>Math.random() -0.5),
};
})
setQuestions(questionsData)
})
}, [])
</code></pre>
<p>It's a state that returns me a quiz question and 4 "randomized" buttons. What I'm trying to do is to update the state to make one of the answerOptions (that is buttons) from selected: false to selected: true. I'm sure it's doable with .map and spread operator but I'm really lost with the syntax</p>
<p>selectAnswer is triggered by an onChange from the radio buttons from the child Component.
I have access to both the question id and each of the answerOptions id so accessing those is not a problem. I just can't figure out how to return the state. Below is an example of my failed attempt to do that.</p>
<pre><code> function selectAnswer(answerId, questionId){
setQuestions(prevData => prevData.map((item)=>{
return item.answerOptions.map((answerItem)=>{
if(answerId === answerItem.id) {
return {...item, [answerOptions[answerItem].selected]: !answerOptions[answerItem].selected}
} else return {...item}
})
}))
}
</code></pre>
<p>Thank you for your time in advance</p>
|
[
{
"answer_id": 74659590,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions((prevData) =>\n prevData.map((item) => ({\n ...item,\n answerOptions: item.answerOptions.map((answerItem) => ({\n ...answerItem,\n selected: answerId === answerItem.id,\n })),\n }))\n );\n}\n"
},
{
"answer_id": 74659621,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 2,
"selected": true,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions(prevData =>\n prevData.map(question => {\n // Create a new array of answerOptions for this question,\n // with the selected answerOption updated to have its selected property set to true.\n const answerOptions = question.answerOptions.map(answerOption => {\n if (answerOption.id === answerId) {\n return { ...answerOption, selected: true };\n } else {\n return answerOption;\n }\n });\n\n // Return a new object for this question with the updated answerOptions array.\n return { ...question, answerOptions };\n })\n );\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668458/"
] |
74,659,543
|
<p>I would like to be able to install the python module jupyter with pip but I get an error in my terminal when I try 'pip install jupyter' which returns this:
`</p>
<pre><code> error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [9 lines of output]
C:\Users\nunes\AppData\Local\Temp\pip-build-env-dofs9qdx\overlay\Lib\site-packages\setuptools\_distutils\dist.py:265: UserWarning: Unknown distribution option: 'cffi_modules'
warnings.warn(msg)
running egg_info
writing pyzmq.egg-info\PKG-INFO
writing dependency_links to pyzmq.egg-info\dependency_links.txt
writing requirements to pyzmq.egg-info\requires.txt
writing top-level names to pyzmq.egg-info\top_level.txt
running configure
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
</code></pre>
<p>`</p>
<p>I have installed Microsoft Visual Studio Builds Tools as indicated but still the same error.
If someone has an idea I'm a taker thank you in advance for your help.</p>
|
[
{
"answer_id": 74659590,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions((prevData) =>\n prevData.map((item) => ({\n ...item,\n answerOptions: item.answerOptions.map((answerItem) => ({\n ...answerItem,\n selected: answerId === answerItem.id,\n })),\n }))\n );\n}\n"
},
{
"answer_id": 74659621,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 2,
"selected": true,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions(prevData =>\n prevData.map(question => {\n // Create a new array of answerOptions for this question,\n // with the selected answerOption updated to have its selected property set to true.\n const answerOptions = question.answerOptions.map(answerOption => {\n if (answerOption.id === answerId) {\n return { ...answerOption, selected: true };\n } else {\n return answerOption;\n }\n });\n\n // Return a new object for this question with the updated answerOptions array.\n return { ...question, answerOptions };\n })\n );\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16996888/"
] |
74,659,589
|
<p>I've managed to convert a js sudoku generator into a ts generator for some practice and the only problem I'm having is getting it to output only complete boards. Right now, it's outputting boards regardless if they're complete and I have to refresh until one board is correct.</p>
<p>I'm not sure how to write the following function so that it only outputs full boards:</p>
<pre><code>function fillBoard(puzzleArray: number[][]): number[][] {
if (nextEmptyCell(puzzleArray).colIndex === -1) return puzzleArray;
let emptyCell = nextEmptyCell(puzzleArray);
for (var num in shuffle(numArray)) {
if (safeToPlace(puzzleArray, emptyCell, numArray[num])) {
puzzleArray[emptyCell.rowIndex][emptyCell.colIndex] = numArray[num];
fillBoard(puzzleArray);
}
}
return puzzleArray;
}
</code></pre>
<p>Here is all my code:</p>
<pre><code>import { Box } from "./Box";
export function Board() {
let BLANK_BOARD = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
];
let NEW_BOARD = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
];
let counter: number = 0;
let check: number[];
const numArray: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function rowSafe(
puzzleArray: number[][],
emptyCell: { rowIndex: number; colIndex: number },
num: number
): boolean {
return puzzleArray[emptyCell.rowIndex].indexOf(num) == -1;
}
function colSafe(
puzzleArray: number[][],
emptyCell: { rowIndex: number; colIndex: number },
num: number
): boolean {
let test = puzzleArray.flat();
for (let i = emptyCell.colIndex; i < test.length; i += 9) {
if (test[i] === num) {
return false;
}
}
return true;
}
function regionSafe(
puzzleArray: number[][],
emptyCell: { rowIndex: number; colIndex: number },
num: number
): boolean {
const rowStart: number = emptyCell.rowIndex - (emptyCell.rowIndex % 3);
const colStart: number = emptyCell.colIndex - (emptyCell.colIndex % 3);
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (puzzleArray[rowStart + i][colStart + j] === num) {
return false;
}
}
}
return true;
}
console.log(rowSafe(BLANK_BOARD, { rowIndex: 4, colIndex: 6 }, 5));
console.log(colSafe(BLANK_BOARD, { rowIndex: 2, colIndex: 3 }, 4));
console.log(regionSafe(BLANK_BOARD, { rowIndex: 5, colIndex: 6 }, 5));
function safeToPlace(
puzzleArray: number[][],
emptyCell: { rowIndex: number; colIndex: number },
num: number
): boolean {
return (
regionSafe(puzzleArray, emptyCell, num) &&
rowSafe(puzzleArray, emptyCell, num) &&
colSafe(puzzleArray, emptyCell, num)
);
}
console.log(safeToPlace(BLANK_BOARD, { rowIndex: 5, colIndex: 6 }, 5));
function nextEmptyCell(puzzleArray: number[][]): {
colIndex: number;
rowIndex: number;
} {
let emptyCell = { rowIndex: -1, colIndex: -1 };
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (puzzleArray[i][j] === 0) {
return { rowIndex: i, colIndex: j };
}
}
}
return emptyCell;
}
function shuffle(array: number[]): number[] {
// using Array sort and Math.random
let shuffledArr = array.sort(() => 0.5 - Math.random());
return shuffledArr;
}
function fillBoard(puzzleArray: number[][]): number[][] {
if (nextEmptyCell(puzzleArray).colIndex === -1) return puzzleArray;
let emptyCell = nextEmptyCell(puzzleArray);
for (var num in shuffle(numArray)) {
if (safeToPlace(puzzleArray, emptyCell, numArray[num])) {
puzzleArray[emptyCell.rowIndex][emptyCell.colIndex] = numArray[num];
fillBoard(puzzleArray);
} else {
puzzleArray[emptyCell.rowIndex][emptyCell.colIndex] = 0;
}
}
return puzzleArray;
}
console.log(nextEmptyCell(BLANK_BOARD));
NEW_BOARD = fillBoard(BLANK_BOARD);
function fullBoard(puzzleArray: number[][]): boolean {
return puzzleArray.every((row) => row.every((col) => col !== 0));
}
return (
<div
style={{
height: "450px",
width: "450px",
display: "inline-grid",
gap: "10px",
gridTemplateColumns: "repeat(9,50px)",
gridTemplateRows: "repeat(9,50px)",
position: "absolute",
top: "30px",
left: "0px",
right: "0px",
marginLeft: "auto",
marginRight: "auto",
}}
>
{NEW_BOARD.flat().map((item) => (
<Box i={item} />
))}
</div>
);
}
</code></pre>
|
[
{
"answer_id": 74659590,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions((prevData) =>\n prevData.map((item) => ({\n ...item,\n answerOptions: item.answerOptions.map((answerItem) => ({\n ...answerItem,\n selected: answerId === answerItem.id,\n })),\n }))\n );\n}\n"
},
{
"answer_id": 74659621,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 2,
"selected": true,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions(prevData =>\n prevData.map(question => {\n // Create a new array of answerOptions for this question,\n // with the selected answerOption updated to have its selected property set to true.\n const answerOptions = question.answerOptions.map(answerOption => {\n if (answerOption.id === answerId) {\n return { ...answerOption, selected: true };\n } else {\n return answerOption;\n }\n });\n\n // Return a new object for this question with the updated answerOptions array.\n return { ...question, answerOptions };\n })\n );\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310478/"
] |
74,659,607
|
<p>I was searching to find how to make the camera fit a game object and I found this answer:</p>
<p><a href="https://stackoverflow.com/questions/71013982/change-the-size-of-camera-to-fit-a-gameobject-in-unity-c">Change the size of camera to fit a GameObject in Unity/C#</a> ,
and I don't understand this part</p>
<pre><code>cam.orthographicSize = ((w > h * cam.aspect) ? (float)w / (float)cam.pixelWidth * cam.pixelHeight : h) / 2;
</code></pre>
<p>I want to understand how that part of the code works.</p>
|
[
{
"answer_id": 74659590,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions((prevData) =>\n prevData.map((item) => ({\n ...item,\n answerOptions: item.answerOptions.map((answerItem) => ({\n ...answerItem,\n selected: answerId === answerItem.id,\n })),\n }))\n );\n}\n"
},
{
"answer_id": 74659621,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 2,
"selected": true,
"text": "function selectAnswer(answerId, questionId) {\n setQuestions(prevData =>\n prevData.map(question => {\n // Create a new array of answerOptions for this question,\n // with the selected answerOption updated to have its selected property set to true.\n const answerOptions = question.answerOptions.map(answerOption => {\n if (answerOption.id === answerId) {\n return { ...answerOption, selected: true };\n } else {\n return answerOption;\n }\n });\n\n // Return a new object for this question with the updated answerOptions array.\n return { ...question, answerOptions };\n })\n );\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668889/"
] |
74,659,635
|
<p>I'm developing Serial Port program using Boost::Asio.<br>
I call the <code>SerialPort::read_async</code> method every time I want to read data from serial port.<br>
While I am testing I realized that the data received on serial port is not getting saved in the <code>read_buffer</code> however the read handler receives proper number of received bytes in <code>boost::asio::placeholders::bytes_transferred</code> field/parameter. The read handler also contains <code>boost::system::errc::success</code> in the <code>boost::asio::placeholders::error</code> field/parameter.<br></p>
<p>The <code>read_buffer</code> holds exactly the same value that was set before the <code>async_read_some</code> call was made.<br></p>
<pre><code>this->read_buffer.fill(static_cast<std::byte>('\0')); //Clear Buffer
this->read_buffer.fill(static_cast<std::byte>('0')); //For Testing
</code></pre>
<p>Code</p>
<pre><code>bool SerialPort::read_async(std::uint32_t read_timeout)
{
try
{
this->read_buffer.fill(static_cast<std::byte>('\0')); //Clear Buffer
//this->read_buffer.fill(static_cast<std::byte>('0')); //For Testing
if (read_timeout not_eq SerialPort::ignore_timeout)
this->read_timeout = read_timeout;//If read_timeout is not set to ignore_timeout, update the read_timeout else use old read_timeout
this->port.async_read_some(boost::asio::buffer(this->read_buffer.data(), this->read_buffer.size()),
boost::bind(&SerialPort::read_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
return true;
}
catch (const std::exception& ex)
{
PLOG_ERROR << ex.what();
return false;
}
}
</code></pre>
<hr />
<p>Update</p>
<p>Remaining Code</p>
<pre><code>bool SerialPort::open_port(const std::string& port_name, std::uint32_t baud_rate, std::uint8_t data_bits, std::uint8_t stop_bits,
parity_t parity, flow_control_t flow_control, std::uint32_t read_timeout, std::uint32_t read_inter_byte_timeout,
std::uint32_t write_timeout)
{
try
{
this->port_name = port_name;
if (not this->open_port())
return false;
if (not this->set_baud_rate(baud_rate).has_value())
return false;
if (not this->set_data_bits(data_bits).has_value())
return false;
if (not this->set_stop_bits(stop_bits).has_value())
return false;
if (not this->set_parity(parity).has_value())
return false;
if (not this->set_flow_control(flow_control).has_value())
return false;
this->read_timeout = read_timeout;
if (read_inter_byte_timeout <= 0)
this->read_inter_byte_timeout = 1;
#ifdef _WIN64
BOOL return_value;
DCB dcb = { 0 };
COMMTIMEOUTS timeouts = { 0 };
if (this->line_mode) //Set COM port to return data either at \n or \r
{
/*
* If the function succeeds, the return value is nonzero.
* If the function fails, the return value is zero. To get extended error information, call GetLastError.
*/
return_value = GetCommState(this->native_port, &dcb);
if (return_value)
{
if(this->new_line_character == '\r')
dcb.EofChar = '\r'; //Specify end of data character as carriage-return (\r)
else // --> Default
dcb.EofChar = '\n'; //Specify end of data character as new-line (\n)
}
else
{
PLOG_ERROR << "Error GetCommState : " << GetLastErrorAsString();
return false;
}
/*
* If the function succeeds, the return value is nonzero.
* If the function fails, the return value is zero. To get extended error information, call GetLastError.
*/
return_value = SetCommState(this->native_port, &dcb);
if (not return_value)
{
PLOG_ERROR << "Error SetCommState : " << GetLastErrorAsString();
return false;
}
}
else //Set COM port to return data on timeout
{
/*
* If the function succeeds, the return value is nonzero.
* If the function fails, the return value is zero. To get extended error information, call GetLastError.
*/
return_value = GetCommTimeouts(this->native_port, &timeouts);
if (return_value)
{
timeouts.ReadIntervalTimeout = this->read_inter_byte_timeout; // Timeout in miliseconds
//timeouts.ReadTotalTimeoutConstant = 0; //MAXDWORD; // in milliseconds - not needed
//timeouts.ReadTotalTimeoutMultiplier = 0; // in milliseconds - not needed
//timeouts.WriteTotalTimeoutConstant = 50; // in milliseconds - not needed
//timeouts.WriteTotalTimeoutMultiplier = write_timeout; // in milliseconds - not needed
}
else
{
PLOG_ERROR << "Error GetCommTimeouts : " << GetLastErrorAsString();
return false;
}
/*
* If the function succeeds, the return value is nonzero.
* If the function fails, the return value is zero. To get extended error information, call GetLastError.
*/
return_value = SetCommTimeouts(this->native_port, &timeouts);
if (not return_value)
{
PLOG_ERROR << "Error SetCommTimeouts : " << GetLastErrorAsString();
return false;
}
}
#else //For Linux termios
#endif // _WIN64
return true;
}
catch (const std::exception& ex)
{
PLOG_ERROR << ex.what();
return false;
}
}
void SerialPort::read_handler(const boost::system::error_code& error, std::size_t bytes_transferred)
{
this->read_async(); // I realized I was calling read_async before reading data
bool receive_complete{ false };
try
{
if (error not_eq boost::system::errc::success) //Error in serial port read
{
PLOG_ERROR << error.to_string();
this->async_signal.emit(this->port_number, SerialPortEvents::read_error, error.to_string());
return;
}
if (this->line_mode)
{
std::string temporary_recieve_data;
std::transform(this->read_buffer.begin(), this->read_buffer.begin() + bytes_transferred, //Data is added to temporary buffer
std::back_inserter(temporary_recieve_data), [](std::byte character) {
return static_cast<char>(character);
}
);
boost::algorithm::trim(temporary_recieve_data); // Trim handles space character, tab, carriage return, newline, vertical tab and form feed
//Data is further processed based on the Process logic
receive_complete = true;
}
else // Bulk-Data. Just append data to end of received_data string buffer.
// Wait for timeout to trigger recevive_complete
{
//Test Function
std::transform(this->read_buffer.begin(), this->read_buffer.begin() + bytes_transferred,
std::back_inserter(this->received_data), [](std::byte character) {
return static_cast<char>(character);
}
);
this->async_signal.emit(this->port_number, SerialPortEvents::read_data, this->received_data); //Data has been recieved send to server via MQTT
}
}
catch (const std::exception& ex)
{
PLOG_ERROR << ex.what();
this->async_signal.emit(this->port_number, SerialPortEvents::read_error, ex.what());
}
}
</code></pre>
|
[
{
"answer_id": 74661374,
"author": "sehe",
"author_id": 85371,
"author_profile": "https://Stackoverflow.com/users/85371",
"pm_score": 1,
"selected": false,
"text": "read_timeout #include <boost/asio.hpp>\n#include <boost/asio/serial_port.hpp>\n#include <boost/bind/bind.hpp>\n#include <iomanip>\n#include <iostream>\nnamespace asio = boost::asio;\n\nstatic inline std::ostream PLOG_ERROR(std::cerr.rdbuf());\n\nstruct SerialPort {\n static constexpr uint32_t ignore_timeout = -1;\n\n SerialPort(asio::any_io_executor ex, std::string dev) : port(ex, dev) {}\n\n bool read_async(uint32_t timeout_override) {\n try {\n read_buffer.fill({}); // Clear Buffer\n\n if (timeout_override not_eq SerialPort::ignore_timeout) {\n read_timeout = timeout_override;\n }\n using namespace asio::placeholders;\n\n port.async_read_some(\n asio::buffer(read_buffer),\n bind(&SerialPort::read_handler, this, error, bytes_transferred));\n\n return true;\n } catch (std::exception const& ex) {\n PLOG_ERROR << ex.what() << std::endl;\n return false;\n }\n }\n\n private:\n void read_handler(boost::system::error_code ec, size_t bytes_transferred) {\n std::cerr << \"received \" << bytes_transferred << \" bytes (\" << ec.message() << \")\"\n << std::endl;\n\n auto fmt = std::cerr.flags();\n for (auto b : read_buffer) {\n if (!bytes_transferred--)\n break;\n std::cerr << \" \" << std::hex << std::showbase << std::setfill('0')\n << std::setw(4) << static_cast<unsigned>(b);\n }\n std::cerr.flags(fmt);\n std::cerr << std::endl;\n\n if (!ec)\n read_async(ignore_timeout);\n }\n\n uint32_t read_timeout = 10;\n std::array<std::byte, 256> read_buffer{};\n asio::serial_port port;\n};\n\nint main(int argc, char** argv) {\n asio::io_context ioc;\n\n SerialPort sp(make_strand(ioc), argc > 1 ? argv[1] : \"/dev/ttyS0\");\n sp.read_async(SerialPort::ignore_timeout);\n\n ioc.run();\n // ioc.run_for(std::chrono::seconds(1));\n}\n socat socat -d -d pty,raw,echo=0 pty,raw,echo=0\n"
},
{
"answer_id": 74662699,
"author": "Dark Sorrow",
"author_id": 6319901,
"author_profile": "https://Stackoverflow.com/users/6319901",
"pm_score": 0,
"selected": false,
"text": "SerialPort::read_handler this->read_async() this->read_async()"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6319901/"
] |
74,659,686
|
<p>Some Python libraries are listed under one name in pip, but imported under a different name in the interpreter.</p>
<p>pycroptodome is a good example. In pip list, you see "pycryptodome". In a Python program, you have to call "import Crypto". "import pycryptodome" gives an error that the module doesn't exist.</p>
<p>Some libraries I've imported are giving me "module not found" errors. I want to see if they're imported under a different name from what appears in pip. Where can I find that data?</p>
<p>For reference, "pip show " and "pip inspect " don't seem to have this information.</p>
|
[
{
"answer_id": 74659825,
"author": "D P",
"author_id": 20622893,
"author_profile": "https://Stackoverflow.com/users/20622893",
"pm_score": 0,
"selected": false,
"text": "pydoc modules \n"
},
{
"answer_id": 74660392,
"author": "Masoud Gheisari",
"author_id": 15863196,
"author_profile": "https://Stackoverflow.com/users/15863196",
"pm_score": 0,
"selected": false,
"text": "Location pip show pycryptodome dist-info pycryptodome-3.16.0.dist-info top_level.txt"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1839555/"
] |
74,659,693
|
<p>We are trying to create a new Excel file with nested data using Python code. Here is the code for reference:</p>
<pre><code>`import glob
import pandas as pd
import re
import openpyxl
dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name ="Sheet1")
line_numbers = [4, 7]
print("Heey, we read")
dp_max = dp.groupby(['Subject', 'Date & Time', 'Trees Again', 'DifficultyLevel', 'Block', 'UpdatevsNonupdate', 'responsetimerecodeforACC', 'Nonupdate', 'Update'], sort=False).max()
dp_max = dp_max[["Total Training Time"]]
print("This worked. Good start. Yaaaay.s")
dp_max.to_excel('unpredictable_grouped_max_heregoesnothing.xlsx', index=True)
print("This worked. Yaaaay.s")
dp['Signal_Detection2'] = dp.loc[:, 'Signal_Detection']
dp_count = dp.groupby(['Subject', 'Signal_Detection'], sort=False).count()[["Signal_Detection2"]]
dp_count.to_excel('unpredictable_grouped_signal_count_heregoesnothing.xlsx', index=True)
Unexpected exception formatting exception. Falling back to standard exception
Output exceeds the size limit. Open the full output data in a text editor
Traceback (most recent call last):
File "C:\Users\mxa210135\AppData\Roaming\Python\Python38\site-packages\IPython\core\interactiveshell.py", line 3433, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-9-853a8bf5b14e>", line 5, in <module>
dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name ="Sheet1")`
</code></pre>
<p>The code above is what we had tried and it had worked previously. We only added the 'Trees Again' variable and 'UpdatevsNonupdate', 'responsetimerecodeforACC', 'Nonupdate', and lastly 'Update'.
Please let me know if more information is needed and I will happily provide it.</p>
<p>We tried splitting the large file in half and run the code on both, but it did not work and gave us the same error message.</p>
|
[
{
"answer_id": 74659825,
"author": "D P",
"author_id": 20622893,
"author_profile": "https://Stackoverflow.com/users/20622893",
"pm_score": 0,
"selected": false,
"text": "pydoc modules \n"
},
{
"answer_id": 74660392,
"author": "Masoud Gheisari",
"author_id": 15863196,
"author_profile": "https://Stackoverflow.com/users/15863196",
"pm_score": 0,
"selected": false,
"text": "Location pip show pycryptodome dist-info pycryptodome-3.16.0.dist-info top_level.txt"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668962/"
] |
74,659,714
|
<p>So I found tutorial about work with GUI in python tkinter<br />
then I try to learn it from w3school, I copied the sample code:</p>
<pre><code>from tkinter import *
from tkinter .ttk import *
root = Tk()
label = Label(root, text="Hello world Tkinket GUI Example ")
label.pack()
root.mainloop()
</code></pre>
<p>So, I google how to install tkinter on ubuntu.
I used:</p>
<pre><code>$ sudo apt-get install python-tk python3-tk tk-dev
$ sudo apt-get install python-tk
$ pip install tk
</code></pre>
<p>It's seem it was successfully but I was wrong..</p>
<p>I get this <a href="https://i.stack.imgur.com/GotdE.png" rel="nofollow noreferrer">error</a></p>
<p>Ubuntu 22.04.1 LTS</p>
|
[
{
"answer_id": 74659803,
"author": "Cracko298",
"author_id": 20669026,
"author_profile": "https://Stackoverflow.com/users/20669026",
"pm_score": 0,
"selected": false,
"text": "from tkinter import * from tkinter .ttk import *"
},
{
"answer_id": 74659804,
"author": "Ryan van Vuure",
"author_id": 15435130,
"author_profile": "https://Stackoverflow.com/users/15435130",
"pm_score": 0,
"selected": false,
"text": "from tkinter .ttk import *"
},
{
"answer_id": 74659823,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": true,
"text": "import tkinter as tk # 'as tk' isn't required, but it's common practice\nfrom tkinter import ttk # though you aren't using any ttk widgets at the moment...\n from tkinter import *\nfrom tkinter.ttk import *\n\nroot = Tk()\nlabel = Label(root, text='Hello!')\n Label import tkinter as tk\nfrom tkinter import ttk\n\nroot = tk.Tk()\nlabel = ttk.Label(root)\n label"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16785674/"
] |
74,659,719
|
<p>I would like to return all ingress resources that do not contain a specific annotation. Using the following command returns an error:</p>
<pre><code>kubectl get ingress --all-namespaces -o=jsonpath='{.items[?(!(@.metadata.annotations.kubernetes\.io/ingress\.class))].metadata.name}'
</code></pre>
<p>error:</p>
<pre><code>error parsing jsonpath {.items[?(!(@.metadata.annotations.kubernetes\.io/ingress\.class))].metadata.name}, unclosed array expect ]
</code></pre>
|
[
{
"answer_id": 74659775,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 1,
"selected": false,
"text": "kubectl get ingress --all-namespaces -o=jsonpath='{.items[?(!(@.metadata.annotations[\"kubernetes.io/ingress.class\"]))].metadata.name}'\n"
},
{
"answer_id": 74669356,
"author": "Akshay",
"author_id": 3881787,
"author_profile": "https://Stackoverflow.com/users/3881787",
"pm_score": 0,
"selected": false,
"text": "kubectl get ingress --all-namespaces -o=jsonpath='{.items[?(!(@.metadata.annotations.kubernetes.io/ingress.class))].metadata.name}'\n kubectl get ingress --all-namespaces --field-selector metadata.annotations.kubernetes.io/ingress.class!=\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10709519/"
] |
74,659,733
|
<p>I'm developing a game in console c#, that you can read maps created in files. For doing so, i'm reading a file and storing that into a string. Then i'm reading each character individually and depending on the character, I need to create an object using the factory pattern. I don't know how to do it without coupling the code.</p>
<p>I have the main entity Object. From object inherit different objects, like: Box, Wall, Grass, Tree. Each one is represented by a character in the file and translated to another character in the game, (B)ox = '■', (W)all = '▓', (G)rass = 'v', (T)ree = '↑'. The way I done that is by placing a property char "Model" in the Object with getter only, and in each object I override the getter with the corresponding model.</p>
<p>Now, while I'm reading the file map mentioned before I need to tell the factory which object to build depending on the character read. I dont want to make a big switch(character) because it will be coupled, because for each object I want to add I will have to add a new case in the switch. Is any better way of doing so?</p>
<p>Example of class Box:</p>
<pre><code>public class Box : Object
{
public override char Model { get { return '■'; } }
public Box()
{
this.Name = "box";
this.MapCharacter = 'B';
this.Colors = new List<ConsoleColor>() { ConsoleColor.DarkYellow };
this.Destructible = true;
this.Passable = false;
this.SeeThrough = false;
this.Health = 200;
}
public override void OnDestroy()
{
}
}
</code></pre>
<p>Example code of Factory:</p>
<pre><code>public class ObjectFactory : IObjectFactory
{
public Object GetObject(char mapCharacter)
{
switch (mapCharacter)
{
case 'B':
return new Box();
case 'T':
return new Tree();
case 'W':
return new Wall();
case 'G':
return new Grass();
default:
return null;
}
}
}
</code></pre>
<p>My idea was using Reflection get the Model of each class inherted from Object and somehow return that class, but that seems poor code</p>
|
[
{
"answer_id": 74659973,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": false,
"text": "switch public class ObjectFactory \n{\n private static readonly Dictionary<char, Func<MyObject>> _objectFactory = new Dictionary<char, Func<MyObject>>()\n {\n { 'B', () => new Box() },\n // ...\n };\n\n public Object GetObject(char mapCharacter)\n {\n if(_objectFactory.TryGetValue(mapCharacter, out var factory))\n {\n return factory();\n }\n\n return null;\n }\n}\n"
},
{
"answer_id": 74675839,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 0,
"selected": false,
"text": "public class InstanceHelper\n{\n public static object Get(string fullyQualifiedName)\n {\n Type t = Type.GetType(fullyQualifiedName);\n return Activator.CreateInstance(t);\n }\n}\n Box box = InstanceHelper.Get(\"Box\") as Box;\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13483046/"
] |
74,659,736
|
<p>I need to give this divider but I don't know how to coding it .</p>
<p><a href="https://i.stack.imgur.com/GzkmV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GzkmV.png" alt="enter image description here" /></a></p>
<p>I tried but I don't know how to give thin to thick .</p>
|
[
{
"answer_id": 74659973,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": false,
"text": "switch public class ObjectFactory \n{\n private static readonly Dictionary<char, Func<MyObject>> _objectFactory = new Dictionary<char, Func<MyObject>>()\n {\n { 'B', () => new Box() },\n // ...\n };\n\n public Object GetObject(char mapCharacter)\n {\n if(_objectFactory.TryGetValue(mapCharacter, out var factory))\n {\n return factory();\n }\n\n return null;\n }\n}\n"
},
{
"answer_id": 74675839,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 0,
"selected": false,
"text": "public class InstanceHelper\n{\n public static object Get(string fullyQualifiedName)\n {\n Type t = Type.GetType(fullyQualifiedName);\n return Activator.CreateInstance(t);\n }\n}\n Box box = InstanceHelper.Get(\"Box\") as Box;\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376640/"
] |
74,659,756
|
<p>I have a data frame with the values of precipitations day per day.
I would like to do a sort of resample, so instead of day per day the data is collected year per year and every year has a column that contains the number of times it rained more than a certain value.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Precipitation</th>
</tr>
</thead>
<tbody>
<tr>
<td>2000-01-01</td>
<td>1</td>
</tr>
<tr>
<td>2000-01-03</td>
<td>6</td>
</tr>
<tr>
<td>2000-01-03</td>
<td>5</td>
</tr>
<tr>
<td>2001-01-01</td>
<td>3</td>
</tr>
<tr>
<td>2001-01-02</td>
<td>1</td>
</tr>
<tr>
<td>2001-01-03</td>
<td>0</td>
</tr>
<tr>
<td>2002-01-01</td>
<td>10</td>
</tr>
<tr>
<td>2002-01-02</td>
<td>8</td>
</tr>
<tr>
<td>2002-01-03</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p>what I want is to count every year how many times Precipitation > 2</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>2000</td>
<td>2</td>
</tr>
<tr>
<td>2001</td>
<td>1</td>
</tr>
<tr>
<td>2002</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>I tried using <code>resample()</code> but with no results</p>
|
[
{
"answer_id": 74659973,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": false,
"text": "switch public class ObjectFactory \n{\n private static readonly Dictionary<char, Func<MyObject>> _objectFactory = new Dictionary<char, Func<MyObject>>()\n {\n { 'B', () => new Box() },\n // ...\n };\n\n public Object GetObject(char mapCharacter)\n {\n if(_objectFactory.TryGetValue(mapCharacter, out var factory))\n {\n return factory();\n }\n\n return null;\n }\n}\n"
},
{
"answer_id": 74675839,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 0,
"selected": false,
"text": "public class InstanceHelper\n{\n public static object Get(string fullyQualifiedName)\n {\n Type t = Type.GetType(fullyQualifiedName);\n return Activator.CreateInstance(t);\n }\n}\n Box box = InstanceHelper.Get(\"Box\") as Box;\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668924/"
] |
74,659,764
|
<p>I'm trying to get a interpolated contour surface with triangulation from matplotlib. My data looks like a curve and I can't get rid of the data below the curve. I would like to have the outside datapoints as boundaries.</p>
<p>I got the code from <a href="https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/irregulardatagrid.html#sphx-glr-gallery-images-contours-and-fields-irregulardatagrid-py" rel="nofollow noreferrer">this tutorial</a></p>
<pre><code>import matplotlib.tri as tri
fig, (ax1, ax2) = plt.subplots(nrows=2)
xi = np.linspace(-10,150,2000)
yi = np.linspace(-10,60,2000)
triang = tri.Triangulation(x_after, y_after)
interpolator = tri.LinearTriInterpolator(triang, strain_after)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)
ax1.triplot(triang, 'ro-', lw=5)
ax1.contour(xi, yi, zi, levels=30, linewidths=0.5, colors='k')
cntr1 = ax1.contourf(xi, yi, zi, levels=30, cmap="jet")
fig.colorbar(cntr1, ax=ax1)
ax1.plot(x_after, y_after, 'ko', ms=3)
ax2.tricontour(x_after, y_after, strain_after, levels=30, linewidths=0.5, colors='k')
cntr2 = ax2.tricontourf(x_after, y_after, strain_after, levels=30, cmap="jet")
fig.colorbar(cntr2, ax=ax2)
ax2.plot(x_after, y_after, 'ko', ms=3)
plt.subplots_adjust(hspace=0.5)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/DCZK0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DCZK0.png" alt="enter image description here" /></a></p>
<p>I found the option to mask the data with this code, but I can't figure out how to define the mask to get what I want</p>
<pre><code>triang.set_mask()
</code></pre>
<p>These are the values for the inner curve:</p>
<pre><code> x_after y_after z_after strain_after
39 117.2757 8.7586 0.1904 7.164
40 119.9474 7.152 0.1862 6.6456
37 111.8319 12.0568 0.1671 6.273
38 114.5314 10.4186 0.1651 5.7309
41 122.7482 5.4811 0.1617 9.1563
36 108.8823 13.4417 0.1421 8.8683
42 125.5035 3.8309 0.141 9.7385
33 99.8064 17.6315 0.1357 9.8613
32 96.8869 18.6449 0.1197 4.4147
35 105.8846 14.6086 0.1079 7.7055
28 84.2221 22.0191 0.1076 6.2098
26 77.8689 23.158 0.1067 7.5833
29 87.354 21.2974 0.1044 11.4365
27 81.0778 22.6443 0.1019 8.3794
24 71.4004 23.7749 0.0968 8.6207
34 102.8772 15.9558 0.0959 18.2025
23 68.2124 23.962 0.0939 7.9201
25 74.6905 23.4465 0.0901 9.0361
30 90.5282 20.398 0.0864 14.1051
31 93.802 19.335 0.0794 10.4563
43 128.3489 2.1002 0.0689 9.0292
22 65.0282 24.1107 0.0654 7.99
21 61.7857 24.0129 0.0543 8.2589
20 58.5831 23.9527 0.0407 9.0087
0 -0.0498 -0.5159 0.0308 7.1073
19 55.3115 23.7794 0.0251 9.6441
5 12.5674 9.3369 0.0203 7.2051
2 4.8147 3.6074 0.0191 8.0103
1 2.363 1.5329 0.0184 7.8285
18 52.0701 23.526 0.016 8.0149
3 7.4067 5.5988 0.0111 8.9994
7 18.2495 12.5836 0.0098 9.771
9 23.9992 15.4145 0.0098 6.7995
16 45.5954 22.5274 0.0098 12.9428
4 9.9776 7.5563 0.0093 6.9804
17 48.9177 23.0669 0.0084 9.3782
13 35.9812 20.0588 0.0066 9.6005
6 15.3578 11.0027 0.0062 9.7801
15 42.2909 21.8663 0.0052 12.0288
11 29.816 17.8723 0.0049 8.9085
8 21.1241 14.0893 0.0032 6.5716
10 26.8691 16.7093 0.0014 6.9672
44 131.1371 0.4155 0.0 11.9578
14 39.0687 20.991 -0.0008 9.9907
12 32.9645 18.9796 -0.0102 9.3389
45 134.083 -1.3928 -0.0616 15.29
</code></pre>
|
[
{
"answer_id": 74659973,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": false,
"text": "switch public class ObjectFactory \n{\n private static readonly Dictionary<char, Func<MyObject>> _objectFactory = new Dictionary<char, Func<MyObject>>()\n {\n { 'B', () => new Box() },\n // ...\n };\n\n public Object GetObject(char mapCharacter)\n {\n if(_objectFactory.TryGetValue(mapCharacter, out var factory))\n {\n return factory();\n }\n\n return null;\n }\n}\n"
},
{
"answer_id": 74675839,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 0,
"selected": false,
"text": "public class InstanceHelper\n{\n public static object Get(string fullyQualifiedName)\n {\n Type t = Type.GetType(fullyQualifiedName);\n return Activator.CreateInstance(t);\n }\n}\n Box box = InstanceHelper.Get(\"Box\") as Box;\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18235748/"
] |
74,659,786
|
<p>I'm new to Excel VBA, and after quite some time attempting to solve my issue, I am unable to create a working solution. The attached image is a mock up of an actual table I'm working with. I would like to:</p>
<p><a href="https://i.stack.imgur.com/JrTLS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JrTLS.png" alt="enter image description here" /></a></p>
<p><strong>#1</strong> Define a date in the VBA to search for in the blue row (e.g. 05/12/2022)</p>
<p><strong>#2</strong> Once found, find all values of both 'Apple' and 'Pear' in that yellow column (Apple = 4 times, Pear = 1 time)</p>
<p><strong>#3</strong> Look at the Green column, and store the names for all matches for 'Apple' in one array (later to be used in a string), and all matches for 'Pear' in another array</p>
<p><strong>#4</strong> Input a comma delimited return of both arrays into a cell within the spreadsheet</p>
<p>Step #1 was completed successfully using the following code:</p>
<pre><code>Public Sub MyVBA()
Dim c As Range
Dim colNum As Integer
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Workbooks("MyOtherWorkbook.xlsx")
Set wks = wkb.Worksheets("SheetInWorkbook")
For Each c In wks.Range("1:1")
If c.Value = "05/12/2022" Then
colNum = c.Column
End If
Next c
End Sub
</code></pre>
<p>Step #2 attempt:</p>
<pre><code> For Each c In wks.Columns(colNum)
If c.Value = "Apple" Then
MsgBox "Apple is " & c.Address
End If
Next c
</code></pre>
<p>This is one of various attempts I've made at Step #2, but each time it produces errors. Advice on how to go forward with Step #2 and #3 would be appreciated.</p>
|
[
{
"answer_id": 74660278,
"author": "Lewis Morris",
"author_id": 3348264,
"author_profile": "https://Stackoverflow.com/users/3348264",
"pm_score": 0,
"selected": false,
"text": "output Public dataWs As Worksheet\nPublic outputWs As Worksheet\nPublic searchWs As Worksheet\n\n\nFunction create_date(string_date)\n 'create a date date not a string date\n Dim day, month, year As String\n Dim dte As Date\n \n day = Left(string_date, 2)\n month = Mid(string_date, 4, 2)\n year = Right(string_date, 2)\n dte = DateSerial(Int(year), Int(month), Int(day))\n create_date = dte\n \nEnd Function\n\nFunction clear_outout()\n\n 'clear output worksheet\n\n outputWs.Range(\"a1:z99999\").Clear\n\n\nEnd Function\n\nFunction addData(name, object)\n\n\n Dim x, lr As Integer\n \n lr = outputWs.Cells(Rows.Count, 1).End(xlUp).Row\n \n 'add columns headers if not there\n If lr = 1 Then\n outputWs.Cells(1, 1) = \"NAME\"\n outputWs.Cells(1, 2) = \"OBJECT\"\n outputWs.Cells(1, 3) = \"TIMES\"\n End If\n \n For x = 2 To lr + 1\n If x = lr + 1 Then\n 'if not in list add name object\n outputWs.Cells(x, 1) = name\n outputWs.Cells(x, 2) = object\n outputWs.Cells(x, 3) = 1\n Exit For\n ElseIf outputWs.Cells(x, 1) = name And outputWs.Cells(x, 2) = object Then\n ' if in list increment count\n outputWs.Cells(x, 3) = outputWs.Cells(x, 3) + 1\n Exit For\n End If\n Next x\n\nEnd Function\n\nFunction check_search_list(search_val)\n\n ' checks to see if input value is a match with one listed in range \n\n Dim search_lr As Integer\n \n 'this is the search last row\n search_lr = searchWs.Cells(Rows.Count, 1).End(xlUp).Row\n 'loop each search val\n For x = 2 To search_lr\n If searchWs.Cells(x, 1) = search_val Then\n check_search_list = True\n End If\n Next x\n \nEnd Function\n\n\nSub check_data()\n ''''\n ''' Run the thing\n ''''\n\n 'set the worksheets\n Set dataWs = Worksheets(\"data\")\n Set outputWs = Worksheets(\"output\")\n Set searchWs = Worksheets(\"search\")\n \n Dim x, y, z, lr, lc As Integer\n Dim searchDate As String\n Dim found_column As Boolean\n \n \n 'clear output sheet\n clear_outout\n 'this gets the pos of the last filled column to the left\n lc = dataWs.Cells(1, Columns.Count).End(xlToLeft).Column\n 'get last row\n lr = dataWs.Cells(Rows.Count, 1).End(xlUp).Row\n 'get the date from the user\n searchDate = InputBox(\"Whats the date in format dd/mm/yyyy\")\n 'create flag for date found\n found_column = False\n 'loop columns and look for dates (as proper dates and not strings)\n For y = 2 To lc\n 'if found then add all columns - this compares the date object, not strin g\n If create_date(dataWs.Cells(1, y)) = create_date(searchDate) Then\n found_column = True\n 'loop eaach row\n For x = 2 To lr\n If check_search_list(dataWs.Cells(x, y)) Then\n ' add the data if search value found\n addData dataWs.Cells(x, 1), dataWs.Cells(x, y)\n End If\n Next x\n 'end loop as column already found\n Exit For\n End If\n Next y\n \n 'open data if found else show message\n If found_column Then\n outputWs.Activate\n Else\n MsgBox \"Date not found\", vbCritical\n End If\n \nEnd Sub\n"
},
{
"answer_id": 74660525,
"author": "Toddleson",
"author_id": 14608750,
"author_profile": "https://Stackoverflow.com/users/14608750",
"pm_score": 0,
"selected": false,
"text": "Public Sub MyVBA()\n\n Dim c As Range\n Dim colNum As Long\n Dim wkb As Excel.Workbook\n Dim wks As Excel.Worksheet\n\n Set wkb = Excel.Workbooks(\"MyOtherWorkbook.xlsx\")\n Set wks = wkb.Worksheets(\"SheetInWorkbook\")\n \n 'Get a Date as input from the user\n Dim UserDate As Date: UserDate = GetUserDate()\n 'Exit if the user has declined to input\n If UserDate = 0 Then Exit Sub\n \n 'Search for the last filled row and column\n 'This can be used to trim the loops so we aren't iterating through a million empty cells\n Dim LastRow As Long\n LastRow = wks.Columns(1).Rows(wks.Rows.Count).End(xlUp).Row\n \n Dim LastColumn As Long\n LastColumn = wks.Rows(1).Columns(wks.Columns.Count).End(xlToLeft).Column\n \n 'For each cell in Row 1\n For Each c In wks.Range(\"1:1\").Resize(, LastColumn).Cells\n 'if the cell contains a date & the date matches the user input\n If IsDate(c.Value) Then\n If CDate(c.Value) = UserDate Then\n colNum = c.Column\n 'if the column is found, stop searching\n Exit For\n End If\n End If\n Next c\n 'Exit if Column not found\n If colNum = 0 Then Exit Sub\n \n 'KeyRanges is a dictionary, this is an object that holds Key & Item pairs\n 'There is an entry in the dictionary for each keyword\n 'The entry's Key is the Keyword (Apple or Pear), and the item is a Collection of worksheet ranges where that keyword was found\n Dim KeyRanges As Object\n Set KeyRanges = CreateObject(\"Scripting.Dictionary\")\n \n 'List of KeyWords\n Dim KeyWords() As String: KeyWords = Split(\"Apple,Pear\", \",\")\n \n 'Adding an entry to the dictionary for each keyword\n Dim KeyWord As Variant\n For Each KeyWord In KeyWords\n KeyRanges.Add KeyWord, New Collection\n Next\n \n 'search the column for matches\n For Each c In wks.Columns(colNum).Resize(LastRow).Cells\n 'compare the cell value to each keyword\n For Each KeyWord In KeyWords\n If c.Value = KeyWord Then\n 'If the cell value matches one of the keywords\n 'Go into the dictionary entry for that keyword\n 'and save the cell from this row, in column A, into the collection\n KeyRanges(KeyWord).Add c.EntireRow.Cells(1)\n End If\n Next\n Next c\n \n 'From your example for 05/12/2022\n 'KeyRanges now contains 2 entries\n 'KeyRanges(\"Apple\") contains a Collection\n 'The Collection contains 4 items\n 'Range(\"A2\")\n 'Range(\"A5\")\n 'Range(\"A7\")\n 'Range(\"A8\")\n 'KeyRanges(\"Pear\") contains a Collection\n 'The Collection contains 1 item\n 'Range(\"A4\")\n \n 'Concatenate into CSV\n 'CSVs is an array to contain the CSV for each KeyWord\n Dim CSVs() As String\n ReDim CSVs(UBound(KeyWords))\n \n 'For each KeyWord\n Dim i As Long\n For i = 0 To UBound(KeyWords)\n 'Take the collection from each entry in KeyRanges\n 'Give it to a function which can turn collections into CSVs\n CSVs(i) = JoinCollection(KeyRanges(KeyWords(i)))\n Next\n \n 'Join all the CSVs into a single CSV & Output to Worksheet\n Range(\"A1\").Value = Join(CSVs, \",\")\n \nEnd Sub\nFunction GetUserDate() As Date\n 'Get Date From User\n Dim UserInput As String\n Do\n UserInput = Application.InputBox(Prompt:=\"Date:\", Default:=Date, Type:=2)\n If UserInput = \"\" Then\n 'User declined to input\n Exit Function\n ElseIf Not IsDate(UserInput) Then\n 'User input not valid\n UserInput = \"\"\n MsgBox \"Please enter a valid date.\", vbOKOnly, \"Error\"\n End If\n Loop While UserInput = \"\"\n \n GetUserDate = CDate(UserInput)\nEnd Function\nFunction JoinCollection(Col As Collection, Optional Delimiter As String = \",\") As String\n If Col.Count = 0 Then Exit Function\n Dim ReturnString As String\n ReturnString = Col(1)\n If Col.Count > 1 Then\n Dim i As Long\n For i = 2 To Col.Count\n ReturnString = ReturnString & Delimiter & Col(i)\n Next\n End If\n JoinCollection = ReturnString\nEnd Function\n KeyWords = Split(\"Apple,Pear\", \",\") KeyWords"
},
{
"answer_id": 74661983,
"author": "Tim Williams",
"author_id": 478884,
"author_profile": "https://Stackoverflow.com/users/478884",
"pm_score": 1,
"selected": false,
"text": "FILTER() Sub Tester()\n Dim ws As Worksheet, m, dt As Date, rng As Range, res\n Dim dict As Object, el, rngNames As Range, f\n \n Set dict = CreateObject(\"scripting.dictionary\")\n dict.CompareMode = 1 'case-insensitive\n \n dt = DateValue(\"12/5/2022\") 'date to be searched on\n \n Set ws = ActiveSheet\n \n m = Application.Match(CLng(dt), ws.Rows(1), 0)\n If Not IsError(m) Then 'got a match\n Set rng = ws.Range(ws.Cells(2, m), ws.Cells(Rows.Count, m).End(xlUp)) 'fruits for this date\n Set rngNames = rng.EntireRow.Columns(\"A\") 'names in ColA\n f = \"FILTER(\" & rngNames.Address() & \",\" & rng.Address() & \"=\"\"<v>\"\")\" 'prep the formula\n For Each el In Array(\"Apple\", \"Pear\", \"Melon\") 'loop over fruits to be counted\n res = ws.Evaluate(Replace(f, \"<v>\", el))\n dict(el) = res\n Next el\n DumpDict dict 'show results\n Else\n MsgBox \"Date not found\"\n End If\nEnd Sub\n\n'display dictionary contents to the Immediate pane\nSub DumpDict(dict As Object)\n Dim k, el, v, i\n For Each k In dict\n Debug.Print k\n v = dict(k)\n If IsError(v) Then\n Debug.Print , \"No names\"\n Else\n For i = LBound(v, 1) To UBound(v, 1)\n Debug.Print , v(i, 1)\n Next i\n End If\n Next k\nEnd Sub\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668968/"
] |
74,659,794
|
<p>I know that if you have something like this...</p>
<pre><code>const [state, setState] = useState('some state');
</code></pre>
<p>and you are getting the warning for setState is never used, you should simply not useState, and instead, a normal variable.</p>
<p>My question is, what if this is useContext instead of useState as shown below? I have this structure for other components but some components do not need to setState for this context. How can I handle this warning? Is eslint my only option here?</p>
<pre><code>const [state, setState] = useContext(myContext);
</code></pre>
<p>I have another component that uses the setState but not the state. How would I handle this?</p>
|
[
{
"answer_id": 74659813,
"author": "Xiduzo",
"author_id": 4655177,
"author_profile": "https://Stackoverflow.com/users/4655177",
"pm_score": 3,
"selected": true,
"text": "const [state] = useContext(myContext);\n useContext useState const useState = () => [\"hi\", \"mom\"];\n\nconst [position_0, position_1] = useState();\n\n\nconsole.log(postition_0) // \"hi\"\nconsole.log(postition_1) // \"mom\"\n\n const [, position_1] = useState();\n object array const context = () => {\n ...your context here...\n\n return {\n state,\n setState,\n ...even more...\n }\n)\n const { state } = useContext(context); // just state\nconst { setState } = useContext(context); // just setState\nconst { state, setState } = useContext(context); // both\n"
},
{
"answer_id": 74659827,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "const myContext = React.createContext();\n\nfunction MyComponent() {\n const state = useContext(myContext);\n\n return (\n <div>\n {/* Use the context state in your component. */}\n <p>{state.someValue}</p>\n </div>\n );\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167364/"
] |
74,659,809
|
<p>I have 2 datasets. One contains a column of companies name, and another contains a column of headlines of news. So the aim I want to achieve is to find all the news whose headline contains one company in the other datasets.<a href="https://i.stack.imgur.com/PQs0d.png" rel="nofollow noreferrer">Basically the two datasets are like this, and I wanna select the news with specific company names</a></p>
<p>I have tried to use for loop to achieve my goals, but I think it takes too much time and I think pandas or some other libraries can do this in an easier way.</p>
<p>I am a starter in python.</p>
|
[
{
"answer_id": 74659813,
"author": "Xiduzo",
"author_id": 4655177,
"author_profile": "https://Stackoverflow.com/users/4655177",
"pm_score": 3,
"selected": true,
"text": "const [state] = useContext(myContext);\n useContext useState const useState = () => [\"hi\", \"mom\"];\n\nconst [position_0, position_1] = useState();\n\n\nconsole.log(postition_0) // \"hi\"\nconsole.log(postition_1) // \"mom\"\n\n const [, position_1] = useState();\n object array const context = () => {\n ...your context here...\n\n return {\n state,\n setState,\n ...even more...\n }\n)\n const { state } = useContext(context); // just state\nconst { setState } = useContext(context); // just setState\nconst { state, setState } = useContext(context); // both\n"
},
{
"answer_id": 74659827,
"author": "Muhammad Salman",
"author_id": 15715337,
"author_profile": "https://Stackoverflow.com/users/15715337",
"pm_score": 0,
"selected": false,
"text": "const myContext = React.createContext();\n\nfunction MyComponent() {\n const state = useContext(myContext);\n\n return (\n <div>\n {/* Use the context state in your component. */}\n <p>{state.someValue}</p>\n </div>\n );\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20135786/"
] |
74,659,811
|
<p>I'm trying to add exploded columns to a dataframe:</p>
<pre><code>from pyspark.sql.functions import *
from pyspark.sql.types import *
# Convenience function for turning JSON strings into DataFrames.
def jsonToDataFrame(json, schema=None):
# SparkSessions are available with Spark 2.0+
reader = spark.read
if schema:
reader.schema(schema)
return reader.json(sc.parallelize([json]))
schema = StructType().add("a", MapType(StringType(), IntegerType()))
events = jsonToDataFrame("""
{
"a": {
"b": 1,
"c": 2
}
}
""", schema)
display(
events.withColumn("a", explode("a").alias("x", "y"))
)
</code></pre>
<p>However, I'm hitting the following error:</p>
<pre><code>AnalysisException: The number of aliases supplied in the AS clause does not match the number of columns output by the UDTF expected 2 aliases but got a
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 74659812,
"author": "Chris Snow",
"author_id": 1033422,
"author_profile": "https://Stackoverflow.com/users/1033422",
"pm_score": 0,
"selected": false,
"text": "display(\n events.select(explode(\"a\").alias(\"x\", \"y\"), *[c for c in events.columns])\n)\n select explode(\"a\").alias(\"x\", \"y\")\n *[c for c in events.columns]\n * Parameters\ncolsstr, Column, or list\ncolumn names (string) or expressions (Column). If one of the column names is ‘*’, that column is expanded to include all columns in the current DataFrame.\n display(\n events.select(\"*\", explode(\"a\").alias(\"x\", \"y\"))\n)\n"
},
{
"answer_id": 74665517,
"author": "Raphael Mansuy",
"author_id": 8877703,
"author_profile": "https://Stackoverflow.com/users/8877703",
"pm_score": 1,
"selected": false,
"text": "events.withColumn(\"a\", explode(\"a\").alias(\"x\", \"y\"))\n events.withColumn(\"a\", explode(\"a\").alias(col(\"x\"), col(\"y\")))\n"
},
{
"answer_id": 74665543,
"author": "sametcodes",
"author_id": 8574166,
"author_profile": "https://Stackoverflow.com/users/8574166",
"pm_score": 1,
"selected": false,
"text": "select from pyspark.sql.functions import *\nfrom pyspark.sql.types import *\n\n# Convenience function for turning JSON strings into DataFrames.\ndef jsonToDataFrame(json, schema=None):\n # SparkSessions are available with Spark 2.0+\n reader = spark.read\n if schema:\n reader.schema(schema)\n return reader.json(sc.parallelize([json]))\n\nschema = StructType().add(\"a\", MapType(StringType(), IntegerType()))\n\nevents = jsonToDataFrame(\"\"\"\n{\n \"a\": {\n \"b\": 1,\n \"c\": 2\n }\n}\n\"\"\", schema)\n\ndisplay(\n events\n .withColumn(\"a\", explode(\"a\").alias(\"x\", \"y\"))\n .select(\"*\", \"x\", \"y\")\n)\n a x y"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] |
74,659,818
|
<p>Having a hard time with Regex.
What would be the regex for finding a file name with variable in between them?
For eg:</p>
<p>File name : DON_2010_JOE_1222022.txt</p>
<p>In the above file name the words DON, JOE and the format .txt will remain constant. Rest numbers might change for every file. There could be characters as well instead of numbers in those two places.
What im looking for is basically something like <code>DON_*_JOE_*.txt</code> with * being whatever it could be.</p>
<p>Can someone please help me with this?</p>
<p>I tried <code>DON_*_JOE_*.txt</code> and obviously it did not work.</p>
|
[
{
"answer_id": 74660057,
"author": "Nataliikaa PetroOwwa",
"author_id": 4848126,
"author_profile": "https://Stackoverflow.com/users/4848126",
"pm_score": 0,
"selected": false,
"text": "DON_(?<firstString>.*)_JOE_(?<secondString>.*).txt\n matcher.group(\"firstString\")"
},
{
"answer_id": 74661292,
"author": "oleedd",
"author_id": 10412361,
"author_profile": "https://Stackoverflow.com/users/10412361",
"pm_score": -1,
"selected": true,
"text": "\"DON_2010_JOE_1222022.txt\".match(/DON_.+_JOE_.+\\.txt/) .+"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10402543/"
] |
74,659,858
|
<p>I'm used to use GCP's secret manager. There, we can create a secret and give a specific READ permission for one specific service account.
I mean, let's say we create a secret ABC and a service account "getsecretaccount", I can give the read permission for this SA called getsecretaccount to access the ABC secret. This getsecretaccount will not have access to any other secret there.</p>
<p>Can I achieve this scenario in Azure Key Vault?</p>
<p>Thx!!</p>
|
[
{
"answer_id": 74660057,
"author": "Nataliikaa PetroOwwa",
"author_id": 4848126,
"author_profile": "https://Stackoverflow.com/users/4848126",
"pm_score": 0,
"selected": false,
"text": "DON_(?<firstString>.*)_JOE_(?<secondString>.*).txt\n matcher.group(\"firstString\")"
},
{
"answer_id": 74661292,
"author": "oleedd",
"author_id": 10412361,
"author_profile": "https://Stackoverflow.com/users/10412361",
"pm_score": -1,
"selected": true,
"text": "\"DON_2010_JOE_1222022.txt\".match(/DON_.+_JOE_.+\\.txt/) .+"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342111/"
] |
74,659,902
|
<p>I want the config to show up with 2 spaces before each line.</p>
<pre><code>---
- hosts: localhost
vars:
filename: file1
a: aaa
config: |-
missingok
daily
compress
rotate 4
create
dateext
dateformat -%d%m%Y
dateyesterday
tasks:
- name: Creating log config file
copy:
dest: /{{ filename }}
content: |
{{ a }}
{
{{ config }}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/0sN87.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0sN87.png" alt="enter image description here" /></a></p>
<p>The spaces show up if I add another line at the beginning of config without any spaces. Putting spaces before the config variable also doesn't work because it only affects the first line (missingok) and the rest would be without any spaces in front.</p>
|
[
{
"answer_id": 74660546,
"author": "flyx",
"author_id": 347964,
"author_profile": "https://Stackoverflow.com/users/347964",
"pm_score": 3,
"selected": true,
"text": " config: |2-\n missingok\n daily\n compress\n rotate 4\n create\n dateext\n dateformat -%d%m%Y\n dateyesterday\n 2 config:"
},
{
"answer_id": 74663713,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 1,
"selected": false,
"text": " a: aaa\n config: |-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\ndaily\ncompress\n}\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config|indent(2) }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n config: |2-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16758323/"
] |
74,659,934
|
<p>I am relatively new to SAS but have done a fair amount of programming over the years. I am at a loss on how to accomplish a task in SAS that I feel I would be able to do relatively easily in other platforms. I have an input table similar to this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>City</th>
<th>_1988</th>
<th>_1989</th>
<th>_1990</th>
<th>_1991</th>
<th>_1992</th>
<th>_1993</th>
<th>_1994</th>
<th>_1995</th>
<th>_1996</th>
<th>_1997</th>
<th>_1998</th>
<th>_1999</th>
<th>_2000</th>
</tr>
</thead>
<tbody>
<tr>
<td>Columbus</td>
<td>438866</td>
<td>437148</td>
<td>16082</td>
<td>475843</td>
<td>224411</td>
<td>411569</td>
<td>658459</td>
<td>174208</td>
<td>592418</td>
<td>31664</td>
<td>312374</td>
<td>242830</td>
<td>342950</td>
</tr>
<tr>
<td>Fargo</td>
<td>11218</td>
<td>7402</td>
<td>35574</td>
<td>14765</td>
<td>64727</td>
<td>29492</td>
<td>104541</td>
<td>616</td>
<td>57864</td>
<td>73451</td>
<td>96251</td>
<td>78803</td>
<td>34743</td>
</tr>
<tr>
<td>Santa Fe</td>
<td>10608</td>
<td>31531</td>
<td>46163</td>
<td>28215</td>
<td>62608</td>
<td>52576</td>
<td>55674</td>
<td>43339</td>
<td>34896</td>
<td>77851</td>
<td>41304</td>
<td>31308</td>
<td>60306</td>
</tr>
<tr>
<td>Poughkeepsie</td>
<td>2184</td>
<td>15642</td>
<td>13505</td>
<td>9279</td>
<td>22796</td>
<td>6458</td>
<td>3279</td>
<td>4458</td>
<td>19672</td>
<td>17610</td>
<td>2672</td>
<td>11454</td>
<td>1072</td>
</tr>
<tr>
<td>Montpelier</td>
<td>1428</td>
<td>671</td>
<td>520</td>
<td>5453</td>
<td>5468</td>
<td>2117</td>
<td>2802</td>
<td>5847</td>
<td>3165</td>
<td>6204</td>
<td>1832</td>
<td>5357</td>
<td>5499</td>
</tr>
<tr>
<td>Waco</td>
<td>12527</td>
<td>695</td>
<td>44426</td>
<td>61651</td>
<td>83997</td>
<td>12811</td>
<td>50570</td>
<td>15022</td>
<td>86732</td>
<td>38541</td>
<td>45292</td>
<td>120719</td>
<td>17969</td>
</tr>
<tr>
<td>Nashville</td>
<td>359806</td>
<td>249811</td>
<td>422314</td>
<td>151319</td>
<td>466174</td>
<td>107335</td>
<td>315576</td>
<td>571273</td>
<td>195685</td>
<td>230626</td>
<td>194663</td>
<td>11060</td>
<td>545940</td>
</tr>
<tr>
<td>Billings</td>
<td>49694</td>
<td>37415</td>
<td>38602</td>
<td>79238</td>
<td>65260</td>
<td>18497</td>
<td>8976</td>
<td>81148</td>
<td>71326</td>
<td>108760</td>
<td>43740</td>
<td>48110</td>
<td>32106</td>
</tr>
<tr>
<td>Pensacola</td>
<td>4501</td>
<td>9682</td>
<td>19061</td>
<td>14731</td>
<td>4623</td>
<td>16106</td>
<td>13419</td>
<td>47607</td>
<td>9198</td>
<td>25003</td>
<td>39303</td>
<td>45146</td>
<td>24143</td>
</tr>
<tr>
<td>Trenton</td>
<td>40341</td>
<td>21210</td>
<td>4162</td>
<td>57773</td>
<td>16937</td>
<td>60495</td>
<td>21508</td>
<td>80819</td>
<td>27349</td>
<td>65088</td>
<td>65815</td>
<td>66308</td>
<td>38151</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to find the median of all the differences in values for each city.</p>
<p>The basic logic is I need to obtain the median of all the values in the array "difference" in the pseudo-code below.</p>
<pre><code> for i = 1988 to 2000
for j = i+1 to 2000
difference(i,j) = value year_i - value year_j
end
end
</code></pre>
<p>I wish I could paste my sample code here, but I am basically at a point of writers block where what I have produced is so far off that it is of no use. I don't necessarily need someone to write the entire code for me but am hoping somebody can send me down the right path. I feel like this shouldn't be that hard, but I am at a loss . . .</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74660546,
"author": "flyx",
"author_id": 347964,
"author_profile": "https://Stackoverflow.com/users/347964",
"pm_score": 3,
"selected": true,
"text": " config: |2-\n missingok\n daily\n compress\n rotate 4\n create\n dateext\n dateformat -%d%m%Y\n dateyesterday\n 2 config:"
},
{
"answer_id": 74663713,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 1,
"selected": false,
"text": " a: aaa\n config: |-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\ndaily\ncompress\n}\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config|indent(2) }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n config: |2-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668733/"
] |
74,659,968
|
<p>I would like to iterate through a dataframe rows and concatenate that row to a different dataframe basically building up a different dataframe with some rows.</p>
<p>For example:
`<a href="https://i.stack.imgur.com/PSx9U.png" rel="nofollow noreferrer">IPCSection and IPCClass Dataframes</a></p>
<pre><code>
allcolumns = np.concatenate((IPCSection.columns, IPCClass.columns), axis = 0)
finalpatentclasses = pd.DataFrame(columns=allcolumns)
for isec, secrow in IPCSection.iterrows():
for icl, clrow in IPCClass.iterrows():
if (secrow[0] in clrow[0]):
pdList = [finalpatentclasses, pd.DataFrame(secrow), pd.DataFrame(clrow)]
finalpatentclasses = pd.concat(pdList, axis=0, ignore_index=True)
display(finalpatentclasses)
</code></pre>
<p><a href="https://i.stack.imgur.com/9gEuY.png" rel="nofollow noreferrer">The output is:</a></p>
<p>I want the nan values to dissapear and move all the data under the correct columns. I tried axis = 1 but messes up the column names. Append does not work as well all values are placed diagonally at the table with nan values as well.</p>
|
[
{
"answer_id": 74660546,
"author": "flyx",
"author_id": 347964,
"author_profile": "https://Stackoverflow.com/users/347964",
"pm_score": 3,
"selected": true,
"text": " config: |2-\n missingok\n daily\n compress\n rotate 4\n create\n dateext\n dateformat -%d%m%Y\n dateyesterday\n 2 config:"
},
{
"answer_id": 74663713,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 1,
"selected": false,
"text": " a: aaa\n config: |-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\ndaily\ncompress\n}\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config|indent(2) }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n config: |2-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74659968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20669067/"
] |
74,660,013
|
<p>I have a query that pulls specific ranges of columns from a different sheet. It is combining the top two rows. Any way to string together multiple ranges of columns from a different sheet and not combine the top row? thanks</p>
<p>example Query ( {'mainview'!, A1:L36, 'mainview'!n1:N36}) this does not work</p>
<p>First column not combined with second.</p>
|
[
{
"answer_id": 74660546,
"author": "flyx",
"author_id": 347964,
"author_profile": "https://Stackoverflow.com/users/347964",
"pm_score": 3,
"selected": true,
"text": " config: |2-\n missingok\n daily\n compress\n rotate 4\n create\n dateext\n dateformat -%d%m%Y\n dateyesterday\n 2 config:"
},
{
"answer_id": 74663713,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 1,
"selected": false,
"text": " a: aaa\n config: |-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\ndaily\ncompress\n}\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config|indent(2) }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n config: |2-\n missingok\n daily\n compress\n - copy:\n dest: /tmp/file1\n content: |\n {{ a }}\n {\n {{ config }}\n }\n shell> cat /tmp/file1 \naaa\n{\n missingok\n daily\n compress\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13052545/"
] |
74,660,024
|
<p>I have a class <code>BleScanner</code> that wraps an internal <code>BluetoothLEAdvertisementWatcher</code>. It also implements <code>IDisposable</code> to make sure that the watcher is stopped when the scanner gets disposed of.</p>
<pre><code>public sealed class BleScanner : IDisposable
{
public event AdvertisementReceivedHandler? AdvertisementReceived;
private readonly BluetoothLEAdvertisementWatcher m_Watcher;
public BleScanner() {
m_Watcher = new() {
// ...
};
// m_Watcher.Received += OnAdvertisementReceived;
}
// private void OnAdvertisementReceived(...) {
// code elided for brevity
// may eventually raise AdvertisementReceived
// }
public void Start() => m_Watcher.Start();
public void Stop() => m_Watcher.Stop();
public void Dispose() {
if (m_Watcher.Status == BluetoothLEAdvertisementWatcherStatus.Started) {
m_Watcher.Stop();
}
}
}
</code></pre>
<p>The watcher is not disposable. So in theory, the scanner would still work if you just called <code>Start</code> again after <code>Dispose</code>:</p>
<pre><code>public async Task ScannerTest(CancellationToken token) {
using var scanner = new BleScanner();
scanner.AdvertisementReceived += OnAdvertisementReceived;
scanner.Start(); // will start the scan
await Task.Delay(3000, token); // raise events for 3 seconds
scanner.Stop(); // could be forgotten
scanner.Dispose(); // will stop the scan if indeed it was forgotten
scanner.Start(); // everything will work, despite "scanner" being disposed already
}
</code></pre>
<p>Should I make sure <code>Start</code> (and maybe <code>Stop</code>) throws an <code>ObjectDisposedException</code> after <code>Dispose</code> was called? The <a href="https://learn.microsoft.com/dotnet/standard/garbage-collection/implementing-dispose" rel="nofollow noreferrer">guidelines on the Dispose pattern</a> only require that <code>Dispose</code> can be called multiple times without an exception, but don't say anything about how the other members should behave after <code>Dispose</code> was called. Neither does <a href="https://learn.microsoft.com/dotnet/standard/garbage-collection/using-objects" rel="nofollow noreferrer">using disposable objects</a> of the <a href="https://learn.microsoft.com/dotnet/api/system.idisposable" rel="nofollow noreferrer">IDisposable interface</a> say what to expect when calling methods on a disposed object.</p>
|
[
{
"answer_id": 74660686,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "BluetoothLEAdvertisementWatcher"
},
{
"answer_id": 74667093,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 0,
"selected": false,
"text": "IDisposable Start Stop Start IDisposable Stop Stop Disposable public sealed class BleScanner\n{\n public event AdvertisementReceivedHandler? AdvertisementReceived;\n\n private readonly BluetoothLEAdvertisementWatcher m_Watcher;\n\n public BleScanner() {\n m_Watcher = new() {\n // ...\n };\n // m_Watcher.Received += OnAdvertisementReceived;\n }\n\n public void Start()\n {\n m_Watcher.Start();\n return Disposable.Create(() => Stop());\n }\n\n private void Stop() => m_Watcher.Stop();\n}\n\npublic async Task ScannerTest(CancellationToken token) {\n var scanner = new BleScanner();\n scanner.AdvertisementReceived += OnAdvertisementReceived;\n\n using var scannerSubsctiption = scanner.Start();\n await Task.Delay(3000, token); // raise events for 3 seconds\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1843468/"
] |
74,660,047
|
<p>I am developing the code for my PIC32MK1024MCM project. I have already tested the code well and now I am only putting all the code modules into the final project (the code is not complete in this example yet, but the functionality is not the axis of interest here). For the first time in my life, I wanted to make it a little bit more professional and use separate source and header files for all the different module function declaration. However, I am clearly facing some kind of syntax problem, because I am getting errors in almost every line of the source file (I guess I have to include something in that source file, but I am not sure) Like I said, it is my very first time facing header and source files, so could you please help me, or at least hint me, what is it that I am missing so obviously? I want to thank you in advance.</p>
<p>main:</p>
<pre><code>#include <xc.h>
#include <configuration_bits.c>
#include <toolchain_specifics.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include "stdio.h"
#include <sys/attribs.h>
#include <analog_to_digital_conversion.h>
void main(void) {
while (1){
}
return (EXIT_FAILURE);
}
</code></pre>
<p>configurations_bits</p>
<pre><code>// DEVCFG3
#pragma config USERID = 0xFFFF // Enter Hexadecimal value (Enter Hexadecimal value)
#pragma config PWMLOCK = OFF // PWM IOxCON lock (PWM IOxCON register writes accesses are not locked or protected)
#pragma config FUSBIDIO2 = OFF // USB2 USBID Selection (USBID pin is controlled by the port function)
#pragma config FVBUSIO2 = OFF // USB2 VBUSON Selection bit (VBUSON pin is controlled by the port function)
#pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration bit (Allow multiple reconfigurations)
#pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations)
#pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations)
#pragma config FUSBIDIO1 = OFF // USB1 USBID Selection (USBID pin is controlled by the port function)
#pragma config FVBUSIO1 = OFF // USB2 VBUSON Selection bit (VBUSON pin is controlled by the port function)
// DEVCFG2
#pragma config FPLLIDIV = DIV_1 // System PLL Input Divider (1x Divider)
#pragma config FPLLRNG = RANGE_BYPASS // System PLL Input Range (Bypass)
#pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
#pragma config FPLLMULT = MUL_4 // System PLL Multiplier (PLL Multiply by 4)
#pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
#pragma config BORSEL = HIGH // Brown-out trip voltage (BOR trip voltage 2.1v (Non-OPAMP deviced operation))
#pragma config UPLLEN = OFF // USB PLL Enable (USB PLL Disabled)
// DEVCFG1
#pragma config FNOSC = POSC // Oscillator Selection Bits (Primary Osc (HS,EC))
#pragma config DMTINTV = WIN_0 // DMT Count Window Interval (Window/Interval value is zero)
#pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable Secondary Oscillator)
#pragma config IESO = ON // Internal/External Switch Over (Enabled)
#pragma config POSCMOD = HS // Primary Oscillator Configuration (HS osc mode)
#pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
#pragma config FCKSM = CSDCMD // Clock Switching and Monitor Selection (Clock Switch Disabled, FSCM Disabled)
#pragma config WDTPS = PS1 // Watchdog Timer Postscaler (1:1)
#pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
#pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
#pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled)
#pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
#pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
#pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)
// DEVCFG0
#pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
#pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled)
#pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
#pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled)
#pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
#pragma config FECCCON = ECC_DECC_DISABLE_ECCON_WRITABLE // Dynamic Flash ECC Configuration Bits (ECC and Dynamic ECC are disabled (ECCCON<1:0> bits are writable))
#pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
#pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
#pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable (MCLR pin generates a normal system Reset)
#pragma config SOSCGAIN = G3 // Secondary Oscillator Gain Control bits (Gain is G3)
#pragma config SOSCBOOST = ON // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config POSCGAIN = G3 // Primary Oscillator Coarse Gain Control bits (Gain Level 3 (highest))
#pragma config POSCBOOST = ON // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config POSCFGAIN = G3 // Primary Oscillator Fine Gain Control bits (Gain is G3)
#pragma config POSCAGCDLY = AGCRNG_x_25ms // AGC Gain Search Step Settling Time Control (Settling time = 25ms x AGCRNG)
#pragma config POSCAGCRNG = ONE_X // AGC Lock Range bit (Range 1x)
#pragma config POSCAGC = Automatic // Primary Oscillator Gain Control bit (Automatic Gain Control for Oscillator)
#pragma config EJTAGBEN = NORMAL // EJTAG Boot Enable (Normal EJTAG functionality)
// DEVCP
#pragma config CP = OFF // Code Protect (Protection Disabled)
// SEQ
#pragma config TSEQ = 0xFFFF // Boot Flash True Sequence Number (Enter Hexadecimal value)
#pragma config CSEQ = 0xFFFF // Boot Flash Complement Sequence Number (Enter Hexadecimal value)
</code></pre>
<p>analog_to_digital_conversion.h</p>
<pre><code>//**************************************************************************
// ANALOG TO DIGITAL CONVERSION HEADER FILE
//**************************************************************************
#include <analog_to_digital_conversion.c>
void Anaolog_to_Digital_Conversion_Setup (void);
void Anaolog_to_Digital_Conversion_Enable (void);
void Anaolog_to_Digital_Conversion_Disable (void);
uint16_t Anaolog_to_Digital_Conversion (void);
</code></pre>
<p>analog_to_digital_conversion.c</p>
<pre><code>//**************************************************************************
// ANALOG TO DIGITAL CONVERSION SOURCE FILE
//**************************************************************************
void Anaolog_to_Digital_Conversion_Setup (void){
//All this procedure is taken from the device`s datasheet (no ADC interrupts are desired)
ADCANCONbits.ANEN5 = 0b0; //Analog and bias circuitry disabled (to set calibration)
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADC5CFGbits.ADCCFG = DEVADC5; //Copying the factory calibration ADC module bits to the ADC configuration register
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCCON1bits.ON = 0b0; //Disabling the ADC module
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADC5TIMEbits.SAMC = 0b1111111111; //Sample time is set to 1025 TAD
ADC5TIMEbits.ADCDIV = 0b1111111; //254 * TQ = TAD (ADC clock division bits)
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCANCONbits.WKUPCLKCNT = 0xF; //ADC warm up time is set to 32768 ADC clock cycles (maximum warm up time, around 32 us @ 100 MHz SYSCLK)
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCCON3bits.ADCSEL = 0b0; //Analog-to-Digital Clock Source (TCLK) -> SYSCLK
ADCCON3bits.CONCLKDIV = 0b000000; //TCLK = TQ
ADCCON3bits.DIGEN5 = 0b0; //All digital bits are disabled (according to the datasheet)
ADCCON3bits.VREFSEL = 0b000; //Vref is set to AVdd and AVss
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCIMCON1bits.DIFF11 = 0b0; //AN11 is using Single-ended mode
ADCIMCON1bits.SIGN11 = 0b0; //AN11 is using Unsigned Data mode
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCTRGSNSbits.LVL11 = 0b0; //Analog input is sensitive to the positive edge of its trigger (this is the value after a reset)
//---------------------------------------------------------------
ADCTRG3bits.TRGSRC11 = 0b00001; //AN11 is software triggered
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCANCONbits.ANEN5 = 0b1; //Analog and bias circuitry enabled
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCCON1bits.ON = 0b1; //Enabling the ADC module
//---------------------------------------------------------------
while(!((ADCCON2bits.BGVRRDY)&&(ADCANCONbits.WKRDY5))); //Wait until device analog environment is ready
ADCCON3bits.DIGEN5 = 0b1; //Enable digital circuitry for data processing
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCCON3bits.ADINSEL = 0b001011; //Select analog channel 11 for conversion
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
ADCCON1bits.ON = 0b0; //Disabling the ADC module
}
void Anaolog_to_Digital_Conversion_Enable (void){
ADCCON1bits.ON = 0b1; //Enabling the ADC module
}
void Anaolog_to_Digital_Conversion_Disable (void){
ADCCON1bits.ON = 0b0; //Disabling the ADC module
}
uint16_t Anaolog_to_Digital_Conversion (void){
uint16_t ADC_value = 0;
ADCCON3bits.RQCNVRT = 1; //Trigger the conversion
while(!ADCDSTAT1bits.ARDY11); //Waiting until ADC result is ready to be read (@ 100 MHz SYSCLK ADC conversion should take around 2ms)
ADC_value = ADCDATA11 & 0x000FFFF; //Acquiring ADC result, register is 32 bits, but conversion only gives 12 bit ADC value, hence getting rid of higher 16 bits (those are all zeros)
return (ADC_value);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/YPgzl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YPgzl.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74660686,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "BluetoothLEAdvertisementWatcher"
},
{
"answer_id": 74667093,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 0,
"selected": false,
"text": "IDisposable Start Stop Start IDisposable Stop Stop Disposable public sealed class BleScanner\n{\n public event AdvertisementReceivedHandler? AdvertisementReceived;\n\n private readonly BluetoothLEAdvertisementWatcher m_Watcher;\n\n public BleScanner() {\n m_Watcher = new() {\n // ...\n };\n // m_Watcher.Received += OnAdvertisementReceived;\n }\n\n public void Start()\n {\n m_Watcher.Start();\n return Disposable.Create(() => Stop());\n }\n\n private void Stop() => m_Watcher.Stop();\n}\n\npublic async Task ScannerTest(CancellationToken token) {\n var scanner = new BleScanner();\n scanner.AdvertisementReceived += OnAdvertisementReceived;\n\n using var scannerSubsctiption = scanner.Start();\n await Task.Delay(3000, token); // raise events for 3 seconds\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18135626/"
] |
74,660,058
|
<p>Looking to solve how to pass my search results to other components so when users use the search bar, the searched results gets displayed instead of that components rendered data.. in this case it would homeScreen. using react router v5 and i tried passing it through the router but many attempts didn't work, should i create a seperate search router too?</p>
<p>App.js:</p>
<pre><code><Container>
<Route path="/" component={HomeScreen} exact />
<Route path="/login" component={LoginScreen} exact />
<Route path="/register" component={RegisterScreen} exact />
<Route path="/product/:id" component={ProductScreen} exact />
<Route path="/cart/:id?" component={CartScreen} exact />
</Container>
</code></pre>
<p>header.js:</p>
<pre><code>function Header() {
const userLogin = useSelector((state) => state.userLogin);
const { userInfo } = userLogin;
// const [items, setItems] = useState("");
const [searchResults, setSearchResults] = useState([]);
const debounce = useDebounce(searchResults, 500);
const dispatch = useDispatch();
const logoutHandler = () => {
dispatch(logout());
};
useEffect(() => {
axios.get(`/api/search/?search=${searchResults}`).then((response) => {
setSearchResults(response.data[0]);
console.log(response.data[0]);
});
}, [debounce]);
const handleSearch = (e) => {
setSearchResults(e.target.value);
};
return (
<div>
<Navbar bg="dark" variant="dark" className="navCustom">
<Container>
<LinkContainer to="/">
<Navbar.Brand>eCommerce</Navbar.Brand>
</LinkContainer>
<Form className="d-flex">
<Form.Control
type="search"
placeholder="Search"
className="me-2"
aria-label="Search"
onChange={handleSearch}
/>
<Button variant="outline-success">Search</Button>
</Form>
</code></pre>
<p>HomeScreen.js:</p>
<pre><code>function HomeScreen({ searchResults }) {
const dispatch = useDispatch();
const productList = useSelector((state) => state.productList);
const { error, loading, products } = productList;
useEffect(() => {
dispatch(listProducts());
}, [dispatch]);
return (
<div>
{searchResults.length > 0 ? (
<Row>
{searchResults.map((product) => (
<Col key={product._id} sm={12} md={6} lg={4} xl={3}>
<Product product={product} />
</Col>
))}
</Row>
) : (
// Fall back to rendering regular products
<Row>
{products &&
products.map((product) => (
<Col key={product._id} sm={12} md={6} lg={4} xl={3}>
<Product product={product} />
</Col>
))}
</Row>
)}
</div>
);
}
export default HomeScreen;
</code></pre>
|
[
{
"answer_id": 74660686,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "BluetoothLEAdvertisementWatcher"
},
{
"answer_id": 74667093,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 0,
"selected": false,
"text": "IDisposable Start Stop Start IDisposable Stop Stop Disposable public sealed class BleScanner\n{\n public event AdvertisementReceivedHandler? AdvertisementReceived;\n\n private readonly BluetoothLEAdvertisementWatcher m_Watcher;\n\n public BleScanner() {\n m_Watcher = new() {\n // ...\n };\n // m_Watcher.Received += OnAdvertisementReceived;\n }\n\n public void Start()\n {\n m_Watcher.Start();\n return Disposable.Create(() => Stop());\n }\n\n private void Stop() => m_Watcher.Stop();\n}\n\npublic async Task ScannerTest(CancellationToken token) {\n var scanner = new BleScanner();\n scanner.AdvertisementReceived += OnAdvertisementReceived;\n\n using var scannerSubsctiption = scanner.Start();\n await Task.Delay(3000, token); // raise events for 3 seconds\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19778871/"
] |
74,660,087
|
<p>I have an igraph plot that is geographically laid out based on its latitude and longitude coordinates. I now want to hide certain points from one time period, while preserving the layout of the graph. I would therefore not like to delete the vertices from the network, but merely make them invisible in this particular plot rendering, conditional on a vertex attribute. Furthermore, the color attribute is already set to capture another variable, so I cannot use that to hide the points.</p>
<p>My plot is generated according to the following code:</p>
<pre><code>lo <- layout.norm(as.matrix(g[, c("longitude","latitude")]))
plot.igraph(g, layout=lo, vertex.label=NA,rescale=T, vertex.size = 4)
</code></pre>
<p>The time attribute is a numerical variable stored in <code>V(g)$period</code></p>
<p>Is there code I can put within the <code>plot.igraph</code> function to hide vertices for which <code>V(g)$period</code> == 1?</p>
|
[
{
"answer_id": 74660686,
"author": "Vic F",
"author_id": 4054386,
"author_profile": "https://Stackoverflow.com/users/4054386",
"pm_score": 2,
"selected": false,
"text": "BluetoothLEAdvertisementWatcher"
},
{
"answer_id": 74667093,
"author": "Stephen Cleary",
"author_id": 263693,
"author_profile": "https://Stackoverflow.com/users/263693",
"pm_score": 0,
"selected": false,
"text": "IDisposable Start Stop Start IDisposable Stop Stop Disposable public sealed class BleScanner\n{\n public event AdvertisementReceivedHandler? AdvertisementReceived;\n\n private readonly BluetoothLEAdvertisementWatcher m_Watcher;\n\n public BleScanner() {\n m_Watcher = new() {\n // ...\n };\n // m_Watcher.Received += OnAdvertisementReceived;\n }\n\n public void Start()\n {\n m_Watcher.Start();\n return Disposable.Create(() => Stop());\n }\n\n private void Stop() => m_Watcher.Stop();\n}\n\npublic async Task ScannerTest(CancellationToken token) {\n var scanner = new BleScanner();\n scanner.AdvertisementReceived += OnAdvertisementReceived;\n\n using var scannerSubsctiption = scanner.Start();\n await Task.Delay(3000, token); // raise events for 3 seconds\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18574641/"
] |
74,660,121
|
<p>Using the method JsonConvert.DeserializeObject returns the default values for all properties.</p>
<pre class="lang-cs prettyprint-override"><code>var current = JsonConvert.DeserializeObject<Current>(myJson);
</code></pre>
<pre class="lang-json prettyprint-override"><code>{
"location": {
"name": "London"
},
"current": {
"temp_c": 5.0,
"cloud": 50
}
}
</code></pre>
<pre><code>public class Current
{
public double Temp_c { get; set; }
public double Cloud { get; set; }
}
</code></pre>
<p>The expected current object should have the values: 50 for <code>Cloud</code>, and 5.0 for <code>Temp_c</code>, but returns the default values for all properties.</p>
|
[
{
"answer_id": 74660200,
"author": "Saeed Gholamzadeh",
"author_id": 12781348,
"author_profile": "https://Stackoverflow.com/users/12781348",
"pm_score": 2,
"selected": false,
"text": "public class YourModel {\n\n //create location class that has Name property\n public Location Location { get; set; }\n\n //create current class that has Temp_c and Cloud property\n public Current Current { get; set; }\n\n}\n var data = JsonConvert.DeserializeObject<YourModel>(myJson);\n var current = data.Current;\n"
},
{
"answer_id": 74660597,
"author": "user3281302",
"author_id": 3281302,
"author_profile": "https://Stackoverflow.com/users/3281302",
"pm_score": 1,
"selected": false,
"text": "[JsonPropertyName(\"temp_c\")] // .Net serializer (I prefer this)\n [JsonProperty(\"temp_c\")] // Newtonsoft.Json serializer\n using System;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\n#nullable disable\n\nnamespace test\n{\n public class Weather\n {\n [JsonPropertyName(\"location\")]\n public Location Location { get; set; }\n\n [JsonPropertyName(\"current\")]\n public Current Current { get; set; }\n }\n\n public class Location\n {\n [JsonPropertyName(\"name\")]\n public string Name { get; set; }\n }\n\n public class Current\n {\n [JsonPropertyName(\"temp_c\")]\n public double TempC { get; set; }\n\n [JsonPropertyName(\"cloud\")]\n public int Cloud { get; set; }\n }\n\n\n class Program\n {\n static void Main(string[] args)\n {\n string json = \"{\\\"location\\\": { \\\"name\\\": \\\"London\\\" }, \\\"current\\\": { \\\"temp_c\\\": 5.0, \\\"cloud\\\": 50 }}\";\n Weather myWeather = JsonSerializer.Deserialize<Weather>(json);\n\n Console.WriteLine(\"Location: {0} - Temp: {1:F}\", myWeather.Location.Name, myWeather.Current.TempC);\n }\n }\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20668996/"
] |
74,660,147
|
<p>Lets supose I have a tabla A like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>bisac1</th>
<th>bisac2</th>
<th>bisac3</th>
<th>desire</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>y</td>
<td>z</td>
<td>10</td>
</tr>
<tr>
<td>y</td>
<td>z</td>
<td>x</td>
<td>8</td>
</tr>
<tr>
<td>z</td>
<td>y</td>
<td>x</td>
<td>6</td>
</tr>
<tr>
<td>x</td>
<td>y</td>
<td>p</td>
<td>20</td>
</tr>
<tr>
<td>r</td>
<td>y</td>
<td>z</td>
<td>13</td>
</tr>
<tr>
<td>x</td>
<td>s</td>
<td>z</td>
<td>1</td>
</tr>
<tr>
<td>a</td>
<td>y</td>
<td>l</td>
<td>12</td>
</tr>
<tr>
<td>a</td>
<td>x</td>
<td>k</td>
<td>2</td>
</tr>
<tr>
<td>x</td>
<td>p</td>
<td>w</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to be able to count the number of times any of these elements (x,y,z) appears in the cols (bisac1,bisac2,bisac3).</p>
<p>So, the expected result should be 3 for the first 3 rows, 2 for the next 3 and 1 for the last 3.</p>
|
[
{
"answer_id": 74660242,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 1,
"selected": false,
"text": "select \n case when bisac1 in ('x','y','z') then 1 else 0 end +\n case when bisac2 in ('x','y','z') then 1 else 0 end +\n case when bisac3 in ('x','y','z') then 1 else 0 end \nfrom t;\n"
},
{
"answer_id": 74660420,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "SELECT \n CASE WHEN 'x' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +\n CASE WHEN 'y' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +\n CASE WHEN 'z' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END\nFROM yourtable;\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10596766/"
] |
74,660,172
|
<p>I am really struggling in creating a macro that from a master Excel file creates multiple Excel files based on the values in the first column. More specifically, I have in column "A" some categories, and based on all the categories (ITT1, ITT2, ITT3, ITT4 and ITT5) I would like to create multiple excel files containing the sheet with just 1 category. At the moment, I have been able to save just 1 file with 1 category. But I cannot do it with multiple. Could you kindly help me please? I am stuck.</p>
<pre><code>Sub Split()
Dim location As String
location = "Z:\Incent_2022\ORDINARIA\RETAIL-WHS\Andamento\Q4\Andamento\Novembre\And. Inc Q4_ITT1.xlsm"
ActiveWorkbook.SaveAs Filename:=location, FileFormat:=52
With ActiveSheet
Const FirstRow As Long = 6
Dim LastRow As Long
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last used row in column A
Dim Row As Long
For Row = LastRow To FirstRow Step -1
If Not .Range("A" & Row).Value = "ITT1" Then
.Range("A" & Row).EntireRow.Delete
End If
Next Row
End With
ActiveWorkbook.Close SaveChanges:=True
End Sub
</code></pre>
|
[
{
"answer_id": 74660242,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 1,
"selected": false,
"text": "select \n case when bisac1 in ('x','y','z') then 1 else 0 end +\n case when bisac2 in ('x','y','z') then 1 else 0 end +\n case when bisac3 in ('x','y','z') then 1 else 0 end \nfrom t;\n"
},
{
"answer_id": 74660420,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "SELECT \n CASE WHEN 'x' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +\n CASE WHEN 'y' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +\n CASE WHEN 'z' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END\nFROM yourtable;\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19076195/"
] |
74,660,181
|
<p>I'm trying to install packages on multiple versions of Python. I'm currently running 3.8.8, and 3.11.0.</p>
<p>Following this post <a href="https://stackoverflow.com/questions/10919569/install-a-module-using-pip-for-specific-python-version">Install a module using pip for specific python version</a>
called</p>
<p><code>python3.11 -m pip install pandas</code></p>
<p>which results in</p>
<p><code>File "<stdin>", line 1 python3.11 -m pip install pandas SyntaxError: invalid syntax </code></p>
<p>This seems to indicate an issue with python, so I double checked that python3.11 is installed.</p>
<p>the python3.11 works in isolation seems to work.</p>
<p>I don't understand why the install command isn't working.</p>
|
[
{
"answer_id": 74660253,
"author": "Ivan Perehiniak",
"author_id": 20637117,
"author_profile": "https://Stackoverflow.com/users/20637117",
"pm_score": 0,
"selected": false,
"text": "python3 —-version\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16451872/"
] |
74,660,182
|
<p>Say I have a Typescript tuple:</p>
<pre><code>type Sandwich = [name: string, toppings: object]
</code></pre>
<p>Now I want to extend it:</p>
<pre><code>type HotDog = [name: string, toppings: object, length: number]
</code></pre>
<p>Can <code>HotDog</code> extend <code>Sandwich</code> without duplication?</p>
|
[
{
"answer_id": 74660221,
"author": "Alex Wayne",
"author_id": 62076,
"author_profile": "https://Stackoverflow.com/users/62076",
"pm_score": 1,
"selected": false,
"text": "type Sandwich = [name: string, toppings: object]\ntype HotDog = [...sandwich: Sandwich, length: number]\n// ^ type is [name: string, toppings: object, length: number]\n"
},
{
"answer_id": 74660249,
"author": "Sbagaria2710",
"author_id": 10111454,
"author_profile": "https://Stackoverflow.com/users/10111454",
"pm_score": 2,
"selected": false,
"text": "// Define a tuple type with three elements\ntype Tuple = [string, number, boolean];\n\n// Extend the tuple type by adding an additional element\n// with the type Date\ntype ExtendedTuple = [...Tuple, Date];\n\n// Create a variable of the extended tuple type\nconst tuple: ExtendedTuple = ['Hello', 42, true, new Date()];\n\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4185992/"
] |
74,660,194
|
<p>I want to create a struct by calling <code>new</code> member function of a given struct by initializing only some of the fields. I am getting an error <code>error[E0063]: missing fields b and join_handle in initializer of B::B</code>. This is my sample code</p>
<p>main.rs</p>
<pre><code>mod B;
mod A;
fn main() {
println!("Hello, world!");
}
</code></pre>
<p>A.rs</p>
<pre><code>pub struct AS {
a: String
}
</code></pre>
<p>B.rs</p>
<pre><code>use crate::A::AS;
use std::thread;
pub struct B {
a: String,
b: AS,
join_handle: thread::JoinHandle<()>
}
impl B {
fn new() -> B {
B {
a: String::from("Hi"),
}
}
}
</code></pre>
<p>How to partially initialize a struct?</p>
|
[
{
"answer_id": 74660337,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 2,
"selected": false,
"text": "Option B struct B {\n a: String,\n b: Option<AS>,\n join_handle: Option<thread::JoinHandle<()>>,\n}\nimpl B {\n fn new() -> Self {\n Self {\n a: String::from(\"hi\"),\n b: None,\n join_handle: None,\n }\n }\n}\n use std::thread;\nfn main() {\n println!(\"Hello, world!\");\n}\n\npub struct AS {\n a: String\n}\n\npub struct B {\n a: String,\n b: AS,\n join_handle: thread::JoinHandle<()>\n}\n\nimpl B {\n fn builder() -> BBuilder {\n BBuilder {\n a: String::from(\"Hi\"),\n b: None,\n join_handle: None,\n }\n }\n}\n\nstruct BBuilder {\n a: String,\n b: Option<AS>,\n join_handle: Option<thread::JoinHandle<()>>,\n}\n\nimpl BBuilder {\n fn a(mut self, b: AS) -> Self {\n self.b = Some(b);\n self\n }\n fn join_handle(mut self, join_handle: thread::JoinHandle<()>) -> Self {\n self.join_handle = Some(join_handle);\n self\n }\n fn build(self) -> Option<B> {\n let Self{ a, b, join_handle } = self;\n let b = b?;\n let join_handle = join_handle?;\n Some(B { a, b, join_handle })\n }\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3938402/"
] |
74,660,214
|
<p>I have a basic assignment and can't get the program right. The assignment is to make a program that displays the minimum amount of banknotes and coins necessary to pay.</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int pari;
cin >> pari;
switch (pari)
{
case 1: cout << pari/5000 << "*5000" << endl;
break;
case 2: cout << pari/1000 << "*1000" << endl;
break;
case 3: cout << pari/500 << "*500" << endl;
break;
case 4: cout << pari/100 << "*100" << endl;
break;
case 5: cout << pari/50 << "*50" << endl;
break;
case 6: cout << pari/10 << "*10" << endl;
break;
case 7: cout << pari/5 << "*5" << endl;
break;
case 8: cout << pari/2 << "*2" << endl;
break;
case 9: cout << pari/1 << "*1" << endl;
break;
default: cout << "WRONG";
}
return 0;
}
</code></pre>
<p>For example:</p>
<p>Input:</p>
<pre class="lang-none prettyprint-override"><code>54321
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>10x5000
4x1000
0x500
3x100
0x50
2x10
0x5
0x2
1x1
</code></pre>
<p>I tried with <code>switch</code> case, with <code>if</code> statements, but nothing works.</p>
|
[
{
"answer_id": 74660901,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n int pari;\n cin >> pari;\n\n cout << pari/5000 << \"*5000\" << endl;\n pari %= 5000;\n\n cout << pari/1000 << \"*1000\" << endl;\n pari %= 1000;\n\n cout << pari/500 << \"*500\" << endl;\n pari %= 500;\n\n cout << pari/100 << \"*100\" << endl;\n pari %= 100;\n\n cout << pari/50 << \"*50\" << endl;\n pari %= 50;\n\n cout << pari/10 << \"*10\" << endl;\n pari %= 10;\n\n cout << pari/5 << \"*5\" << endl;\n pari %= 5;\n\n cout << pari/2 << \"*2\" << endl;\n pari %= 2;\n\n cout << pari/1 << \"*1\" << endl;\n\n return 0;\n}\n #include <iostream>\nusing namespace std;\n\nint main()\n{\n const int bankNotes[] = {5000, 1000, 500, 100, 50, 10, 5, 2, 1};\n const int numBankNotes = sizeof(bankNotes)/sizeof(bankNotes[0]);\n\n int pari;\n cin >> pari;\n\n for (int i = 0; i < numBankNotes; ++i) {\n cout << pari/bankNotes[i] << \"*\" << bankNotes[i] << endl;\n pari %= bankNotes[i];\n }\n\n return 0;\n}\n"
},
{
"answer_id": 74661057,
"author": "W077Y",
"author_id": 9292589,
"author_profile": "https://Stackoverflow.com/users/9292589",
"pm_score": 0,
"selected": false,
"text": "int main()\n{\n int input_value = 0;\n std::cin >> input_value; // First we get the input.\n // We start with the highest value banknote.\n\n int value = input_value;\n int const number_of_5000_notes = value / 5000; // How many of these notes do \n // we need?\n value = value % 5000; // Now calculate the rest.\n\n int const number_of_1000_notes = value / 1000; // How many of these notes do \n // we need? \n value = value % 1000; // Now calculate the rest.\n int const number_of_500_notes = value / 500;\n value = value % 500;\n int const number_of_100_notes = value / 100;\n value = value % 100;\n int const number_of_50_notes = value / 50;\n value = value % 50;\n int const number_of_10_notes = value / 10;\n value = value % 10;\n int const number_of_5_notes = value / 5;\n value = value % 5;\n int const number_of_2_notes = value / 2;\n value = value % 2;\n int const number_of_1_notes = value;\n\n // At the end we write the output \n std::cout << \"Input: \" << input_value << std::endl;\n std::cout << \"Output:\" << std::endl;\n std::cout << number_of_5000_notes << \" x 5000\" << std::endl;\n std::cout << number_of_1000_notes << \" x 1000\" << std::endl;\n std::cout << number_of_500_notes << \" x 500\" << std::endl;\n std::cout << number_of_100_notes << \" x 100\" << std::endl;\n std::cout << number_of_50_notes << \" x 50\" << std::endl;\n std::cout << number_of_10_notes << \" x 10\" << std::endl;\n std::cout << number_of_5_notes << \" x 5\" << std::endl;\n std::cout << number_of_2_notes << \" x 2\" << std::endl;\n std::cout << number_of_1_notes << \" x 1\" << std::endl;\n\n return 0;\n}\n int main()\n{\n int value = 0;\n std::cin >> value; // Get input\n\n // Check input\n if (value == 0)\n {\n std::cout << \"No value or 0 has been entered\";\n return 0;\n }\n\n // Output on the fly\n std::cout << \"Input: \" << value << std::endl;\n std::cout << \"Output:\" << std::endl;\n\n // loop over a sorted list of banknotes.\n for (auto note_value_ent : {5000, 1000, 500, 100, 50, 10, 5, 2, 1})\n {\n int const number_of_notes = value / note_value_ent;\n value %= note_value_ent;\n std::cout << number_of_notes << \" x \" << note_value_ent << std::endl;\n }\n return 0;\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20669379/"
] |
74,660,234
|
<p>I have a simple string and a list:</p>
<pre><code>string = "the secret key is A"
list = ["123","234","345"]
</code></pre>
<p>I need to replace one item ("A") combining that item with another item from the list ("A123") as many times as the number of items in the list. Basically the result I would like to achieve is:</p>
<pre class="lang-none prettyprint-override"><code>"the secret key is A123"
"the secret key is A234"
"the secret key is A345"
</code></pre>
<p>I know I need to use a for loop but I fail in joining together the items.</p>
|
[
{
"answer_id": 74660259,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 0,
"selected": false,
"text": "str.replace st = \"the secret key is A\"\n\nlst = [\"123\",\"234\",\"345\"]\n\nkey_rep = \"A\"\n\nfor l in lst:\n print(st.replace(key_rep, key_rep+l))\n\n# Or as list_comprehension\n# [st.replace(key_rep, key_rep+l) for l in lst]\n the secret key is A123\nthe secret key is A234\nthe secret key is A345\n"
},
{
"answer_id": 74660298,
"author": "Pierre D",
"author_id": 758174,
"author_profile": "https://Stackoverflow.com/users/758174",
"pm_score": 1,
"selected": false,
"text": "s = \"the secret key is A\"\nlst = [\"123\",\"234\",\"345\"]\n\nitem = 'A'\nnewlst = [s.replace(item, f'{item}{tok}') for tok in lst]\n\n>>> newlst\n['the secret key is A123', 'the secret key is A234', 'the secret key is A345']\n 'And the secret key is A' item import re\n\ns = 'And the secret key is A, I repeat: A.'\nlst = ['123', '234', '345']\n\nitem = 'A'\nnewlst = [re.sub(fr'\\b{item}\\b', f'{item}{e}', s) for e in lst]\n\n>>> newlst\n['And the secret key is A123, I repeat: A123.',\n 'And the secret key is A234, I repeat: A234.',\n 'And the secret key is A345, I repeat: A345.']\n"
},
{
"answer_id": 74660691,
"author": "David",
"author_id": 20102061,
"author_profile": "https://Stackoverflow.com/users/20102061",
"pm_score": 0,
"selected": false,
"text": "string = \"the secret key is A\"\nlst = [\"123\", \"234\", \"345\"]\n\nres = list(map(lambda x: string + x, lst))\n\n#You can print it in any way you want, here are some examples:\nprint(*res)\n[print(i for i in res)]\n#...\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18020486/"
] |
74,660,240
|
<p>I'm playing a game with the following circuit diagram.<br />
3 inputs can be turned on.<br />
The solution of the game is to turn ON inputs 3, 4 and 8.</p>
<p><a href="https://i.stack.imgur.com/zlCXX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zlCXX.png" alt="Circuit diagram" /></a></p>
<blockquote>
<p>Here are the games rules:</p>
<p>The 3 wires of this circuit have been torn off.<br />
You have to choose where to plug them in to make the laser work again.<br />
The integrated circuit has AND, OR and XOR logic connectors.</p>
<p>AND: The 2 wires on the left must be powered for the right wire to be powered.<br />
OR : At least one of the 2 wires on the left must be powered for the right wire to be powered.<br />
XOR : Only one of the 2 wires on the left must be powered for the right wire to be powered.</p>
</blockquote>
<p>I would like to write an JavaScript algorithm to solve it, but I have no clue on how to write it...</p>
<p>I tried brute forcing using permutations but didn't manage to write the logical condition test.</p>
|
[
{
"answer_id": 74660631,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 2,
"selected": false,
"text": "function test(a, b, c, d, e, f, g, h) {\n const ab = a && b;\n const abcd = (ab || c) && d;\n const ef = e && f;\n const efgh = ef || g || h;\n\n const abcdef = abcd || ef;\n const efgh2 = ef !== efgh;\n\n const abcdefgh = abcdef && efgh2;\n\n return abcdefgh;\n}\n const result = document.querySelector('#result')\nconst wrapper = document.querySelector('#wrapper')\nconst inputs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].map(e => {\n const div = document.createElement('div')\n\n const label = document.createElement('label')\n label.textContent = e\n label.setAttribute('for', e)\n div.appendChild(label)\n\n const input = document.createElement('input')\n input.setAttribute('type', 'checkbox')\n input.setAttribute('id', e)\n div.appendChild(input)\n\n wrapper.appendChild(div)\n\n return input\n})\n\nupdate()\n\nwrapper.addEventListener('change', update)\n\nfunction update() {\n const value = test(...inputs.map(e => e.checked))\n result.textContent = value ? 'true' : 'false'\n}\n\nfunction test(a, b, c, d, e, f, g, h) {\n const ab = a && b\n const abcd = (ab || c) && d\n const ef = e && f\n const efgh = (ef || g || h)\n\n const abcdef = abcd || ef\n const efgh2 = ef !== efgh\n\n const abcdefgh = abcdef && efgh2\n\n return abcdefgh\n} <div id=\"wrapper\"></div>\n<p>result: <span id=\"result\"></span></p> for (const inp of getInputs()) {\n const result = test(...inp)\n if (result) {\n const values = inp.map((e, i) => e ? i + 1 : null).filter(e => e !== null)\n console.log(values)\n break\n }\n}\n\nfunction test(a, b, c, d, e, f, g, h) {\n const ab = a && b\n const abcd = (ab || c) && d\n const ef = e && f\n const efgh = (ef || g || h)\n\n const abcdef = abcd || ef\n const efgh2 = ef !== efgh\n\n const abcdefgh = abcdef && efgh2\n\n return abcdefgh\n}\n\nfunction* getInputs() {\n for (let i = 0; i < 2 ** 8; i += 1) {\n yield [...i.toString(2).padStart(8, '0')].map(e => e === '1')\n }\n}"
},
{
"answer_id": 74660677,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "OR const circuit(inputs) {\n const and0 = inputs[0] && inputs[1];\n const input2 = inputs[2] || and0; // implicit\n const and1 = input2 && inputs[3];\n const and2 = inputs[4] && inputs[5];\n const input6 = inputs[6] || and2; // implicit\n const or0 = input6 || inputs[7];\n const or1 = and1 || and2; // or `and1 || input6`?\n const xor = or0 != and2; // or `or0 != input6`?\n const and3 = or1 && xor;\n return and3;\n}\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19558281/"
] |
74,660,254
|
<p>I'm using Angular 14. I checked <a href="https://masteringjs.io/tutorials/fundamentals/foreach-break" rel="nofollow noreferrer">this</a> and several other articles but none was useful at all. I've a piece of code in a ternary operator. The code is like this:</p>
<pre><code>var finalValue = this.recordData.myArray.length === 0
? 'empty record'
: this.recordData.myArray.forEach(
(item: any) => {
if (item.stockKeepingStatus == 'A') {
this.thing = 'found';
// break; // syntax error
return this.thing;
} else {
this.thing = 'all are inactive';
}
return this.thing;
}
)
console.log(finalValue);
</code></pre>
<p>The logic is simple. If <code>myArray</code> is empty, then just say 'empty record'. Otherwise we will iterate through <code>myArray</code> array and check which item has <code>stockKeepingStatus</code> as active i.e. 'A'. The moment we find our first 'A' we will just break the loop and return 'found'. If none of the<code>stockKeepingStatus</code> was 'A' then we will just say 'all are inactive'. I'm getting <code>finalValue</code> undefined. Please point out my mistake.</p>
|
[
{
"answer_id": 74660351,
"author": "Satpal",
"author_id": 1668533,
"author_profile": "https://Stackoverflow.com/users/1668533",
"pm_score": 0,
"selected": false,
"text": "undefined every() var finalValue = this.recordData.myArray.length === 0 ?\n 'empty record' :\n (this.recordData.myArray.every((item: any) => item.stockKeepingStatus == 'A') ?\n 'found' :\n 'all are inactive');\n\nconsole.log(finalValue);"
},
{
"answer_id": 74660684,
"author": "Prashant Singh",
"author_id": 11170656,
"author_profile": "https://Stackoverflow.com/users/11170656",
"pm_score": 0,
"selected": false,
"text": "const strings = [\"Alpha\", \"Bravo\", \"Charlie\"];\n\nlet resultString = '';\n\nstrings.forEach(string => {\n if (string.startsWith('A')) {\n resultString = string;\n break;\n }\n});\n\nconsole.log(resultString); // 'Alpha'\n"
},
{
"answer_id": 74660947,
"author": "Thuti Navnaneeth Reddy",
"author_id": 16893554,
"author_profile": "https://Stackoverflow.com/users/16893554",
"pm_score": 1,
"selected": false,
"text": "find undefined const item = this.recordData.myArray.find((item: any) => item.stockKeepingStatus == 'A');\n\nconst finalValue = this.recordData.myArray.length === 0 ? 'empty record' : item ? 'found' : 'all are inactive';\n\nconsole.log(finalValue);\n\n"
},
{
"answer_id": 74660964,
"author": "Dmitry S.",
"author_id": 11008394,
"author_profile": "https://Stackoverflow.com/users/11008394",
"pm_score": 2,
"selected": true,
"text": "find forEach stockKeepingStatus undefined undefined const finalValue = this.recordData.myArray.length === 0\n ? 'empty record'\n : (this.recordData.myArray.find(item => item.stockKeepingStatus === 'A') ?\n 'found' : 'all are inactive'\n );\n\n\nconsole.log(finalValue);\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11163977/"
] |
74,660,257
|
<p>I've already looked at this and it did not solve my issue <a href="https://www.stackoverflow.com/">https://stackoverflow.com/questions/51079664/c-sharp-error-with-exceldatareader</a></p>
<p>I've tried building a method that reads an <strong>XLS</strong> file and converts it to string[]
But I get an error when trying to run it: <em>ExcelDataReader.Exceptions.HeaderException: Invalid file signature.</em></p>
<p>I have tried running it with <strong>XLSX</strong> and it works fine</p>
<p>The files that I am using have worked before</p>
<p>Note. I have run the same method that worked with XLS before, so I'm confused as to why this error is occurring.(using ExcelDataReader Version 3.6.0)</p>
<p>Here is the code:</p>
<pre><code>
private static List<string[]> GetExcelRecords(string path, bool hasHeaders)
{
var records = new List<string[]>();
using (var stream = File.Open(path, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var sheetFile = reader.AsDataSet().Tables[0];
for (int i = 0; i < sheetFile.Rows.Count; i++)
{
var record = sheetFile.Rows[i];
if (hasHeaders)
{
hasHeaders = false;
continue;
}
var row = record.ItemArray.Select(o => o.ToString()).ToArray();
records.Add(row);
}
}
}
return records;
}
</code></pre>
<p>The exception occurs on line 4</p>
<p>I have tried using ExcelReaderFactory.CreateBinaryReader and ExcelReaderFactory.CreateOpenXlmReader</p>
|
[
{
"answer_id": 74660351,
"author": "Satpal",
"author_id": 1668533,
"author_profile": "https://Stackoverflow.com/users/1668533",
"pm_score": 0,
"selected": false,
"text": "undefined every() var finalValue = this.recordData.myArray.length === 0 ?\n 'empty record' :\n (this.recordData.myArray.every((item: any) => item.stockKeepingStatus == 'A') ?\n 'found' :\n 'all are inactive');\n\nconsole.log(finalValue);"
},
{
"answer_id": 74660684,
"author": "Prashant Singh",
"author_id": 11170656,
"author_profile": "https://Stackoverflow.com/users/11170656",
"pm_score": 0,
"selected": false,
"text": "const strings = [\"Alpha\", \"Bravo\", \"Charlie\"];\n\nlet resultString = '';\n\nstrings.forEach(string => {\n if (string.startsWith('A')) {\n resultString = string;\n break;\n }\n});\n\nconsole.log(resultString); // 'Alpha'\n"
},
{
"answer_id": 74660947,
"author": "Thuti Navnaneeth Reddy",
"author_id": 16893554,
"author_profile": "https://Stackoverflow.com/users/16893554",
"pm_score": 1,
"selected": false,
"text": "find undefined const item = this.recordData.myArray.find((item: any) => item.stockKeepingStatus == 'A');\n\nconst finalValue = this.recordData.myArray.length === 0 ? 'empty record' : item ? 'found' : 'all are inactive';\n\nconsole.log(finalValue);\n\n"
},
{
"answer_id": 74660964,
"author": "Dmitry S.",
"author_id": 11008394,
"author_profile": "https://Stackoverflow.com/users/11008394",
"pm_score": 2,
"selected": true,
"text": "find forEach stockKeepingStatus undefined undefined const finalValue = this.recordData.myArray.length === 0\n ? 'empty record'\n : (this.recordData.myArray.find(item => item.stockKeepingStatus === 'A') ?\n 'found' : 'all are inactive'\n );\n\n\nconsole.log(finalValue);\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16889986/"
] |
74,660,274
|
<p>Kinda stuck here.</p>
<p>I am fetching data from database with php into this variable in javascript.</p>
<pre><code><?php
//connection to database
include("con.php");
//query
$query = "SELECT * FROM magacin_artikli";
$r = mysqli_query($conn, $query);
$dataGrafDodArt = array();
while($row = mysqli_fetch_array($r)){
$dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"];
}
//closing conn
$conn->close();
?>
</code></pre>
<pre><code>var oData = <?php echo json_encode($dataGrafDodArt);?>;
</code></pre>
<p>Output is:</p>
<pre class="lang-js prettyprint-override"><code>var oData = ["asd:2","asd:3","asd:2","ddd:3"];
</code></pre>
<p>And I need this to be formated like object array like this("asd":2), something like this inside variable:</p>
<p>Example output:</p>
<pre><code>var oData = {
"2008": 10,
"2009": 39.9,
"2010": 17,
"2011": 30.0,
"2012": 5.3,
"2013": 38.4,
"2014": 15.7,
"2015": 9.0
};
</code></pre>
<p>This is for animated graph which is taking parameters from Example output.</p>
<p>Any help would be good.</p>
<p>Tried a lot of things from array map to trimming the array and other stuff but none worked.</p>
|
[
{
"answer_id": 74660331,
"author": "Zeeshan ATS",
"author_id": 20669413,
"author_profile": "https://Stackoverflow.com/users/20669413",
"pm_score": -1,
"selected": false,
"text": "[\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n const jsonArray = [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n];\n\nconst objectArray = jsonArray.map(jsonObject => {\n return {\n name: jsonObject.name,\n age: jsonObject.age\n };\n});\n [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n"
},
{
"answer_id": 74660362,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": true,
"text": "$dataGrafDodArt[] = $row[\"art_naz\"]. \":\". $row[\"art_nabcena\"];\n $dataGrafDodArt[$row[\"art_naz\"]] = $row[\"art_nabcena\"];\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8431130/"
] |
74,660,283
|
<p>I am attempting to build a stopwatch Shiny app.</p>
<p>My end goal is to record "trial" times. Each trial will start when the space bar (key code == 32) is pressed, and will end when the space bar is released. I also want to record the time between my trials, which is time from when the space bar is released to when the space bar is pressed again.</p>
<p>I'd like to get the stopwatch to run continuously when the app is open. However, I want the stopwatch to reset to 0 when I press the space bar while continuing to count up in seconds while holding the space bar, and reset to 0 then start counting up again when I release the space bar.</p>
<p>Currently I am struggling to get my stopwatch (what I called <code>timer()</code>) to reset to 0 whenever I press spacebar or release it.</p>
<p>Below is the code I have tried.</p>
<pre><code>#install.packages("lubdridate")
#install.packages("shiny")
library(lubridate)
library(shiny)
ui <- fluidPage(hr(),
tags$script('
$(document).on("keydown", function (e) {
Shiny.onInputChange("space_down", e.which == 32);
});'
),
## keyup
tags$script('
$(document).on("keyup", function (e) {
Shiny.onInputChange("space_released", e.which == 32);
});'
),
tags$hr(),
textOutput('stopwatch')
)
server <- function(input, output, session) {
# Initialize the stopwatch, timer starts when shiny app opens.
timer <- reactiveVal(0)
update_interval = 0.01 # each interval increases the timer by one hundrendth of a second
# Output the stopwatch.
output$stopwatch <- renderText({
paste("Time passed: ", seconds_to_period(timer()))
})
# observer that invalidates every second. Increases timer by one update_interval.
observe({
invalidateLater(10, session)
isolate({
timer(round(timer()+update_interval,2))
})
})
# observers for Keys == 32 (Spacebar)
observeEvent(input$space_down, {timer(0)})
observeEvent(input$space_released, {timer(0)})
}
shinyApp(ui, server)
</code></pre>
<p>Please let me know if I am need to be more specific. Thank you in advance!</p>
|
[
{
"answer_id": 74660331,
"author": "Zeeshan ATS",
"author_id": 20669413,
"author_profile": "https://Stackoverflow.com/users/20669413",
"pm_score": -1,
"selected": false,
"text": "[\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n const jsonArray = [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n];\n\nconst objectArray = jsonArray.map(jsonObject => {\n return {\n name: jsonObject.name,\n age: jsonObject.age\n };\n});\n [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n"
},
{
"answer_id": 74660362,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": true,
"text": "$dataGrafDodArt[] = $row[\"art_naz\"]. \":\". $row[\"art_nabcena\"];\n $dataGrafDodArt[$row[\"art_naz\"]] = $row[\"art_nabcena\"];\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20669225/"
] |
74,660,327
|
<p>I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SECONDS, but what I want to achieve is to set maximum time of input to 5 seconds so if a user types an answer in let's say 2 seconds he will go the next word. Could you tell me the way to achieve my goal. Thanks in advance!</p>
<pre><code>
for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
# User gets maximum of 5 seconds to write the word,
# if he does it before 5 seconds pass ,he goes to next word (does not have to wait exactly 5 seconds, he
# can send input in e.g 2 seconds)
# if he does not do it in 5 seconds he loses game and it is finished
user_input = input(f"Type word '{word}': ")
#IF the word is correct go to next iteration
if(user_input==word):
continue
#If the word is incorrect finish the game
else:
print("You lost")
break
</code></pre>
<h1>I tried to do it with threading.Timer() but it doesn't work</h1>
<pre><code>import threading
class NoTime(Exception):
pass
def count_time():
raise NoTime
for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
try:
#Create timer which raises exception after 5 seconds
timer = threading.Timer(5,count_time)
timer.start()
user_input = input(f"Type word '{word}': ")
#if timer hasn't lasted 5 seconds then destroy it in order to prevent unwanted exception
timer.cancel()
if user_input==word:
print("Correct")
else:
print("Incorrect, you LOSE!")
break
except NoTime:
print("You run out of time, you lose")
break
</code></pre>
<h1>The error i get</h1>
<pre><code>Traceback (most recent call last):
File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1394, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\papit\OneDrive\Pulpit\Programming\Python Bro Course\Math\second\threading_training.py", line 7, in count_time
raise NoTime
NoTime
</code></pre>
|
[
{
"answer_id": 74660331,
"author": "Zeeshan ATS",
"author_id": 20669413,
"author_profile": "https://Stackoverflow.com/users/20669413",
"pm_score": -1,
"selected": false,
"text": "[\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n const jsonArray = [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n];\n\nconst objectArray = jsonArray.map(jsonObject => {\n return {\n name: jsonObject.name,\n age: jsonObject.age\n };\n});\n [\n { \"name\": \"John Doe\", \"age\": 30 },\n { \"name\": \"Jane Doe\", \"age\": 25 }\n]\n"
},
{
"answer_id": 74660362,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": true,
"text": "$dataGrafDodArt[] = $row[\"art_naz\"]. \":\". $row[\"art_nabcena\"];\n $dataGrafDodArt[$row[\"art_naz\"]] = $row[\"art_nabcena\"];\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12786471/"
] |
74,660,328
|
<pre><code> dictionary = testEns(idSession)
columns = dictionary.keys()
for i in dictionary.values():
sql2='''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i)
cursor.execute(sql2)
</code></pre>
<p>The function testEns(idSession) contains the result of an api call that returns an xml response that has been transformed into a dictionary.</p>
<p>i'm trying to insert the response into a table that have been created in a postgres database but here is the error i'm getting. Any idea why? and what am i missing?</p>
<pre><code>psycopg2.errors.SyntaxError: syntax error at or near "{"
LINE1: ...nsert into PERSONS(person_id, person_name) VALUES{'category...
</code></pre>
<p>After I changed VALUES{id, name} to VALUES(id, name)</p>
<p>I have this error</p>
<pre><code>psycopg2.errors.UndefinedColumn: column "id" does not exist
LINE 1: ...sert into PERSONS(person_id , person_name) VALUES(id, name)
</code></pre>
<p>eve though my table PERSONS is created in pgadmin with the columns id and name</p>
|
[
{
"answer_id": 74660378,
"author": "Frederik Bruun",
"author_id": 6172247,
"author_profile": "https://Stackoverflow.com/users/6172247",
"pm_score": -1,
"selected": false,
"text": "sql2 = '''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i)\n sql2 = '''INSERT INTO PERSONS (person_id, person_name) VALUES (value1, value2, ...)'''.format(i)\n"
},
{
"answer_id": 74660424,
"author": "HasaniH",
"author_id": 7141,
"author_profile": "https://Stackoverflow.com/users/7141",
"pm_score": 0,
"selected": false,
"text": "sql2='''insert into PERSONS (person_id , person_name) VALUES (%s, %s);'''\ncursor.execute(sql2, (i.person_id, i.person_name))\n i"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13435513/"
] |
74,660,360
|
<p>I have two files and want to transfer date from one to other after doing a test</p>
<p>File1:</p>
<pre><code>ID, X1, X2, X3
2000, 1, 2, 3
2001, 3, 4, 5
1999, 2, 5, 6
2003, 3, 5, 4
</code></pre>
<p>File2:</p>
<pre><code>ID, X1, X2, X3,
2000,
2001,
2002,
2003,
</code></pre>
<p>Result file will be like:</p>
<p>1999 "There is an error"</p>
<p>File2:</p>
<pre><code>ID, X1, X2, X3
2000, 1, 2, 3
2001, 3, 4, 5
2002, Na, Na, Na
2003, 3, 5, 4
</code></pre>
<p>I tried to use for loop with if, Unfortunately, it doesn't work:</p>
<pre><code>for(j in length(1: nrows(file1){
for(i in length(1: nrows(file2){
if( file1&ID[j]>= file2&ID[j+1]){
print(j, ' wrong value')
esle
file2[i,]<- file1[j,]
break
</code></pre>
<p>It would be very nice if I can get some ideas, codes how I can get something similar to result file</p>
<p>I hope I can find the right code to solve this problem</p>
|
[
{
"answer_id": 74660482,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 1,
"selected": false,
"text": "right_join df1 %>% \n right_join(df2, by=\"ID\") %>% \n arrange(ID)\n ID X1 X2 X3\n1 2000 1 2 3\n2 2001 3 4 5\n3 2002 NA NA NA\n4 2003 3 5 4\n df1 <- structure(list(ID = c(2000L, 2001L, 1999L, 2003L), X1 = c(1L, \n3L, 2L, 3L), X2 = c(2L, 4L, 5L, 5L), X3 = c(3L, 5L, 6L, 4L)), class = \"data.frame\", row.names = c(NA, \n-4L))\n\ndf2 <- structure(list(ID = 2000:2003), class = \"data.frame\", row.names = c(NA, \n-4L))\n"
},
{
"answer_id": 74660543,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "data.table library(data.table)\nsetDT(df2)[df1, names(df1)[-1] := mget(paste0(\"i.\", names(df1)[-1])), on = .(ID)]\n > df2\n ID X1 X2 X3\n1: 2000 1 2 3\n2: 2001 3 4 5\n3: 2002 NA NA NA\n4: 2003 3 5 4\n"
},
{
"answer_id": 74660916,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 0,
"selected": false,
"text": "coalesce_by_column <- function(df) {\n return(coalesce(df[1], df[2]))\n}\n\nbind_rows(df1, df2) %>% \n group_by(ID) %>%\n summarise_all(coalesce_by_column)\n ID X1 X2 X3\n <int> <int> <int> <int>\n1 1999 2 5 6\n2 2000 1 2 3\n3 2001 3 4 5\n4 2002 NA NA NA\n5 2003 3 5 4\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20624987/"
] |
74,660,368
|
<p>I am learning about layout constraints and find it a bit confusing why the last line of NSLayout Constraints for the trailing anchor mentions a view instead of loginView? Is there any good logical way to think of this? Struggling to imagine what is written.</p>
<pre><code>let loginView = LoginView()
view.addSubview(loginView)
NSLayoutConstraint.activate([
loginView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
loginView.leadingAnchor.constraint(equalToSystemSpacingAfter: view.leadingAnchor, multiplier: 1),
view.trailingAnchor.constraint(equalToSystemSpacingAfter: loginView.trailingAnchor, multiplier: 1)
])
</code></pre>
|
[
{
"answer_id": 74660495,
"author": "hallux",
"author_id": 14128044,
"author_profile": "https://Stackoverflow.com/users/14128044",
"pm_score": 0,
"selected": false,
"text": "loginView view.trailingAnchor loginView loginView loginView loginView"
},
{
"answer_id": 74660554,
"author": "matt",
"author_id": 341994,
"author_profile": "https://Stackoverflow.com/users/341994",
"pm_score": 0,
"selected": false,
"text": "view self.view loginView loginView loginView self.view"
},
{
"answer_id": 74661772,
"author": "DonMag",
"author_id": 6257435,
"author_profile": "https://Stackoverflow.com/users/6257435",
"pm_score": 2,
"selected": false,
"text": "loginView.leadingAnchor.constraint(...)\n view.trailingAnchor.constraint(...)\n NSLayoutConstraint.activate([\n\n loginView.heightAnchor.constraint(equalToConstant: 120.0),\n loginView.centerYAnchor.constraint(equalTo: view.centerYAnchor),\n\n loginView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0),\n\n loginView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8.0),\n \n])\n NSLayoutConstraint.activate([\n \n loginView.heightAnchor.constraint(equalToConstant: 120.0),\n loginView.centerYAnchor.constraint(equalTo: view.centerYAnchor),\n \n loginView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0),\n\n view.trailingAnchor.constraint(equalTo: loginView.trailingAnchor, constant: 8.0),\n \n])\n loginView view equalToSystemSpacingAfter equalToSystemSpacingBelow equalToSystemSpacingBefore equalToSystemSpacingAbove NSLayoutConstraint.activate([\n \n loginView.centerYAnchor.constraint(equalTo: view.centerYAnchor),\n loginView.heightAnchor.constraint(equalToConstant: 120.0),\n \n loginView.leadingAnchor.constraint(equalToSystemSpacingAfter: view.leadingAnchor, multiplier: 1),\n view.trailingAnchor.constraint(equalToSystemSpacingAfter: loginView.trailingAnchor, multiplier: 1),\n \n])\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20372651/"
] |
74,660,374
|
<p>I have to convert 2022-11-29 to '2022-11-29T04:00:00.000Z' it is offset for Santo Domingo Timezone.</p>
<p>But the first problem StartFromUtc is already '2022-11-29T02:00:00+02:00' but I expected '2022-11-29T00:00:00+00:00'.</p>
<p>so the next calculation is wrong too.</p>
<p>How can help?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const tz = 'America/Santo_Domingo';
const startFromDate = '2022-11-29';
const utcdate = dayjs(startFromDate + 'T00:00:00.000Z');
const tzdate = utcdate.tz(tz);
const utcFromTzdate = utcdate.tz(tz);
console.log(
'StartFrom: ', startFromDate,
'\nStartFromUtc: ', utcdate.format(),
'\nCreated UTC: ', utcdate.toISOString(),
'\nSanto Domingo:', tzdate.format(),
'\nUTC For Santo Domingo:', utcFromTzdate.format(),
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/timezone.js"></script>
<script>
dayjs.extend(window.dayjs_plugin_utc);
dayjs.extend(window.dayjs_plugin_timezone);
</script></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74660483,
"author": "MrAusnadian",
"author_id": 14635109,
"author_profile": "https://Stackoverflow.com/users/14635109",
"pm_score": 0,
"selected": false,
"text": "const tz = 'America/Santo_Domingo';\nconst startFromDate = dayjs(new Date('2022-11-29 UTC'));\nconst tzdate = startFromDate.tz(tz);\nconst utcFromTzdate = startFromDate.tz('UTC');\n\nconsole.log(\n 'StartFrom: ', startFromDate, \n '\\nStartFromUtc: ', startFromDate.format(), \n '\\nCreated UTC: ', startFromDate.toISOString(), \n '\\nSanto Domingo:', tzdate.format(),\n '\\nUTC from Santo Domingo:', utcFromTzdate.format(),\n); <script src=\"https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/dayjs@1/plugin/timezone.js\"></script>\n<script>\n dayjs.extend(window.dayjs_plugin_utc);\n dayjs.extend(window.dayjs_plugin_timezone); \n</script>"
},
{
"answer_id": 74666234,
"author": "RobG",
"author_id": 257182,
"author_profile": "https://Stackoverflow.com/users/257182",
"pm_score": 3,
"selected": true,
"text": "dayjs(startFromDate);\n let tzdate = dayjs(startFromDate).tz(tz, true)\n let utc = tzdate.tz('UTC')\n const tz = 'America/Santo_Domingo';\nconst startFromDate = '2022-11-29';\nlet tzdate = dayjs(startFromDate).tz(tz, true);\nlet utc = tzdate.tz('UTC');\n\nconsole.log(\n 'StartFrom : ', startFromDate, \n '\\nSanto Domingo :', tzdate.format(),\n '\\nUTC eqiuvalent:', utc.format(),\n); <script src=\"https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/dayjs@1/plugin/timezone.js\"></script>\n<script>\n dayjs.extend(window.dayjs_plugin_utc);\n dayjs.extend(window.dayjs_plugin_timezone); \n</script>"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450466/"
] |
74,660,417
|
<p>I'm trying to compare 2 csv files and then put the common entries in a 3rd csv to write to file. For some reason it iterates the whole loop for row in csv_input but the entry in csv_compare loop iterates only once and stops on the last entry. I want to compare every row entry with every entry entry.</p>
<pre><code>import csv
finalCSV = {}
with open('input.csv', newline='') as csvfile, open('compare.csv', newline='') as keyCSVFile, open('output.csv', 'w' ,newline='') as OutputCSV:
csv_input = csv.reader(csvfile)
csv_compare = csv.reader(keyCSVFile)
csv_output = csv.writer(OutputCSV)
csv_output.writerow(next(csv_input))
for row in csv_input:
for entry in csv_compare:
print(row[0] + ' ' + entry[0])
if row[0] == entry[0]:
csv_output.writerow(row)
break
print('wait...')
</code></pre>
|
[
{
"answer_id": 74660466,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 0,
"selected": false,
"text": "csv_compare import csv\n\nfinalCSV = {}\nwith open(\"input.csv\", newline=\"\") as csvfile, open(\n \"compare.csv\", newline=\"\"\n) as keyCSVFile, open(\"output.csv\", \"w\", newline=\"\") as OutputCSV:\n csv_input = csv.reader(csvfile)\n csv_compare = csv.reader(keyCSVFile)\n csv_output = csv.writer(OutputCSV)\n csv_output.writerow(next(csv_input))\n\n compare = {entry[0] for entry in csv_compare} # <--- read csv_compare to a set\n\n for row in csv_input:\n if row[0] in compare: # <--- use `in` operator\n csv_output.writerow(row)\n"
},
{
"answer_id": 74660471,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "csv_compare with open('input.csv', newline='') as csvfile, open('output.csv', 'w' ,newline='') as OutputCSV:\n csv_input = csv.reader(csvfile)\n csv_output = csv.writer(OutputCSV)\n csv_output.writerow(next(csv_input))\n\n for row in csv_input:\n with open('compare.csv', newline='') as keyCSVFile:\n csv_compare = csv.reader(keyCSVFile)\n for entry in csv_compare:\n if row[0] == entry[0]:\n csv_output.writerow(row)\n break\n"
},
{
"answer_id": 74660630,
"author": "tdelaney",
"author_id": 642070,
"author_profile": "https://Stackoverflow.com/users/642070",
"pm_score": 0,
"selected": false,
"text": "input.csv compare.csv import csv\n\nwith open('compare.csv', newline='') as keyCSVFile:\n key_set = {row[0] for row in csv.reader(keyCSVFile)}\n\nwith open('input.csv', newline='') as csvfile, open('output.csv', 'w' ,newline='') as OutputCSV:\n csv_input = csv.reader(csvfile)\n csv_output = csv.writer(OutputCSV)\n csv_output.writerow(next(csv_input))\n csv_output.writerows(row for row in csv_input if row[0] in key_set)\n\ndel key_set\nprint('wait...')\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373439/"
] |
74,660,418
|
<p>I would like to have instead of only the vector of optimal solution to a mip , all the feasible (suboptimal) vectors.<br />
I found some old questions here, but I am not sure how they work.</p>
<p>First of all, is there any new library tool/way to do that automatically ?<br />
I tried this but, it did nothing:</p>
<pre><code>if termination_status(m) == MOI.FEASIBLE_POINT
println(x)
end
optimize!(m);
</code></pre>
<p>If not, what's the easiest way?<br />
I thought of scanning the optimal solution till I find the first non -zero decision variable, then constraint this variable to be zero and solving the model again.</p>
<pre><code>for i in 1:active_variables
if value.(z[i])==1
@constraint(m, x[i] == 0)
break
end
end
optimize!(m);
</code></pre>
<p>But I see this problem with this method** :</p>
<ol>
<li>Ιf I constraint x[i] to be zero, in the next step I will want maybe to drop again this constraint? This comes down to whether there can exist two(or more) different solutions in which <code>x[i]==1</code></li>
</ol>
<hr />
|
[
{
"answer_id": 74661407,
"author": "Oscar Dowson",
"author_id": 13591160,
"author_profile": "https://Stackoverflow.com/users/13591160",
"pm_score": 2,
"selected": false,
"text": "using JuMP\nmodel = Model()\n@variable(model, x[1:10] >= 0)\n# ... other constraints ...\noptimize!(model)\n\nif termination_status(model) != OPTIMAL\n error(\"The model was not solved correctly.\")\nend\n\nan_optimal_solution = value.(x; result = 1)\noptimal_objective = objective_value(model; result = 1)\nfor i in 2:result_count(model)\n @assert has_values(model; result = i)\n println(\"Solution $(i) = \", value.(x; result = i))\n obj = objective_value(model; result = i)\n println(\"Objective $(i) = \", obj)\n if isapprox(obj, optimal_objective; atol = 1e-8)\n print(\"Solution $(i) is also optimal!\")\n end\nend\n"
},
{
"answer_id": 74671987,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 3,
"selected": true,
"text": "using Random, JuMP, HiGHS, MathOptInterface\n\nfunction example_knapsack()\n profit = [5, 3, 2, 7, 4]\n weight = [2, 8, 4, 2, 5]\n capacity = 10\n minprofit = 10\n model = Model(HiGHS.Optimizer)\n set_silent(model)\n @variable(model, x[1:5], Bin)\n @objective(model, FEASIBILITY_SENSE, 0)\n @constraint(model, weight' * x <= capacity)\n @constraint(model, profit' * x >= minprofit)\n return model\nend\n function findallsol(model, x)\n perm = shuffle(1:length(x))\n res = Vector{Float64}[]\n _findallsol!(res, model, x, perm, 0)\n return res\nend\n\nfunction _findallsol!(res, model, x, perm, depth)\n n = length(x)\n depth > n && return\n optimize!(model)\n if termination_status(model) == MathOptInterface.OPTIMAL\n if depth == n\n push!(res, value.(x))\n return\n else\n idx = perm[depth+1]\n v = value(x[idx])\n newcon = @constraint(model, x[idx] == v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n newcon = @constraint(model, x[idx] == 1 - v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n end\n end\n return\nend\n julia> m = example_knapsack()\nA JuMP Model\nMaximization problem with:\nVariables: 5\n...\nNames registered in the model: x\n\njulia> res = findallsol(m, m.obj_dict[:x])\n5-element Vector{Vector{Float64}}:\n [1.0, 0.0, 0.0, 1.0, 1.0]\n [0.0, 0.0, 0.0, 1.0, 1.0]\n [1.0, 0.0, 1.0, 1.0, 0.0]\n [1.0, 0.0, 0.0, 1.0, 0.0]\n [0.0, 1.0, 0.0, 1.0, 0.0]\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14386149/"
] |
74,660,427
|
<p><strong>Problem</strong>: Our company receives a data set that summarizes invoices to be paid.
For each outstanding invoice, there is a single row of data.
Each invoice has a variable number of items to be paid and are listed on the same row.
Each item has four columns listed on the invoice row.
As a result, the number of columns per invoice can become unwieldy.</p>
<p>We need to <em>upload this data with one row per item</em> and it currently requires an accounting clerk to manually copy/paste each item to a new row.</p>
<p><strong>Request</strong>: Please help me find a way to copy every item (four columns) and paste to a new row with the invoice listed first.</p>
<p><strong>Attachments</strong>:
"RAW" Worksheet is the original data.</p>
<ul>
<li>Columns A-D, highlighted in Gray are the invoice detail.</li>
<li>Columns J-M highlighted in Orange are the first item, Columns N-Q highlighted in Blue are the second item, etc.
<a href="https://i.stack.imgur.com/DJ8rH.png" rel="nofollow noreferrer">"RAW" Screenshot</a></li>
</ul>
<p>"Output" Worksheet is the desired outcome (currently done by manually copy/paste)</p>
<p><a href="https://i.stack.imgur.com/eKpHj.png" rel="nofollow noreferrer">"Output" Screenshot</a></p>
<p><a href="https://docs.google.com/spreadsheets/d/1Cq4XB89gG9qG0Wi3x21EeU1lBgEpWiHH/edit?usp=sharing&ouid=111142850540123360382&rtpof=true&sd=true" rel="nofollow noreferrer">Link to Google Doc for data</a></p>
<p><strong>Attempts:</strong>
I am a fairly inexperienced Excel user, but I tried a series of if/then, transpositions, pivots, and Offsets with no success.</p>
<p>I think that this problem requires a VBA that reviews each row and identifies</p>
<ol>
<li>if there is a non-zero four column item. For each non-zero four column item, it will paste the invoice summary (columns A-D) and the non-zero item (ex. columns J-M) on a new row.</li>
<li>If there is a zero-value four column item, the VBA will move to the next row (invoice).</li>
</ol>
<p>That is my best guess, and I haven't a clue how to script this VBA.
Thanks for any insight here!!</p>
|
[
{
"answer_id": 74661407,
"author": "Oscar Dowson",
"author_id": 13591160,
"author_profile": "https://Stackoverflow.com/users/13591160",
"pm_score": 2,
"selected": false,
"text": "using JuMP\nmodel = Model()\n@variable(model, x[1:10] >= 0)\n# ... other constraints ...\noptimize!(model)\n\nif termination_status(model) != OPTIMAL\n error(\"The model was not solved correctly.\")\nend\n\nan_optimal_solution = value.(x; result = 1)\noptimal_objective = objective_value(model; result = 1)\nfor i in 2:result_count(model)\n @assert has_values(model; result = i)\n println(\"Solution $(i) = \", value.(x; result = i))\n obj = objective_value(model; result = i)\n println(\"Objective $(i) = \", obj)\n if isapprox(obj, optimal_objective; atol = 1e-8)\n print(\"Solution $(i) is also optimal!\")\n end\nend\n"
},
{
"answer_id": 74671987,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 3,
"selected": true,
"text": "using Random, JuMP, HiGHS, MathOptInterface\n\nfunction example_knapsack()\n profit = [5, 3, 2, 7, 4]\n weight = [2, 8, 4, 2, 5]\n capacity = 10\n minprofit = 10\n model = Model(HiGHS.Optimizer)\n set_silent(model)\n @variable(model, x[1:5], Bin)\n @objective(model, FEASIBILITY_SENSE, 0)\n @constraint(model, weight' * x <= capacity)\n @constraint(model, profit' * x >= minprofit)\n return model\nend\n function findallsol(model, x)\n perm = shuffle(1:length(x))\n res = Vector{Float64}[]\n _findallsol!(res, model, x, perm, 0)\n return res\nend\n\nfunction _findallsol!(res, model, x, perm, depth)\n n = length(x)\n depth > n && return\n optimize!(model)\n if termination_status(model) == MathOptInterface.OPTIMAL\n if depth == n\n push!(res, value.(x))\n return\n else\n idx = perm[depth+1]\n v = value(x[idx])\n newcon = @constraint(model, x[idx] == v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n newcon = @constraint(model, x[idx] == 1 - v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n end\n end\n return\nend\n julia> m = example_knapsack()\nA JuMP Model\nMaximization problem with:\nVariables: 5\n...\nNames registered in the model: x\n\njulia> res = findallsol(m, m.obj_dict[:x])\n5-element Vector{Vector{Float64}}:\n [1.0, 0.0, 0.0, 1.0, 1.0]\n [0.0, 0.0, 0.0, 1.0, 1.0]\n [1.0, 0.0, 1.0, 1.0, 0.0]\n [1.0, 0.0, 0.0, 1.0, 0.0]\n [0.0, 1.0, 0.0, 1.0, 0.0]\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20669255/"
] |
74,660,443
|
<p>I have to download a lot of data in mass from the internet, and I don't want this to crowd my main directory so much, so I like to move it to a /data folder. I make this data into a list, then move that entire list into that folder. However, I then struggle to do analyses with sapply() and other functions upon this entire list of files once it is located in the folder. I can't find any argument within sapply() that takes a path or anything, so I was wondering how I can get around this. Below is some code demonstrating this problem.</p>
<pre><code>library(dplyr)
library(fs)
mtcars %>% write.csv("data_1.csv")
DNase %>% write.csv("data_2.csv")
iris %>% write.csv("data_3.csv")
my_list <- list.files(pattern = "data_")
fs::file_move(my_list, new_path = "MYDIRECTORY/data")
sapply(my_list, read.csv)
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'data_1.csv': No such file or directory
</code></pre>
|
[
{
"answer_id": 74661407,
"author": "Oscar Dowson",
"author_id": 13591160,
"author_profile": "https://Stackoverflow.com/users/13591160",
"pm_score": 2,
"selected": false,
"text": "using JuMP\nmodel = Model()\n@variable(model, x[1:10] >= 0)\n# ... other constraints ...\noptimize!(model)\n\nif termination_status(model) != OPTIMAL\n error(\"The model was not solved correctly.\")\nend\n\nan_optimal_solution = value.(x; result = 1)\noptimal_objective = objective_value(model; result = 1)\nfor i in 2:result_count(model)\n @assert has_values(model; result = i)\n println(\"Solution $(i) = \", value.(x; result = i))\n obj = objective_value(model; result = i)\n println(\"Objective $(i) = \", obj)\n if isapprox(obj, optimal_objective; atol = 1e-8)\n print(\"Solution $(i) is also optimal!\")\n end\nend\n"
},
{
"answer_id": 74671987,
"author": "Dan Getz",
"author_id": 3580870,
"author_profile": "https://Stackoverflow.com/users/3580870",
"pm_score": 3,
"selected": true,
"text": "using Random, JuMP, HiGHS, MathOptInterface\n\nfunction example_knapsack()\n profit = [5, 3, 2, 7, 4]\n weight = [2, 8, 4, 2, 5]\n capacity = 10\n minprofit = 10\n model = Model(HiGHS.Optimizer)\n set_silent(model)\n @variable(model, x[1:5], Bin)\n @objective(model, FEASIBILITY_SENSE, 0)\n @constraint(model, weight' * x <= capacity)\n @constraint(model, profit' * x >= minprofit)\n return model\nend\n function findallsol(model, x)\n perm = shuffle(1:length(x))\n res = Vector{Float64}[]\n _findallsol!(res, model, x, perm, 0)\n return res\nend\n\nfunction _findallsol!(res, model, x, perm, depth)\n n = length(x)\n depth > n && return\n optimize!(model)\n if termination_status(model) == MathOptInterface.OPTIMAL\n if depth == n\n push!(res, value.(x))\n return\n else\n idx = perm[depth+1]\n v = value(x[idx])\n newcon = @constraint(model, x[idx] == v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n newcon = @constraint(model, x[idx] == 1 - v)\n _findallsol!(res, model, x, perm, depth + 1)\n delete(model, newcon)\n end\n end\n return\nend\n julia> m = example_knapsack()\nA JuMP Model\nMaximization problem with:\nVariables: 5\n...\nNames registered in the model: x\n\njulia> res = findallsol(m, m.obj_dict[:x])\n5-element Vector{Vector{Float64}}:\n [1.0, 0.0, 0.0, 1.0, 1.0]\n [0.0, 0.0, 0.0, 1.0, 1.0]\n [1.0, 0.0, 1.0, 1.0, 0.0]\n [1.0, 0.0, 0.0, 1.0, 0.0]\n [0.0, 1.0, 0.0, 1.0, 0.0]\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14306416/"
] |
74,660,475
|
<p><a href="https://i.stack.imgur.com/YmAkE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YmAkE.png" alt="HTML source:" /></a></p>
<p>How to create an array forEach of the playlist card ids and test to assert array positioning/order on the page ex. 0=130, 1=100 etc. in Cypress</p>
<p>I think I could use this slector, but unsure how create forEach array for it...</p>
<pre><code>data-object-type="playlists"
</code></pre>
<p>Test</p>
<pre><code>
it('verify expected order on program landing page', () =\> {
cy.visit(learnerLandingPage);
});
</code></pre>
<p>I only tried asserting against the number of playlist cards present which work as expected, but unsure how/if I can use the playlists <code>data-object-type</code></p>
<pre><code> cy.get('[data-object-type="playlists"]').should('have.length', 3);
</code></pre>
<p>Looking for the cleaneast way to accomplish with also being able to work across different environments where the ids in array will be different</p>
|
[
{
"answer_id": 74661041,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 2,
"selected": true,
"text": "data-object-type data-object-type const expectedOrder = [\"130\", \"100\", \"1\"];\ncy.get(\"[data-object-type]\")\n .should(\"have.length\", 3)\n // get array of data-object-type attr\n .then(($list) =>\n Cypress._.map($list, ($el) => $el.getAttribute(\"data-object-type\"))\n )\n .should(\"deep.equal\", expectedOrder);\n"
},
{
"answer_id": 74661567,
"author": "Ine Wilmann",
"author_id": 20659725,
"author_profile": "https://Stackoverflow.com/users/20659725",
"pm_score": 2,
"selected": false,
"text": "const order = ['130', '100' , '1']\n\ncy.get('[data-object-type=\"playlists\"]').each(($el, index) => {\n expect($el.attr('data-object-id')).to.eq(order[index])\n})\n $el.attr('data-object-id') .invoke() const order = ['130', '100' , '1']\n\ncy.get('[data-object-type=\"playlists\"]').each(($el, index) => {\n cy.wrap($el)\n .invoke('attr', 'data-object-id')\n .should('eq', order[index])\n})\n .should()"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4584966/"
] |
74,660,484
|
<p>I have dataframe that looks like this:</p>
<pre><code> email account_name
0 NaN weichert, realtors mnsota
1 jhawkins sterling group com sterling group
2 lbaltz baltzchevy com baltz chevrolet
</code></pre>
<p>and I have this code that works as a solution but it takes forever on larger datasets and I know there has to be an easier way to solve it so just looking to see if anyone knows of a more concise/elegant way to do find a count of matching words between corresponding rows of both columns. Thanks</p>
<pre><code>test = prod_nb_wcomps_2.sample(3, random_state=10).reset_index(drop = True)
test = test[['email','account_name']]
print(test)
lst = []
for i in test.index:
if not isinstance(test['email'].iloc[i], float):
for word in test['email'].iloc[i].split(' '):
if not isinstance(test['account_name'].iloc[i], float):
for word2 in test['account_name'].iloc[i].split(' '):
if word in word2:
lst.append({'index':i, 'bool_col': True})
else: lst.append({'index':i, 'bool_col': False})
df_dct = pd.DataFrame(lst)
df_dct = df_dct.loc[df_dct['bool_col'] == True]
df_dct['number of matches_per_row'] = df_dct.groupby('index')['bool_col'].transform('size')
df_dct.set_index('index', inplace=True, drop=True)
df_dct.drop(['bool_col'], inplace=True, axis =1)
test_ = pd.merge(test, df_dct, left_index=True, right_index=True)
test_
</code></pre>
<p>the resulting dataframe <code>test_</code> looks like this</p>
<p><a href="https://i.stack.imgur.com/ivXGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ivXGm.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74661041,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 2,
"selected": true,
"text": "data-object-type data-object-type const expectedOrder = [\"130\", \"100\", \"1\"];\ncy.get(\"[data-object-type]\")\n .should(\"have.length\", 3)\n // get array of data-object-type attr\n .then(($list) =>\n Cypress._.map($list, ($el) => $el.getAttribute(\"data-object-type\"))\n )\n .should(\"deep.equal\", expectedOrder);\n"
},
{
"answer_id": 74661567,
"author": "Ine Wilmann",
"author_id": 20659725,
"author_profile": "https://Stackoverflow.com/users/20659725",
"pm_score": 2,
"selected": false,
"text": "const order = ['130', '100' , '1']\n\ncy.get('[data-object-type=\"playlists\"]').each(($el, index) => {\n expect($el.attr('data-object-id')).to.eq(order[index])\n})\n $el.attr('data-object-id') .invoke() const order = ['130', '100' , '1']\n\ncy.get('[data-object-type=\"playlists\"]').each(($el, index) => {\n cy.wrap($el)\n .invoke('attr', 'data-object-id')\n .should('eq', order[index])\n})\n .should()"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13530377/"
] |
74,660,492
|
<p>I am new to coding and i can't figure out a way to convert this pseudocode to actual code in python especially the total number of dice part.
I want to calculate total number of green dice in a dice stack of different colours.</p>
<pre><code>Y4 G6
R3 G2
W2 W1
</code></pre>
<pre><code>where,
Y4 = yellow dice with face value 4
R3 = red dice with face value 2
W2 = white dice with face value 2
G6 = green dice with face value 6
G2 = green dice with face value 2
W1 = white dice with face value 1
</code></pre>
<pre><code>score = 0
if total number of green dice is 1
score = 2
if total number of green dice is 2
score = 5
if total number of green dice is 3
score = 10
if total number of green dice is 4
score = 15
if total number of green dice is 5
score = 20
if total number of green dice is 6
score = 30
return score
</code></pre>
|
[
{
"answer_id": 74660567,
"author": "twister_void",
"author_id": 637377,
"author_profile": "https://Stackoverflow.com/users/637377",
"pm_score": -1,
"selected": false,
"text": "class Dice(object):\n\n def __init__(self, dice_list):\n self.dice_list = dice_list\n\n def score(self):\n total_number_of_dice = 0\n for dice in self.dice_list:\n total_number_of_dice = total_number_of_dice + dice\n if total_number_of_dice == 1:\n return 2\n if total_number_of_dice == 2:\n return 5\n if total_number_of_dice == 3:\n return 10\n if total_number_of_dice == 4:\n return 15\n if total_number_of_dice == 5:\n return 20\n if total_number_of_dice == 6:\n return 30\n return 0\n"
},
{
"answer_id": 74661028,
"author": "John B.",
"author_id": 19814518,
"author_profile": "https://Stackoverflow.com/users/19814518",
"pm_score": 0,
"selected": false,
"text": "Underscore example: new_member\nCamel case example: newMember\n if variable1 condition variable2:\n if new_member condition variable2:\n if new_member == variable2:\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n def my_func():\n def newcomer_greeting():\n def newcomer_greeting(new_member):\n def newcomer_greeting(new_member):\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n\n return\n def newcomer_greeting(new_member):\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n\n return\n\nnew_member = 'High_spectre1408'\nnewcomer_greeting(new_member)\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20436221/"
] |
74,660,537
|
<p>I work with Sales and problem is that this table does not have records for each client for every year. Records are missing randomly. Instead i need to have those years there and put 0 for sales for those years for my analysis.</p>
<p>I have limited knowledge of SQL. Can anybody help on this one? What i have as of now and what i would like to have is shown below.</p>
<p>I have thoughts to use LAG() function, but missing records can be for 2 years in a row or 3. I am not sure how to tackle such problem.</p>
<p>What I have now:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Client_ID</th>
<th style="text-align: right;">SalesYear</th>
<th style="text-align: right;">Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td style="text-align: right;">2010</td>
<td style="text-align: right;">12</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2012</td>
<td style="text-align: right;">20</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2013</td>
<td style="text-align: right;">21</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2016</td>
<td style="text-align: right;">14</td>
</tr>
</tbody>
</table>
</div>
<p>What i need to have:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Client_ID</th>
<th style="text-align: right;">SalesYear</th>
<th style="text-align: right;">Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td style="text-align: right;">2010</td>
<td style="text-align: right;">12</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2011</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2012</td>
<td style="text-align: right;">20</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2013</td>
<td style="text-align: right;">21</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2014</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2015</td>
<td style="text-align: right;">0</td>
</tr>
<tr>
<td>1</td>
<td style="text-align: right;">2016</td>
<td style="text-align: right;">14</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74660567,
"author": "twister_void",
"author_id": 637377,
"author_profile": "https://Stackoverflow.com/users/637377",
"pm_score": -1,
"selected": false,
"text": "class Dice(object):\n\n def __init__(self, dice_list):\n self.dice_list = dice_list\n\n def score(self):\n total_number_of_dice = 0\n for dice in self.dice_list:\n total_number_of_dice = total_number_of_dice + dice\n if total_number_of_dice == 1:\n return 2\n if total_number_of_dice == 2:\n return 5\n if total_number_of_dice == 3:\n return 10\n if total_number_of_dice == 4:\n return 15\n if total_number_of_dice == 5:\n return 20\n if total_number_of_dice == 6:\n return 30\n return 0\n"
},
{
"answer_id": 74661028,
"author": "John B.",
"author_id": 19814518,
"author_profile": "https://Stackoverflow.com/users/19814518",
"pm_score": 0,
"selected": false,
"text": "Underscore example: new_member\nCamel case example: newMember\n if variable1 condition variable2:\n if new_member condition variable2:\n if new_member == variable2:\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n def my_func():\n def newcomer_greeting():\n def newcomer_greeting(new_member):\n def newcomer_greeting(new_member):\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n\n return\n def newcomer_greeting(new_member):\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n\n return\n\nnew_member = 'High_spectre1408'\nnewcomer_greeting(new_member)\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20584166/"
] |
74,660,556
|
<p>I'm trying to convert the dates inside a JSON file to their respective quarter and year. My JSON file is formatted below:</p>
<pre><code>{
"lastDate": {
"0": "11/22/2022",
"1": "10/28/2022",
"2": "10/17/2022",
"7": "07/03/2022",
"8": "07/03/2022",
"9": "06/03/2022",
"18": "05/17/2022",
"19": "05/08/2022",
"22": "02/03/2022",
"24": "02/04/2022"
}
}
</code></pre>
<p>The current code I'm using is an attempt of using the <code>pandas.Series.dt.quarter</code> as seen below:</p>
<pre><code>import json
import pandas as pd
data = json.load(open("date_to_quarters.json"))
df = data['lastDate']
pd.to_datetime(df['lastDate'])
df['Quarter'] = df['Date'].dt.quarter
open("date_to_quarters.json", "w").write(
json.dumps(data, indent=4))
</code></pre>
<p>The issue I face is that my code isn't comprehending the object name "lastDate". My ideal output should have the dates ultimately replaced into their quarter, check below:</p>
<pre><code>{
"lastDate": {
"0": "Q42022",
"1": "Q42022",
"2": "Q42022",
"7": "Q32022",
"8": "Q32022",
"9": "Q22022",
"18": "Q22022",
"19": "Q22022",
"22": "Q12022",
"24": "Q12022"
}
}
</code></pre>
|
[
{
"answer_id": 74660567,
"author": "twister_void",
"author_id": 637377,
"author_profile": "https://Stackoverflow.com/users/637377",
"pm_score": -1,
"selected": false,
"text": "class Dice(object):\n\n def __init__(self, dice_list):\n self.dice_list = dice_list\n\n def score(self):\n total_number_of_dice = 0\n for dice in self.dice_list:\n total_number_of_dice = total_number_of_dice + dice\n if total_number_of_dice == 1:\n return 2\n if total_number_of_dice == 2:\n return 5\n if total_number_of_dice == 3:\n return 10\n if total_number_of_dice == 4:\n return 15\n if total_number_of_dice == 5:\n return 20\n if total_number_of_dice == 6:\n return 30\n return 0\n"
},
{
"answer_id": 74661028,
"author": "John B.",
"author_id": 19814518,
"author_profile": "https://Stackoverflow.com/users/19814518",
"pm_score": 0,
"selected": false,
"text": "Underscore example: new_member\nCamel case example: newMember\n if variable1 condition variable2:\n if new_member condition variable2:\n if new_member == variable2:\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n def my_func():\n def newcomer_greeting():\n def newcomer_greeting(new_member):\n def newcomer_greeting(new_member):\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n\n return\n def newcomer_greeting(new_member):\n if new_member == 'High_spectre1408':\n print('Welcome to the community!')\n\n return\n\nnew_member = 'High_spectre1408'\nnewcomer_greeting(new_member)\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18823431/"
] |
74,660,579
|
<p>I'm working with a REST API, and I need to return a <code>JSON</code> with my values to it. However, I need the <code>items</code> of the payload variable to show all the items inside the <code>cart_item</code>.</p>
<p>I have this:</p>
<pre class="lang-py prettyprint-override"><code>payload = {
"items": [],
}
</code></pre>
<p>I tried this, but I don't know how I would put this inside the <code>items</code> of the payload:</p>
<pre class="lang-py prettyprint-override"><code>for cart_item in cart_items:
item = [
{
"reference_id": f"{cart_item.sku}",
"name": f"{cart_item.product.name}",
"quantity": cart_item.quantity,
"unit_amount": cart_item.product.price
},
]
</code></pre>
<p>I need you to get back to me:</p>
<pre><code>
payload = {
"items": [
{
"reference_id": "SKU49FS20DD",
"name": "Produto 1",
"quantity": 1,
"unit_amount": 130
},
{
"reference_id": "SKU42920SSD",
"name": "Produto 2",
"quantity": 1,
"unit_amount": 100
}
],
}
response = requests.request(
"POST",
url,
headers=headers,
json=payload
)
</code></pre>
<p>I don't know if I would need to pass what's in <code>JSON</code> to the dictionary to change and then send it to <code>JSON</code> again.</p>
|
[
{
"answer_id": 74660660,
"author": "Sarah Messer",
"author_id": 2112722,
"author_profile": "https://Stackoverflow.com/users/2112722",
"pm_score": 1,
"selected": true,
"text": " from json import dumps\n\n items_dict = []\n for cart_item in cart_items:\n items_dict.append({\n \"reference_id\": f\"{cart_item.sku}\",\n \"name\": f\"{cart_item.product.name}\",\n \"quantity\": cart_item.quantity,\n \"unit_amount\": cart_item.product.price\n })\n\npayload = {\n 'items': items_dict\n}\n\n# And if you want a JSON string as output\nprint(dumps(payload))\n response = requests.request(\n \"POST\",\n url, \n headers=headers,\n json=payload\n)\n"
},
{
"answer_id": 74660731,
"author": "accdias",
"author_id": 6789321,
"author_profile": "https://Stackoverflow.com/users/6789321",
"pm_score": 1,
"selected": false,
"text": "payload['items'] payload['items'] = [\n {\n 'reference_id': cart_item.sku,\n 'name': cart_item.product.name,\n 'quantity': cart_item.quantity,\n 'unit_amount': cart_item.product.price \n }\n for cart_item in cart_items\n]\n requests requests.requests('POST' ...) requests.post(...) json JSON json.dumps import requests\nimport json\n\npayload['items'] = [\n {\n 'reference_id': cart_item.sku,\n 'name': cart_item.product.name,\n 'quantity': cart_item.quantity,\n 'unit_amount': cart_item.product.price \n }\n for cart_item in cart_items\n]\n\nresponse = requests.post(\n url,\n headers=headers,\n json=json.dumps(payload)\n)\n requests.post() payload json=payload"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19455169/"
] |
74,660,582
|
<p>Here's my function that returns the Sum of all pair numbers in an array, and the Average of Odd numbers. Although it outputs the Average as zero for some reason.</p>
<pre><code> #include <stdio.h>
int MoySom(int Tab[],float* Moyenne,int Length)
{
int S=0,C=0;
*Moyenne=0;
for(int i=0;i<Length;++i)
{
if(Tab[i] % 2 == 0)
{
S=S+Tab[i];
}
else if(Tab[i] % 2 != 0)
{
*Moyenne+=Tab[i];
++C;
}
}
*Moyenne=*Moyenne/C;
return S;
}
void main()
{
int Length,Tab[Length];
float Moyenne;
printf("Entrer la longeur de tableau: ");
scanf("%d",&Length);
for(int i=0;i<Length;++i)
{
printf("Entrer l'element %d: ",i);
scanf("%d",&Tab[i]);
}
printf("Somme est:%d\nMoyenne est: %.2f",
MoySom(Tab,&Moyenne,Length), Moyenne);
}
</code></pre>
|
[
{
"answer_id": 74660653,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": true,
"text": "int Length,Tab[Length]; Tab[Length] Length Tab[] Length int Length;\n float Moyenne;\n printf(\"Entrer la longeur de tableau: \");\n scanf(\"%d\",&Length);\n int Tab[Length];\n scanf() int cnt = scanf(\"%d\",&Length);\n if (cnt != 1 || Length <= 0) {\n Report_Error_and_exit();\n } \n int Tab[Length];\n Moyenne //printf(\"Somme est:%d\\nMoyenne est: %.2f\",\n// MoySom(Tab,&Moyenne,Length), Moyenne);\n\nprintf(\"Somme est:%d\\n\", MoySom(Tab,&Moyenne,Length));\nprintf(\"Moyenne est: %.2f\", Moyenne);\n *Moyenne=*Moyenne/C; if(Tab[i] % 2 == 0) {\n S=S+Tab[i];\n } else if(Tab[i] % 2 != 0) {\n *Moyenne+=Tab[i];\n if(Tab[i] % 2 == 0) {\n S=S+Tab[i];\n } else {\n *Moyenne+=Tab[i];\n"
},
{
"answer_id": 74660832,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint MoySom(int* Tab, float* Moyenne, int Length)\n{\n int S = 0, C = 0;\n *Moyenne = 0;\n for (int i = 0; i < Length; ++i)\n {\n if (Tab[i] % 2 == 0)\n {\n S = S + Tab[i];\n }\n else if (Tab[i] % 2 != 0)\n {\n *Moyenne += Tab[i];\n ++C;\n }\n }\n if (C > 0)\n {\n *Moyenne = *Moyenne / C;\n }\n return S;\n}\n\nvoid main()\n{\n int Length;\n float Moyenne;\n printf(\"Entrer la longeur de tableau: \");\n scanf(\"%d\", &Length);\n\n // Dynamically allocate the array using malloc()\n int* Tab = malloc(Length * sizeof(int));\n if (Tab == NULL)\n {\n // Handle allocation failure\n printf(\"Erreur d'allocation de memoire!\\n\");\n return;\n }\n\n for (int i = 0; i < Length; ++i)\n {\n printf(\"Entrer l'element %d: \", i);\n scanf(\"%d\", &Tab[i]);\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20361438/"
] |
74,660,588
|
<p>Two models Users (built-in) and Posts:</p>
<pre><code>class Post(models.Model):
post_date = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='user_post')
post = models.CharField(max_length=100)
</code></pre>
<p>I want to have an API endpoint that returns the percentage of users that have posted. Basically I want SUM(unique users who have posted) / total_users</p>
<p>I have been trying to play around with annotate and aggregate, but I am getting the sum of posts for each users, or the sum of users per post (which is one...). How can I get the sum of posts returned with unique users, divide that by user.count and return?</p>
<p>I feel like I am missing something silly but my brain has gone to mush staring at this.</p>
<pre><code>class PostParticipationAPIView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_queryset(self):
start_date = self.request.query_params.get('start_date')
end_date = self.request.query_params.get('end_date')
# How can I take something like this, divide it by User.objects.all().count() * 100, and assign it to something to return as the queryset?
queryset = Post.objects.filter(post_date__gte=start_date, post_date__lte=end_date).distinct('user').count()
return queryset
</code></pre>
<p>My goal is to end up with the endpoint like:</p>
<blockquote>
<p>{
total_participation: 97.3
}</p>
</blockquote>
<p>Thanks for any guidance.</p>
<p>BCBB</p>
|
[
{
"answer_id": 74660653,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": true,
"text": "int Length,Tab[Length]; Tab[Length] Length Tab[] Length int Length;\n float Moyenne;\n printf(\"Entrer la longeur de tableau: \");\n scanf(\"%d\",&Length);\n int Tab[Length];\n scanf() int cnt = scanf(\"%d\",&Length);\n if (cnt != 1 || Length <= 0) {\n Report_Error_and_exit();\n } \n int Tab[Length];\n Moyenne //printf(\"Somme est:%d\\nMoyenne est: %.2f\",\n// MoySom(Tab,&Moyenne,Length), Moyenne);\n\nprintf(\"Somme est:%d\\n\", MoySom(Tab,&Moyenne,Length));\nprintf(\"Moyenne est: %.2f\", Moyenne);\n *Moyenne=*Moyenne/C; if(Tab[i] % 2 == 0) {\n S=S+Tab[i];\n } else if(Tab[i] % 2 != 0) {\n *Moyenne+=Tab[i];\n if(Tab[i] % 2 == 0) {\n S=S+Tab[i];\n } else {\n *Moyenne+=Tab[i];\n"
},
{
"answer_id": 74660832,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint MoySom(int* Tab, float* Moyenne, int Length)\n{\n int S = 0, C = 0;\n *Moyenne = 0;\n for (int i = 0; i < Length; ++i)\n {\n if (Tab[i] % 2 == 0)\n {\n S = S + Tab[i];\n }\n else if (Tab[i] % 2 != 0)\n {\n *Moyenne += Tab[i];\n ++C;\n }\n }\n if (C > 0)\n {\n *Moyenne = *Moyenne / C;\n }\n return S;\n}\n\nvoid main()\n{\n int Length;\n float Moyenne;\n printf(\"Entrer la longeur de tableau: \");\n scanf(\"%d\", &Length);\n\n // Dynamically allocate the array using malloc()\n int* Tab = malloc(Length * sizeof(int));\n if (Tab == NULL)\n {\n // Handle allocation failure\n printf(\"Erreur d'allocation de memoire!\\n\");\n return;\n }\n\n for (int i = 0; i < Length; ++i)\n {\n printf(\"Entrer l'element %d: \", i);\n scanf(\"%d\", &Tab[i]);\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/858103/"
] |
74,660,595
|
<p>I've implemented the 2D ISING model in Python, using NumPy and Numba's JIT:</p>
<pre><code>
from timeit import default_timer as timer
import matplotlib.pyplot as plt
import numba as nb
import numpy as np
# TODO for Dict optimization.
# from numba import types
# from numba.typed import Dict
@nb.njit(nogil=True)
def initialstate(N):
'''
Generates a random spin configuration for initial condition
'''
state = np.empty((N,N),dtype=np.int8)
for i in range(N):
for j in range(N):
state[i,j] = 2*np.random.randint(2)-1
return state
@nb.njit(nogil=True)
def mcmove(lattice, beta, N):
'''
Monte Carlo move using Metropolis algorithm
'''
# # TODO* Dict optimization
# dict_param = Dict.empty(
# key_type=types.int64,
# value_type=types.float64,
# )
# dict_param = {cost : np.exp(-cost*beta) for cost in [-8, -4, 0, 4, 8] }
for _ in range(N):
for __ in range(N):
a = np.random.randint(0, N)
b = np.random.randint(0, N)
s = lattice[a, b]
dE = lattice[(a+1)%N,b] + lattice[a,(b+1)%N] + lattice[(a-1)%N,b] + lattice[a,(b-1)%N]
cost = 2*s*dE
if cost < 0:
s *= -1
#TODO* elif np.random.rand() < dict_param[cost]:
elif np.random.rand() < np.exp(-cost*beta):
s *= -1
lattice[a, b] = s
return lattice
@nb.njit(nogil=True)
def calcEnergy(lattice, N):
'''
Energy of a given configuration
'''
energy = 0
for i in range(len(lattice)):
for j in range(len(lattice)):
S = lattice[i,j]
nb = lattice[(i+1)%N, j] + lattice[i,(j+1)%N] + lattice[(i-1)%N, j] + lattice[i,(j-1)%N]
energy += -nb*S
return energy/2
@nb.njit(nogil=True)
def calcMag(lattice):
'''
Magnetization of a given configuration
'''
mag = np.sum(lattice, dtype=np.int32)
return mag
@nb.njit(nogil=True)
def ISING_model(nT, N, burnin, mcSteps):
"""
nT : Number of temperature points.
N : Size of the lattice, N x N.
burnin : Number of MC sweeps for equilibration (Burn-in).
mcSteps : Number of MC sweeps for calculation.
"""
T = np.linspace(1.2, 3.8, nT);
E,M,C,X = np.zeros(nT), np.zeros(nT), np.zeros(nT), np.zeros(nT)
n1, n2 = 1.0/(mcSteps*N*N), 1.0/(mcSteps*mcSteps*N*N)
for temperature in range(nT):
lattice = initialstate(N) # initialise
E1 = M1 = E2 = M2 = 0
iT = 1/T[temperature]
iT2= iT*iT
for _ in range(burnin): # equilibrate
mcmove(lattice, iT, N) # Monte Carlo moves
for _ in range(mcSteps):
mcmove(lattice, iT, N)
Ene = calcEnergy(lattice, N) # calculate the Energy
Mag = calcMag(lattice,) # calculate the Magnetisation
E1 += Ene
M1 += Mag
M2 += Mag*Mag
E2 += Ene*Ene
E[temperature] = n1*E1
M[temperature] = n1*M1
C[temperature] = (n1*E2 - n2*E1*E1)*iT2
X[temperature] = (n1*M2 - n2*M1*M1)*iT
return T,E,M,C,X
def main():
N = 32
start_time = timer()
T,E,M,C,X = ISING_model(nT = 64, N = N, burnin = 8 * 10**4, mcSteps = 8 * 10**4)
end_time = timer()
print("Elapsed time: %g seconds" % (end_time - start_time))
f = plt.figure(figsize=(18, 10)); #
# figure title
f.suptitle(f"Ising Model: 2D Lattice\nSize: {N}x{N}", fontsize=20)
_ = f.add_subplot(2, 2, 1 )
plt.plot(T, E, '-o', color='Blue')
plt.xlabel("Temperature (T)", fontsize=20)
plt.ylabel("Energy ", fontsize=20)
plt.axis('tight')
_ = f.add_subplot(2, 2, 2 )
plt.plot(T, abs(M), '-o', color='Red')
plt.xlabel("Temperature (T)", fontsize=20)
plt.ylabel("Magnetization ", fontsize=20)
plt.axis('tight')
_ = f.add_subplot(2, 2, 3 )
plt.plot(T, C, '-o', color='Green')
plt.xlabel("Temperature (T)", fontsize=20)
plt.ylabel("Specific Heat ", fontsize=20)
plt.axis('tight')
_ = f.add_subplot(2, 2, 4 )
plt.plot(T, X, '-o', color='Black')
plt.xlabel("Temperature (T)", fontsize=20)
plt.ylabel("Susceptibility", fontsize=20)
plt.axis('tight')
plt.show()
if __name__ == '__main__':
main()
</code></pre>
<p>Which of course, works:</p>
<p><a href="https://i.stack.imgur.com/zTwIk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zTwIk.png" alt="enter image description here" /></a></p>
<p>I have two main questions:</p>
<ol>
<li>Is there anything left to optimize? I knew ISING model is hard to simulate, but looking at the following table, it seems like I'm missing something...</li>
</ol>
<pre><code> lattice size : 32x32
burnin = 8 * 10**4
mcSteps = 8 * 10**4
Simulation time = 365.98 seconds
lattice size : 64x64
burnin = 10**5
mcSteps = 10**5
Simulation time = 1869.58 seconds
</code></pre>
<ol start="2">
<li>I tried implementing another optimization based on not calculating the exponential over and over again using a dictionary, yet on my tests, it seems like its slower. What am I doing wrong?</li>
</ol>
|
[
{
"answer_id": 74660653,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": true,
"text": "int Length,Tab[Length]; Tab[Length] Length Tab[] Length int Length;\n float Moyenne;\n printf(\"Entrer la longeur de tableau: \");\n scanf(\"%d\",&Length);\n int Tab[Length];\n scanf() int cnt = scanf(\"%d\",&Length);\n if (cnt != 1 || Length <= 0) {\n Report_Error_and_exit();\n } \n int Tab[Length];\n Moyenne //printf(\"Somme est:%d\\nMoyenne est: %.2f\",\n// MoySom(Tab,&Moyenne,Length), Moyenne);\n\nprintf(\"Somme est:%d\\n\", MoySom(Tab,&Moyenne,Length));\nprintf(\"Moyenne est: %.2f\", Moyenne);\n *Moyenne=*Moyenne/C; if(Tab[i] % 2 == 0) {\n S=S+Tab[i];\n } else if(Tab[i] % 2 != 0) {\n *Moyenne+=Tab[i];\n if(Tab[i] % 2 == 0) {\n S=S+Tab[i];\n } else {\n *Moyenne+=Tab[i];\n"
},
{
"answer_id": 74660832,
"author": "Cyzanfar",
"author_id": 3307520,
"author_profile": "https://Stackoverflow.com/users/3307520",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint MoySom(int* Tab, float* Moyenne, int Length)\n{\n int S = 0, C = 0;\n *Moyenne = 0;\n for (int i = 0; i < Length; ++i)\n {\n if (Tab[i] % 2 == 0)\n {\n S = S + Tab[i];\n }\n else if (Tab[i] % 2 != 0)\n {\n *Moyenne += Tab[i];\n ++C;\n }\n }\n if (C > 0)\n {\n *Moyenne = *Moyenne / C;\n }\n return S;\n}\n\nvoid main()\n{\n int Length;\n float Moyenne;\n printf(\"Entrer la longeur de tableau: \");\n scanf(\"%d\", &Length);\n\n // Dynamically allocate the array using malloc()\n int* Tab = malloc(Length * sizeof(int));\n if (Tab == NULL)\n {\n // Handle allocation failure\n printf(\"Erreur d'allocation de memoire!\\n\");\n return;\n }\n\n for (int i = 0; i < Length; ++i)\n {\n printf(\"Entrer l'element %d: \", i);\n scanf(\"%d\", &Tab[i]);\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14044445/"
] |
74,660,599
|
<p>I have a large data frame called <code>data_frame</code> with two columns <code>PRE</code> and <code>STATUS</code> that look like this:</p>
<pre><code>PRE STATUS
1_752566 GAINED
1_776546 LOST
1_832918 NA
1_842013 LOST
1_846864 GAINED
11_8122943 NA
11_8188699 GAINED
11_8321128 NA
23_95137734 NA
23_95146814 GAINED
</code></pre>
<p>What I would like is to create a new column <code>CHR</code> with only the number(s) before the underscore and make sure they are matched up next to the original column correctly like this:</p>
<pre><code>PRE STATUS CHR
1_752566 GAINED 1
1_776546 LOST 1
1_832918 NA 1
1_842013 LOST 1
1_846864 GAINED 1
11_8122943 NA 11
11_8188699 GAINED 11
11_8321128 NA 11
23_95137734 NA 23
23_95146814 GAINED 23
</code></pre>
<p>From here I'd like to group <code>CHR</code> by number and then find the sum of each group. If possible, I would like a new data table showing the sums of each group number like this:</p>
<pre><code>NUM SUM
1 5
11 3
23 2
</code></pre>
<p>I would then plot this to visualize the sums of each number where my x-axis is <code>NUM</code> and my y-axis is <code>SUM</code></p>
|
[
{
"answer_id": 74660629,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "_ library(dplyr)\ndf <- df %>%\n mutate(CHR = trimws(PRE, whitespace = \"_.*\"))\n df\n PRE STATUS CHR\n1 1_752566 GAINED 1\n2 1_776546 LOST 1\n3 1_832918 <NA> 1\n4 1_842013 LOST 1\n5 1_846864 GAINED 1\n6 11_8122943 <NA> 11\n7 11_8188699 GAINED 11\n8 11_8321128 <NA> 11\n9 23_95137734 <NA> 23\n10 23_95146814 GAINED 23\n count df %>%\n count(CHR, name = \"SUM\")\n CHR SUM\n1 1 5\n2 11 3\n3 23 2\n library(ggplot2)\ndf %>%\n count(CHR, name = \"SUM\") %>%\n ggplot(aes(x = CHR, y = SUM)) +\n geom_col()\n df <- structure(list(PRE = c(\"1_752566\", \"1_776546\", \"1_832918\", \"1_842013\", \n\"1_846864\", \"11_8122943\", \"11_8188699\", \"11_8321128\", \"23_95137734\", \n\"23_95146814\"), STATUS = c(\"GAINED\", \"LOST\", NA, \"LOST\", \"GAINED\", \nNA, \"GAINED\", NA, NA, \"GAINED\")), class = \"data.frame\", row.names = c(NA, \n-10L))\n"
},
{
"answer_id": 74660713,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "parse_number() readr parse_number _ library(dplyr)\nlibrary(readr)\ndf %>% \n group_by(CHR = parse_number(PRE)) %>% \n summarise(NUM = first(CHR), SUM =n()) %>% \n select(-CHR)\n NUM SUM\n <dbl> <int>\n1 1 5\n2 11 3\n3 23 2\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924976/"
] |
74,660,611
|
<p>I am using the following Gradio sample code to transcribe my audio:</p>
<pre><code>from transformers import pipeline
p = pipeline("automatic-speech-recognition")
import gradio as gr
def transcribe(audio):
text = p(audio)["text"]
return text
gr.Interface(
fn=transcribe,
inputs=gr.Audio(source="microphone", type="filepath"),
outputs="text").launch()
</code></pre>
<p>However, the user has to start recording audio, stop recording audio, and the submit the audio. Can I auto submit the audio when the user presses stop recording audio?</p>
|
[
{
"answer_id": 74660629,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "_ library(dplyr)\ndf <- df %>%\n mutate(CHR = trimws(PRE, whitespace = \"_.*\"))\n df\n PRE STATUS CHR\n1 1_752566 GAINED 1\n2 1_776546 LOST 1\n3 1_832918 <NA> 1\n4 1_842013 LOST 1\n5 1_846864 GAINED 1\n6 11_8122943 <NA> 11\n7 11_8188699 GAINED 11\n8 11_8321128 <NA> 11\n9 23_95137734 <NA> 23\n10 23_95146814 GAINED 23\n count df %>%\n count(CHR, name = \"SUM\")\n CHR SUM\n1 1 5\n2 11 3\n3 23 2\n library(ggplot2)\ndf %>%\n count(CHR, name = \"SUM\") %>%\n ggplot(aes(x = CHR, y = SUM)) +\n geom_col()\n df <- structure(list(PRE = c(\"1_752566\", \"1_776546\", \"1_832918\", \"1_842013\", \n\"1_846864\", \"11_8122943\", \"11_8188699\", \"11_8321128\", \"23_95137734\", \n\"23_95146814\"), STATUS = c(\"GAINED\", \"LOST\", NA, \"LOST\", \"GAINED\", \nNA, \"GAINED\", NA, NA, \"GAINED\")), class = \"data.frame\", row.names = c(NA, \n-10L))\n"
},
{
"answer_id": 74660713,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "parse_number() readr parse_number _ library(dplyr)\nlibrary(readr)\ndf %>% \n group_by(CHR = parse_number(PRE)) %>% \n summarise(NUM = first(CHR), SUM =n()) %>% \n select(-CHR)\n NUM SUM\n <dbl> <int>\n1 1 5\n2 11 3\n3 23 2\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10151520/"
] |
74,660,613
|
<p>`</p>
<pre><code>life_max = -5
life_min = 999
country_max = ""
country_min = ""
answer = int(input("Which year would you like to enter? "))
with open ("life.csv") as f:
next(f)
for line in f:
parts = line.split(",")
life = float(parts[3])
year = int(parts[2])
country = parts[0].strip()
code = parts[1].strip()
if life > life_max:
life_max = life
country_max = country
if life < life_min:
life_min = life
country_min = country
average = range(sum(life)) / range(len(life))
print(f"The average is {average}")
print(f"The country with the worst life expectancy is {country_min} at {life_min} years.")
print(f"The country with the best life expectancy is {country_max} at {life_max} years.")
</code></pre>
<p>`</p>
<p>I'm having some troubles in finding the average life expectancy given a specified year, it returns with a 'float' not iterable error and I'm pretty lost.</p>
|
[
{
"answer_id": 74660629,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "_ library(dplyr)\ndf <- df %>%\n mutate(CHR = trimws(PRE, whitespace = \"_.*\"))\n df\n PRE STATUS CHR\n1 1_752566 GAINED 1\n2 1_776546 LOST 1\n3 1_832918 <NA> 1\n4 1_842013 LOST 1\n5 1_846864 GAINED 1\n6 11_8122943 <NA> 11\n7 11_8188699 GAINED 11\n8 11_8321128 <NA> 11\n9 23_95137734 <NA> 23\n10 23_95146814 GAINED 23\n count df %>%\n count(CHR, name = \"SUM\")\n CHR SUM\n1 1 5\n2 11 3\n3 23 2\n library(ggplot2)\ndf %>%\n count(CHR, name = \"SUM\") %>%\n ggplot(aes(x = CHR, y = SUM)) +\n geom_col()\n df <- structure(list(PRE = c(\"1_752566\", \"1_776546\", \"1_832918\", \"1_842013\", \n\"1_846864\", \"11_8122943\", \"11_8188699\", \"11_8321128\", \"23_95137734\", \n\"23_95146814\"), STATUS = c(\"GAINED\", \"LOST\", NA, \"LOST\", \"GAINED\", \nNA, \"GAINED\", NA, NA, \"GAINED\")), class = \"data.frame\", row.names = c(NA, \n-10L))\n"
},
{
"answer_id": 74660713,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "parse_number() readr parse_number _ library(dplyr)\nlibrary(readr)\ndf %>% \n group_by(CHR = parse_number(PRE)) %>% \n summarise(NUM = first(CHR), SUM =n()) %>% \n select(-CHR)\n NUM SUM\n <dbl> <int>\n1 1 5\n2 11 3\n3 23 2\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20669567/"
] |
74,660,619
|
<p>Im some ocassion a Stack user help me for make this script. Im edit it for add more attributes but I have problems when try to add <strong>Authors</strong></p>
<p>The Author label is next to <code>target</code> and <code>href</code>. I have problem in this part.</p>
<pre><code> library(tidyverse)
library(rvest)
startTime <- Sys.time()
get_cg <- function(pages) {
cat("Scraping page", pages, "\n")
page <-
str_c("https://cgspace.cgiar.org/discover?
scope=10568%2F106146&query=cassava&submit=&rpp=10&page=", pages) %>%
read_html()
tibble(
title = page %>%
html_elements(".ds-artifact-item") %>%
html_element(".description-info") %>%
html_text2(), # run well
fecha = page %>%
html_elements(".ds-artifact-item") %>%
html_element(".date") %>%
html_text2(), # run well
Type = page %>%
html_elements(".ds-artifact-item") %>%
html_element(".artifact-type") %>%
html_text2(), # run well
Autor= page %>%
html_elements(".ds-artifact-item") %>%
html_element(".description-info") %>%
html_attr("href"), # not download the Authors
link = page %>%
html_elements(".ds-artifact-item") %>%
html_element(".description-info") %>%
html_attr("href") %>% # run well
str_c("https://cgspace.cgiar.org", .)
)
}
df <- map_dfr(1, get_cg)
endTime <- Sys.time()
print(endTime - startTim)
</code></pre>
<p>Im try with other selector but get NA</p>
|
[
{
"answer_id": 74662671,
"author": "margusl",
"author_id": 646761,
"author_profile": "https://Stackoverflow.com/users/646761",
"pm_score": 2,
"selected": false,
"text": "; library(tidyverse, warn.conflicts = F)\nlibrary(rvest, warn.conflicts = F)\n\nstartTime <- Sys.time()\nget_cg <- function(pages) {\n \n cat(\"Scraping page\", pages, \"\\n\")\n \n page <-\n str_c(\"https://cgspace.cgiar.org/discover?scope=10568%2F106146&query=cassava&submit=&rpp=10&page=\", pages) %>%\n read_html()\n \n html_elements(page, \"div.artifact-description > div.artifact-description\") %>% \n map_df(~ list(\n title = html_element(.x, \".description-info\") %>% html_text2(),\n fecha = html_element(.x, \".date\") %>% html_text2(),\n Type = html_element(.x, \".artifact-type\") %>% html_text2(),\n # Autor_links = html_elements(.x,\".description-info > span > a\") %>% html_attr(\"href\") %>% paste(collapse = \";\"),\n Autor = html_element(.x, \"span.description-info\") %>% html_text2(),\n link = html_element(.x, \"a.description-info\") %>% html_attr(\"href\") %>% str_c(\"https://cgspace.cgiar.org\", .)\n )) \n}\n\ndf <- map_dfr(1, get_cg)\n#> Scraping page 1\n\nendTime <- Sys.time()\nprint(endTime - startTime)\n#> Time difference of 0.989037 secs\n df\n#> # A tibble: 10 × 5\n#> title fecha Type Autor link \n#> <chr> <chr> <chr> <chr> <chr>\n#> 1 Global Climate Regions for Cassava 2020… Type… Hyma… http…\n#> 2 Performance of the CSM–MANIHOT–Cassava model for sim… 2021… Type… Phon… http…\n#> 3 Adoption of cassava improved modern varieties in the… 2020 Type… Laba… http…\n#> 4 First report of Sri Lankan cassava mosaic virus and … 2021… Type… Chit… http…\n#> 5 Surveillance and diagnostics dataset on Sri Lankan c… 2020 Type… Siri… http…\n#> 6 Socieconomic and soil conservation practices for cas… 2022… Type… Ibar… http…\n#> 7 The transformation and outcome of traditional cassav… 2020 Type… Dou,… http…\n#> 8 Cassava Annual Report 2019 2020 Type… Inte… http…\n#> 9 Cassava Annual Report 2020 2021… Type… Bece… http…\n#> 10 Adoption of cassava improved modern varieties in the… 2020 Type… Flor… http…\n\nglimpse(df)\n#> Rows: 10\n#> Columns: 5\n#> $ title <chr> \"Global Climate Regions for Cassava\", \"Performance of the CSM–MA…\n#> $ fecha <chr> \"2020-08-03\", \"2021-05-01\", \"2020\", \"2021-04-23\", \"2020\", \"2022-…\n#> $ Type <chr> \"Type:Dataset\", \"Type:Journal Article\", \"Type:Dataset\", \"Type:Jo…\n#> $ Autor <chr> \"Hyman, Glenn G.\", \"Phoncharoen, Phanupong; Banterng, Poramate; …\n#> $ link <chr> \"https://cgspace.cgiar.org/handle/10568/109500\", \"https://cgspac…\n"
},
{
"answer_id": 74665712,
"author": "sametcodes",
"author_id": 8574166,
"author_profile": "https://Stackoverflow.com/users/8574166",
"pm_score": 0,
"selected": false,
"text": "Autor = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n html_attr(\"href\"),\n\nlink = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n html_attr(\"href\") %>%\n str_c(\"https://cgspace.cgiar.org\", .)\n Autor = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n map_chr(\"href\"),\n\nlink = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n map_chr(\"href\") %>%\n str_c(\"https://cgspace.cgiar.org\", .)\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15449339/"
] |
74,660,628
|
<p>When I`m trying to connect Django Server to PostgreSQL db there is an error:
" port 5433 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? "</p>
<p>I`m using Windows 10, Pycharm, Debian</p>
<p>Settings in Django:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'ps_store_db',
'USER': 'zesshi',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '5433',
}
}
</code></pre>
<p>Tried to check connection with DBeaver and all`s good there, but still cant connect with Django</p>
<p>My firewall is off, i was trying to change from 5432 to 5433</p>
<p><a href="https://i.stack.imgur.com/R4vd6.png" rel="nofollow noreferrer">Dbeaver connection</a></p>
<p><a href="https://i.stack.imgur.com/BWkb3.png" rel="nofollow noreferrer">Dbeaver connection 2</a></p>
|
[
{
"answer_id": 74662671,
"author": "margusl",
"author_id": 646761,
"author_profile": "https://Stackoverflow.com/users/646761",
"pm_score": 2,
"selected": false,
"text": "; library(tidyverse, warn.conflicts = F)\nlibrary(rvest, warn.conflicts = F)\n\nstartTime <- Sys.time()\nget_cg <- function(pages) {\n \n cat(\"Scraping page\", pages, \"\\n\")\n \n page <-\n str_c(\"https://cgspace.cgiar.org/discover?scope=10568%2F106146&query=cassava&submit=&rpp=10&page=\", pages) %>%\n read_html()\n \n html_elements(page, \"div.artifact-description > div.artifact-description\") %>% \n map_df(~ list(\n title = html_element(.x, \".description-info\") %>% html_text2(),\n fecha = html_element(.x, \".date\") %>% html_text2(),\n Type = html_element(.x, \".artifact-type\") %>% html_text2(),\n # Autor_links = html_elements(.x,\".description-info > span > a\") %>% html_attr(\"href\") %>% paste(collapse = \";\"),\n Autor = html_element(.x, \"span.description-info\") %>% html_text2(),\n link = html_element(.x, \"a.description-info\") %>% html_attr(\"href\") %>% str_c(\"https://cgspace.cgiar.org\", .)\n )) \n}\n\ndf <- map_dfr(1, get_cg)\n#> Scraping page 1\n\nendTime <- Sys.time()\nprint(endTime - startTime)\n#> Time difference of 0.989037 secs\n df\n#> # A tibble: 10 × 5\n#> title fecha Type Autor link \n#> <chr> <chr> <chr> <chr> <chr>\n#> 1 Global Climate Regions for Cassava 2020… Type… Hyma… http…\n#> 2 Performance of the CSM–MANIHOT–Cassava model for sim… 2021… Type… Phon… http…\n#> 3 Adoption of cassava improved modern varieties in the… 2020 Type… Laba… http…\n#> 4 First report of Sri Lankan cassava mosaic virus and … 2021… Type… Chit… http…\n#> 5 Surveillance and diagnostics dataset on Sri Lankan c… 2020 Type… Siri… http…\n#> 6 Socieconomic and soil conservation practices for cas… 2022… Type… Ibar… http…\n#> 7 The transformation and outcome of traditional cassav… 2020 Type… Dou,… http…\n#> 8 Cassava Annual Report 2019 2020 Type… Inte… http…\n#> 9 Cassava Annual Report 2020 2021… Type… Bece… http…\n#> 10 Adoption of cassava improved modern varieties in the… 2020 Type… Flor… http…\n\nglimpse(df)\n#> Rows: 10\n#> Columns: 5\n#> $ title <chr> \"Global Climate Regions for Cassava\", \"Performance of the CSM–MA…\n#> $ fecha <chr> \"2020-08-03\", \"2021-05-01\", \"2020\", \"2021-04-23\", \"2020\", \"2022-…\n#> $ Type <chr> \"Type:Dataset\", \"Type:Journal Article\", \"Type:Dataset\", \"Type:Jo…\n#> $ Autor <chr> \"Hyman, Glenn G.\", \"Phoncharoen, Phanupong; Banterng, Poramate; …\n#> $ link <chr> \"https://cgspace.cgiar.org/handle/10568/109500\", \"https://cgspac…\n"
},
{
"answer_id": 74665712,
"author": "sametcodes",
"author_id": 8574166,
"author_profile": "https://Stackoverflow.com/users/8574166",
"pm_score": 0,
"selected": false,
"text": "Autor = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n html_attr(\"href\"),\n\nlink = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n html_attr(\"href\") %>%\n str_c(\"https://cgspace.cgiar.org\", .)\n Autor = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n map_chr(\"href\"),\n\nlink = page %>%\n html_elements(\".ds-artifact-item\") %>%\n html_nodes(\".description-info\") %>%\n map_chr(\"href\") %>%\n str_c(\"https://cgspace.cgiar.org\", .)\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20646427/"
] |
74,660,641
|
<p>i am trying to make a program that compares word1 strings with word2 string to occur only once</p>
<pre><code>class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
word1 = [x.strip() for x in word1]
word2 = [x.strip() for x in word2]
update = False
for x in word1:
if(x in word2):
update = True
if(type(x) is str):
a = word1.index(x)
b = word2.index(x)
word1[a]=''
word2[b]=''
else:
update = False
else:
update = False
break
return update
print(Solution.closeStrings(Solution,word1='a',word2='aa'))
</code></pre>
<p>Input</p>
<pre><code>word1 = 'a',word2 ='aa'
</code></pre>
<p>Expected
<code> Output = False</code></p>
<p>Actual
<code>Output = True</code></p>
|
[
{
"answer_id": 74660751,
"author": "Thomas Weller",
"author_id": 480982,
"author_profile": "https://Stackoverflow.com/users/480982",
"pm_score": 1,
"selected": false,
"text": "print(Solution.closeStrings(Solution,word1='a',word2='aa')) Solution self word1 = [x.strip() for x in word1] print([x.strip() for x in \"Hello world\"]) class Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n for x in word1:\n if word2.count(x) != word1.count(x): return False\n return True\n\n\ns = Solution()\nprint(s.closeStrings(word1='a',word2='aa'))\nprint(s.closeStrings(word1='abcb',word2='bcab'))\n"
},
{
"answer_id": 74660811,
"author": "twister_void",
"author_id": 637377,
"author_profile": "https://Stackoverflow.com/users/637377",
"pm_score": 0,
"selected": false,
"text": "class Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n for i in word1:\n if i not in word2:\n return False\n for i in word2:\n if i not in word1:\n return False\n return True\n\n def closeStrings2(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n if set(word1) != set(word2):\n return False\n return True\n\n def closeStrings3(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n if sorted(word1) != sorted(word2):\n return False\n return True\n\nprint(Solution().closeStrings(word1=\"cabbba\", word2=\"abbccc\"))\nprint(Solution().closeStrings3(word1=\"cabbba\", word2=\"aabbss\"))\nprint(Solution().closeStrings3(word1=\"cabbba\", word2=\"aabbss\"))\n\n\n\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615635/"
] |
74,660,644
|
<p>I have a text file where every other row either begins with "A" or "B" like this</p>
<pre><code>A810 WE WILDWOOD DR
B20220901BROOKE
A6223 AMHERST BAY
B20221001SARAI
</code></pre>
<p>How can I read the text file and create a two column pandas dataframe where the line beginning with "A" is a column and likewise for the "B", on a single row. Like this</p>
<pre><code>|A |B |
|:------------------|:--------------|
|A810 WE WILDWOOD DR|B20220901BROOKE|
|:------------------|---------------|
|A6223 AMHERST BAY |B20221001SARAI |
|:------------------|---------------|
</code></pre>
|
[
{
"answer_id": 74660723,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": false,
"text": "pandas.DataFrame.shift pandas.DataFrame.join from io import StringIO \nimport pandas as pd\n\ns = \"\"\"A810 WE WILDWOOD DR\nB20220901BROOKE\nA6223 AMHERST BAY\nB20221001SARAI\n\"\"\"\n\ndf = pd.read_csv(StringIO(s), header=None, names=[\"A\"])\n#in your case, df = pd.read_csv(\"path_of_your_txtfile\", header=None, names=[\"A\"])\n\nout = (\n df\n .join(df.shift(-1).rename(columns= {\"A\": \"B\"}))\n .iloc[::2]\n .reset_index(drop=True)\n )\n print(out)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74660974,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "pivot col = df[0].str.extract('(.)', expand=False)\n\nout = (df\n .assign(col=col, idx=df.groupby(col).cumcount())\n .pivot(index='idx', columns='col', values=0)\n .rename_axis(index=None, columns=None)\n)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74661037,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "A B pd.DataFrame(df.values.reshape((-1, 2)), columns=list('AB'))\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11069614/"
] |
74,660,663
|
<p>I am writing a program that sends a signal in one process and receives it in a thread in another. I have the entire program written with signals being caught and handled, as well as any synchronization issues. The problem is, I am trying to log the time the signal was sent and the time the signal was received. Though the values across the process vary strangely.</p>
<p>Here is how I did it.</p>
<p>I have a header file <code>header.h</code> which includes a shared global <code>extern struct timespec begin, end;</code>. The reason I made these shared was that I would need the beginning time to calculate the time elapsed since the program began.</p>
<p>Here is how I calculate the time elapsed.</p>
<p>I am using the POSIX clock_gettime().
I start the program and begin the timer, then when a signal is sent I run:</p>
<pre><code>clock_gettime(CLOCK_REALTIME, &end);
long seconds = end.tv_sec - begin.tv_sec;
long nanoseconds = end.tv_nsec - begin.tv_nsec;
double elapsed = seconds + nanoseconds * 1e-9;
</code></pre>
<p>This all occurs in the main program.
The second process is another program which is <code>exec()</code> in a child process and that is where the signal catch occurs.
When I catch the signal, I store some data about it in a struct and store it in a buffer for another thread to read and log from.</p>
<pre><code>typedef struct
{
int sig;
double time;
long int tid;
} data;
</code></pre>
<p>Here's what I do in one of the threads:</p>
<pre><code>data d;
d.sig = 2;
d.tid = pthread_self();
clock_gettime(CLOCK_REALTIME, &end);
long seconds = end.tv_sec - begin.tv_sec;
long nanoseconds = end.tv_nsec - begin.tv_nsec;
double elapsed = seconds + nanoseconds * 1e-9;
d.time = elapsed;
put(d);
</code></pre>
<p>The problem is my outputs are vastly different. In my <code>sentlog.txt</code> the time is represented correctly, with enough precision to see a difference.</p>
<pre><code>SIGUSR2 sent at 1.000286 seconds
SIGUSR2 sent at 1.082671 seconds
SIGUSR2 sent at 1.155440 seconds
SIGUSR1 sent at 1.250770 seconds
SIGUSR1 sent at 1.314637 seconds
SIGUSR2 sent at 1.398995 seconds
SIGUSR1 sent at 1.460559 seconds
SIGUSR2 sent at 1.498223 seconds
SIGUSR2 sent at 1.577555 seconds
SIGUSR1 sent at 1.618036 seconds
SIGUSR2 sent at 1.684488 seconds
SIGUSR2 sent at 1.743165 seconds
SIGUSR2 sent at 1.780100 seconds
SIGUSR2 sent at 1.871603 seconds
SIGUSR1 sent at 1.901293 seconds
SIGUSR2 sent at 1.944139 seconds
SIGUSR1 sent at 1.984142 seconds
SIGUSR1 sent at 2.040130 seconds
</code></pre>
<p>While the <code>receivelog.txt</code> is not.</p>
<p>Here is how I log to the file and stdout</p>
<pre><code>if (d.sig == 1)
{
printf("SIGUSR1 received by thread %ld at time %f\n", d.tid, d.time);
fflush(stdout);
fprintf(fpRecieve, "Thread %ld received SIGUSR1 at %f seconds\n", d.tid, d.time);
fflush(fpRecieve);
}
else if (d.sig == 2)
{
printf("SIGUSR2 received by thread %ld at time %f\n", d.tid, d.time);
fflush(stdout);
fprintf(fpRecieve, "Thread %ld received SIGUSR2 at %f seconds\n", d.tid, d.time);
fflush(fpRecieve);
}
</code></pre>
<pre><code>Thread 139995363964672 received SIGUSR2 at 1670008328.531628 seconds
Thread 139995363964672 received SIGUSR2 at 1670008328.613999 seconds
Thread 139995363964672 received SIGUSR2 at 1670008328.686767 seconds
Thread 139995372357376 received SIGUSR1 at 1670008328.782099 seconds
Thread 139995372357376 received SIGUSR1 at 1670008328.845975 seconds
Thread 139995363964672 received SIGUSR2 at 1670008328.930328 seconds
Thread 139995372357376 received SIGUSR1 at 1670008328.991889 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.029554 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.108883 seconds
Thread 139995372357376 received SIGUSR1 at 1670008329.149364 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.215814 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.274493 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.311425 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.402932 seconds
Thread 139995372357376 received SIGUSR1 at 1670008329.432621 seconds
Thread 139995363964672 received SIGUSR2 at 1670008329.475466 seconds
</code></pre>
<p>Why can I not simply just use the same operation as before?</p>
|
[
{
"answer_id": 74660723,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": false,
"text": "pandas.DataFrame.shift pandas.DataFrame.join from io import StringIO \nimport pandas as pd\n\ns = \"\"\"A810 WE WILDWOOD DR\nB20220901BROOKE\nA6223 AMHERST BAY\nB20221001SARAI\n\"\"\"\n\ndf = pd.read_csv(StringIO(s), header=None, names=[\"A\"])\n#in your case, df = pd.read_csv(\"path_of_your_txtfile\", header=None, names=[\"A\"])\n\nout = (\n df\n .join(df.shift(-1).rename(columns= {\"A\": \"B\"}))\n .iloc[::2]\n .reset_index(drop=True)\n )\n print(out)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74660974,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "pivot col = df[0].str.extract('(.)', expand=False)\n\nout = (df\n .assign(col=col, idx=df.groupby(col).cumcount())\n .pivot(index='idx', columns='col', values=0)\n .rename_axis(index=None, columns=None)\n)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74661037,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "A B pd.DataFrame(df.values.reshape((-1, 2)), columns=list('AB'))\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16009652/"
] |
74,660,690
|
<p><a href="https://i.stack.imgur.com/5AV9o.png" rel="nofollow noreferrer">This is the dataset:</a></p>
<p>`</p>
<pre><code>data = {'id': ['1','1','1','1','2','2','2','2','2','3','3','3','3','3','3','3'],
'status': ['Active','Active','Active','Pending Action','Pending Action','Pending Action','Active','Pending Action','Active','Draft','Active','Draft','Draft','Draft','Active','Draft'],
'calc_date_id':['05/07/2022','07/06/2022','31/08/2021','01/07/2021','20/11/2022','25/10/2022','02/04/2022','28/02/2022','01/07/2021','23/06/2022','15/06/2022','07/04/2022','09/11/2022','18/08/2020','19/03/2020','17/01/202']
}
df = pd.DataFrame(data)
#to datetime
df['calc_date_id'] = pd.to_datetime(df['calc_date_id'])
</code></pre>
<p>`</p>
<p>How do I get the first date in the last time the status change by id?</p>
<p>I tried sorting by date and groupby with id and status and keep="first" but I got:</p>
<p><a href="https://i.stack.imgur.com/is8J6.png" rel="nofollow noreferrer">Groupbing by status </a></p>
<p>Also tried</p>
<pre><code>df_mt_date.loc[df_mt_date.groupby(['id',' status'])['calc_date_id'].idxmin()]
</code></pre>
<p>Instead of that I'd like to preserve the order by date obtaining only the first time where the id has changed status for the last time (not all of the history).</p>
<p><a href="https://i.stack.imgur.com/sia6E.png" rel="nofollow noreferrer">This is the desired output</a></p>
<p>I'm running out of ideas, I'll appreciate any suggestion</p>
<p>Thank you</p>
|
[
{
"answer_id": 74660723,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": false,
"text": "pandas.DataFrame.shift pandas.DataFrame.join from io import StringIO \nimport pandas as pd\n\ns = \"\"\"A810 WE WILDWOOD DR\nB20220901BROOKE\nA6223 AMHERST BAY\nB20221001SARAI\n\"\"\"\n\ndf = pd.read_csv(StringIO(s), header=None, names=[\"A\"])\n#in your case, df = pd.read_csv(\"path_of_your_txtfile\", header=None, names=[\"A\"])\n\nout = (\n df\n .join(df.shift(-1).rename(columns= {\"A\": \"B\"}))\n .iloc[::2]\n .reset_index(drop=True)\n )\n print(out)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74660974,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "pivot col = df[0].str.extract('(.)', expand=False)\n\nout = (df\n .assign(col=col, idx=df.groupby(col).cumcount())\n .pivot(index='idx', columns='col', values=0)\n .rename_axis(index=None, columns=None)\n)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74661037,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "A B pd.DataFrame(df.values.reshape((-1, 2)), columns=list('AB'))\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20661992/"
] |
74,660,709
|
<p>In my power automate flow, I have an action that give time output in this format: 2022-12-01T18:52:50.0000000Z
How can I take this output and format as yyyy/mm/dd .
I want to use the time output as string for a folder structure.</p>
|
[
{
"answer_id": 74660723,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": false,
"text": "pandas.DataFrame.shift pandas.DataFrame.join from io import StringIO \nimport pandas as pd\n\ns = \"\"\"A810 WE WILDWOOD DR\nB20220901BROOKE\nA6223 AMHERST BAY\nB20221001SARAI\n\"\"\"\n\ndf = pd.read_csv(StringIO(s), header=None, names=[\"A\"])\n#in your case, df = pd.read_csv(\"path_of_your_txtfile\", header=None, names=[\"A\"])\n\nout = (\n df\n .join(df.shift(-1).rename(columns= {\"A\": \"B\"}))\n .iloc[::2]\n .reset_index(drop=True)\n )\n print(out)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74660974,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "pivot col = df[0].str.extract('(.)', expand=False)\n\nout = (df\n .assign(col=col, idx=df.groupby(col).cumcount())\n .pivot(index='idx', columns='col', values=0)\n .rename_axis(index=None, columns=None)\n)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74661037,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "A B pd.DataFrame(df.values.reshape((-1, 2)), columns=list('AB'))\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19374360/"
] |
74,660,743
|
<p>I need to restructure my data so that it goes from 5 columns to 1 column, while preserving the relative positions. The example is generic but the real data will have different stems and responses for each row.</p>
<p>For example, say I have the data below:</p>
<p><a href="https://i.stack.imgur.com/hO4pw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hO4pw.png" alt="Wide data, multiple columns" /></a></p>
<p>I want to end up with data that looks like the image below:</p>
<p><a href="https://i.stack.imgur.com/Xtjuo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xtjuo.png" alt="Long data, single column" /></a></p>
<p>The real data sets will always have 5 columns, but each stem and response will be different</p>
<p>I tried VBA and macros, but am not well versed in either of those. I am expecting to go from 5 columns(a stem and 4 responses) to 1 columns that contains a list of a stem followed by it's responses, then the next stem and its responses,...etc.</p>
<p>I have looked into some VBA and macros but haven't found something that works or haven't been applying them properly. Does anyone know a macro or VBA commands to get this to work?</p>
<p>Thanks for any help you can give me!</p>
|
[
{
"answer_id": 74660723,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": false,
"text": "pandas.DataFrame.shift pandas.DataFrame.join from io import StringIO \nimport pandas as pd\n\ns = \"\"\"A810 WE WILDWOOD DR\nB20220901BROOKE\nA6223 AMHERST BAY\nB20221001SARAI\n\"\"\"\n\ndf = pd.read_csv(StringIO(s), header=None, names=[\"A\"])\n#in your case, df = pd.read_csv(\"path_of_your_txtfile\", header=None, names=[\"A\"])\n\nout = (\n df\n .join(df.shift(-1).rename(columns= {\"A\": \"B\"}))\n .iloc[::2]\n .reset_index(drop=True)\n )\n print(out)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74660974,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "pivot col = df[0].str.extract('(.)', expand=False)\n\nout = (df\n .assign(col=col, idx=df.groupby(col).cumcount())\n .pivot(index='idx', columns='col', values=0)\n .rename_axis(index=None, columns=None)\n)\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
},
{
"answer_id": 74661037,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "A B pd.DataFrame(df.values.reshape((-1, 2)), columns=list('AB'))\n A B\n0 A810 WE WILDWOOD DR B20220901BROOKE\n1 A6223 AMHERST BAY B20221001SARAI\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18738799/"
] |
74,660,782
|
<p>I've got a simple CMake educational project sturctured like this:</p>
<p><a href="https://i.stack.imgur.com/CwxCo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CwxCo.png" alt="project structure" /></a></p>
<p>The root CMakeLists.txt is like that:</p>
<pre><code>cmake_minimum_required(VERSION 3.24.2)
project(SIMPLE_ENGINE CXX)
add_subdirectory(engine)
add_subdirectory(game)
</code></pre>
<p>game:</p>
<pre><code>cmake_minimum_required(VERSION 3.24.2)
project(GAME CXX)
add_executable(
game
src/main.cpp
)
target_link_libraries(
game
engine
)
set_property(TARGET game PROPERTY CXX_STANDARD 20)
</code></pre>
<p>engine:</p>
<pre><code>cmake_minimum_required(VERSION 3.24.2)
project(ENGINE CXX)
add_library(
engine
include/base/window.h
src/base/window.cpp
include/base/engine.h
src/base/engine.cpp
)
target_include_directories(
engine
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
)
target_link_libraries(
engine
glfw
GLEW
GL
)
set_property(TARGET engine PROPERTY CXX_STANDARD 20)
</code></pre>
<p>The problem is that VSCode can't find include files despite the fact the project compiles and runs successfully. As far as I understand it should get all the information from cmake files. Any advice in that regard?</p>
|
[
{
"answer_id": 74662888,
"author": "s0nicYouth",
"author_id": 1745543,
"author_profile": "https://Stackoverflow.com/users/1745543",
"pm_score": 1,
"selected": false,
"text": "\"configurationProvider\" \"ms-vscode.makefile-tools\" \"configurationProvider\": \"ms-vscode.cmake-tools\""
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1745543/"
] |
74,660,791
|
<p>I created a custom hook which takes a url and return the data</p>
<pre class="lang-js prettyprint-override"><code>import { useEffect, useState } from "react";
export function useHttp({ url }: { url: string }) {
const [data, setData] = useState<any>(null);
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
fetch(url, { signal })
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => {
if (err.name === "AbortError") {
console.log("successfully aborted");
} else {
// handle error
}
});
return () => {
// cancel the request before component unmounts
controller.abort();
};
}, []);
return data ;
}
</code></pre>
<p>I'm using the hook to fetch data in my main page, this works fine</p>
<pre class="lang-js prettyprint-override"><code>import { useState } from "react";
import { useHttp } from "./useHttp";
import "./App.css";
type person = { name: string; id: number };
function App() {
const [selectedId, setSelectedId] = useState<number>(1);
const people = useHttp({ url: "https://jsonplaceholder.typicode.com/users" });
return (
<div className="App">
{(people as unknown as person[])?.map(({ id, name }) => (
<button key={id} onClick={() => setSelectedId(id)}>
{name}
</button>
))}
<br />
<InnerComponent selectedId={selectedId} />
</div>
);
}
</code></pre>
<p>The part where I'm stuck is, I'm trying to reuse the hook again in a child component to fetch detail about depending on some value from the main component</p>
<pre class="lang-js prettyprint-override"><code>
const InnerComponent = ({ selectedId }: { selectedId: number }) => {
console.log(selectedId)
const person = useHttp({
url: `https://jsonplaceholder.typicode.com/users/${selectedId}`,
});
return <div>{person?.name}</div>;
};
</code></pre>
<p>also I can seen that the prop value has changed, my hook doesn't rerun, how can I implement that without rewriting the logic in useEffect?</p>
<p>I expected the hook to rerun when the prop changes and fetch me the result, but it only runs once in the initial render</p>
|
[
{
"answer_id": 74660825,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "export function useHttp({ url }: { url: string }) {\n const [data, setData] = useState<any>(null);\n\n useEffect(() => {\n // ...\n }, [url]);\n\n return data ;\n}\n"
},
{
"answer_id": 74661086,
"author": "Ricardo Romero",
"author_id": 8755155,
"author_profile": "https://Stackoverflow.com/users/8755155",
"pm_score": 1,
"selected": true,
"text": "url useEffect useEffect(() => {\n // ...\n}, [url]);\n"
}
] |
2022/12/02
|
[
"https://Stackoverflow.com/questions/74660791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20669639/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.