qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,532,270
|
<p>In this exercise, you'll use the for....of loop to iterate over an array and to iterate over an object's own properties.</p>
<p>Step 1. You are given an array of dairy products:</p>
<pre><code>var dairy = ['cheese', 'sour cream', 'milk', 'yogurt', 'ice cream', 'milkshake']
</code></pre>
<p>Create a function called logDairy. Within it, console log each of the items in the dairy array, using the for...of loop.
The expected output should be:</p>
<pre><code>cheese
sour cream
milk
yogurt
ice cream
milkshake
</code></pre>
<p>Step 2. You are given the following starter code:</p>
<pre><code>const animal = {
canJump: true
};
const bird = Object.create(animal);
bird.canFly = true;
bird.hasFeathers = true;
</code></pre>
<p>Create a function called <code>birdCan</code>, within it, loop over the bird object's properties and console log each one, using the for...of loop. Remember, you need to console log both the key and the value of each of the bird object's properties.</p>
<p>Step 3. Using the same starter code as in task 2, create a function called <code>animalCan</code> and within it, loop over all the properties in both the bird object and its prototype - the animal object - using the for...in loop.</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>// Task 1
function logDairy() {
const logDairy = ['cheese', 'sour cream', 'milk', 'yogurt', 'ice cream', 'milkshake'];
for (let i = 0; i < logDairy.length; i++) {
console.log(logDairy[i])
}
}
logDairy();
// Task 2
function birdCan() {
const animal = {
canJump: true
};
const bird = Object.create(animal);
bird.canFly = true;
bird.hasFeathers = true;
for (prop of Object.keys(bird)) {
console.log(prop + ":" + bird[prop])
}
}
birdCan();
// Task 3
function animalCan() {
const animal = {
canJump: true
};
const bird = Object.create(animal);
bird.canFly = true;
bird.hasFeathers = true;
for (prop in animal) {
console.log(prop);
}
for (prop in bird) {
console.log(prop);
}
}
animalCan();</code></pre>
</div>
</div>
</p>
<p>I have passed task 1 but not 2nd and 3rd</p>
<p>result</p>
<p>Passed: Console logged expected values for logDairy
FAILED: Console logged expected values for birdCan - returned canFly:truehasFeathers:true but expected canFly: truehasFeathers: true
FAILED: Console logged expected values for animalCan - returned canJumpcanFlyhasFeatherscanJump but expected canFly: truehasFeathers: truecanJump: true</p>
<p>tell me where did i go wrong?</p>
|
[
{
"answer_id": 74538872,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\ndata = []\nfor page in range(1, 3): # <-- increase number of pages here\n url = f\"https://www.allocine.fr/film/meilleurs/?page={page}\"\n soup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\n for movie in soup.select(\"li.mdl\"):\n data.append(\n {\n \"Title\": movie.h2.text.strip(),\n \"Note Presse\": movie.select_one(\n \".rating-item:-soup-contains(Presse) .stareval-note\"\n ).text.strip(),\n \"Note Spectateurs\": movie.select_one(\n \".rating-item:-soup-contains(Spectateurs) .stareval-note\"\n ).text.strip(),\n }\n )\n\ndf = pd.DataFrame(data)\nprint(df)\n Title Note Presse Note Spectateurs\n0 Forrest Gump 2,6 4,6\n1 La Liste de Schindler 4,2 4,6\n2 La Ligne verte 2,8 4,6\n3 12 hommes en colère 5,0 4,6\n4 Le Parrain 4,6 4,5\n5 Les Evadés 3,2 4,5\n6 Le Seigneur des anneaux : le retour du roi 3,8 4,5\n7 Le Roi Lion 3,4 4,5\n8 Vol au-dessus d'un nid de coucou 5,0 4,5\n9 The Dark Knight, Le Chevalier Noir 4,0 4,5\n10 Pulp Fiction 4,4 4,5\n11 Il était une fois dans l'Ouest 4,0 4,5\n12 Le Bon, la brute et le truand 4,1 4,5\n13 Il était une fois en Amérique 4,9 4,5\n14 Django Unchained 4,6 4,5\n15 Le Seigneur des anneaux : la communauté de l'anneau 3,7 4,5\n16 Gladiator 4,3 4,5\n17 Gran Torino 4,7 4,5\n18 Le Seigneur des anneaux : les deux tours 4,0 4,5\n19 Interstellar 3,8 4,5\n"
},
{
"answer_id": 74539654,
"author": "Raouf Yahiaoui",
"author_id": 18448274,
"author_profile": "https://Stackoverflow.com/users/18448274",
"pm_score": 0,
"selected": false,
"text": "page = requests.get(url_allocine + str(x))\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n\nfilms_all = soup.find_all('div',{'class':'card entity-card entity-card-list cf'})\ndef remove_word(string):\n return string.replace(\"Presse\",\"\").replace(\"Spectateurs\",\"\")\n\nfor film in films_all:\n title = film.find('h2').get_text(strip=True)\n rates = film.find_all('div', class_='rating-holder rating-holder-3')\n for rate in rates:\n note_presse = remove_word(rate.find_all(\"div\",{'class':'rating-item'})[0].get_text(strip=True))\n note_spectateur = remove_word(rate.find_all(\"div\",{'class':'rating-item'})[1].get_text(strip=True))\n\n property_info = {\n 'title': title,\n 'note_presse': note_presse,\n 'note_spectateur': note_spectateur,\n }\n df.append(property_info)\n# print(len(df))\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20571969/"
] |
74,532,299
|
<p>i am trying to send some virtual keycodes to an application while it is out of focus. I get it to work without a problem except for releasing normal keys.</p>
<p>I have tried:</p>
<p><code>win32api.SendMessage(hwnd, win32con.WM_KEYUP, VK_CODE["a"])</code></p>
<p><code>win32api.PostMessage(hwnd, win32con.WM_KEYUP, VK_CODE["a"])</code></p>
<p>releasing a key works perfectly with the left mouse button:</p>
<p><code>win32api.SendMessage(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0)</code></p>
<p>and using keydb_event:</p>
<p><code>win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)</code></p>
<p>But for some reason when trying to release a key using SendMessage it pressed down the button instead.</p>
|
[
{
"answer_id": 74538872,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\ndata = []\nfor page in range(1, 3): # <-- increase number of pages here\n url = f\"https://www.allocine.fr/film/meilleurs/?page={page}\"\n soup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\n for movie in soup.select(\"li.mdl\"):\n data.append(\n {\n \"Title\": movie.h2.text.strip(),\n \"Note Presse\": movie.select_one(\n \".rating-item:-soup-contains(Presse) .stareval-note\"\n ).text.strip(),\n \"Note Spectateurs\": movie.select_one(\n \".rating-item:-soup-contains(Spectateurs) .stareval-note\"\n ).text.strip(),\n }\n )\n\ndf = pd.DataFrame(data)\nprint(df)\n Title Note Presse Note Spectateurs\n0 Forrest Gump 2,6 4,6\n1 La Liste de Schindler 4,2 4,6\n2 La Ligne verte 2,8 4,6\n3 12 hommes en colère 5,0 4,6\n4 Le Parrain 4,6 4,5\n5 Les Evadés 3,2 4,5\n6 Le Seigneur des anneaux : le retour du roi 3,8 4,5\n7 Le Roi Lion 3,4 4,5\n8 Vol au-dessus d'un nid de coucou 5,0 4,5\n9 The Dark Knight, Le Chevalier Noir 4,0 4,5\n10 Pulp Fiction 4,4 4,5\n11 Il était une fois dans l'Ouest 4,0 4,5\n12 Le Bon, la brute et le truand 4,1 4,5\n13 Il était une fois en Amérique 4,9 4,5\n14 Django Unchained 4,6 4,5\n15 Le Seigneur des anneaux : la communauté de l'anneau 3,7 4,5\n16 Gladiator 4,3 4,5\n17 Gran Torino 4,7 4,5\n18 Le Seigneur des anneaux : les deux tours 4,0 4,5\n19 Interstellar 3,8 4,5\n"
},
{
"answer_id": 74539654,
"author": "Raouf Yahiaoui",
"author_id": 18448274,
"author_profile": "https://Stackoverflow.com/users/18448274",
"pm_score": 0,
"selected": false,
"text": "page = requests.get(url_allocine + str(x))\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n\nfilms_all = soup.find_all('div',{'class':'card entity-card entity-card-list cf'})\ndef remove_word(string):\n return string.replace(\"Presse\",\"\").replace(\"Spectateurs\",\"\")\n\nfor film in films_all:\n title = film.find('h2').get_text(strip=True)\n rates = film.find_all('div', class_='rating-holder rating-holder-3')\n for rate in rates:\n note_presse = remove_word(rate.find_all(\"div\",{'class':'rating-item'})[0].get_text(strip=True))\n note_spectateur = remove_word(rate.find_all(\"div\",{'class':'rating-item'})[1].get_text(strip=True))\n\n property_info = {\n 'title': title,\n 'note_presse': note_presse,\n 'note_spectateur': note_spectateur,\n }\n df.append(property_info)\n# print(len(df))\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20571682/"
] |
74,532,302
|
<p>I have a dataframe <code>df</code> which looks something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>key</th>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>0.6</td>
</tr>
<tr>
<td>x</td>
<td>0.5</td>
</tr>
<tr>
<td>x</td>
<td>0.43</td>
</tr>
<tr>
<td>x</td>
<td>0.56</td>
</tr>
<tr>
<td>y</td>
<td>13</td>
</tr>
<tr>
<td>y</td>
<td>14</td>
</tr>
<tr>
<td>y</td>
<td>0.4</td>
</tr>
<tr>
<td>y</td>
<td>0.1</td>
</tr>
</tbody>
</table>
</div>
<p>I'd like to replace the Last value for every <code>key</code> value with 0, so that the df looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>key</th>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>0.6</td>
</tr>
<tr>
<td>x</td>
<td>0.5</td>
</tr>
<tr>
<td>x</td>
<td>0.43</td>
</tr>
<tr>
<td>x</td>
<td>0</td>
</tr>
<tr>
<td>y</td>
<td>13</td>
</tr>
<tr>
<td>y</td>
<td>14</td>
</tr>
<tr>
<td>y</td>
<td>0.4</td>
</tr>
<tr>
<td>y</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried the following:</p>
<pre><code>for i in df['key'].unique():
df.loc[df['key'] == i, 'id'].iat[-1] = 0
</code></pre>
<p>the problem is it does not replace the actual value in the df. What am I missing? and perhaps there's an even better (performing) way to tackle this problem.</p>
|
[
{
"answer_id": 74532322,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "Series.duplicated key 0 DataFrame.loc df.loc[~df['key'].duplicated(keep='last'), 'id'] = 0\n\nprint (df)\n key id\n0 x 0.60\n1 x 0.50\n2 x 0.43\n3 x 0.00\n4 y 13.00\n5 y 14.00\n6 y 0.40\n7 y 0.00\n print (df.assign(mask=df['key'].duplicated(keep='last'),\n invert_mask=~df['key'].duplicated(keep='last')))\n key id mask invert_mask\n0 x 0.60 True False\n1 x 0.50 True False\n2 x 0.43 True False\n3 x 0.00 False True\n4 y 13.00 True False\n5 y 14.00 True False\n6 y 0.40 True False\n7 y 0.00 False True\n id df['id'] = df['key'].duplicated(keep='last').mul(df['id'])\nprint (df)\n key id\n0 x 0.60\n1 x 0.50\n2 x 0.43\n3 x 0.00\n4 y 13.00\n5 y 14.00\n6 y 0.40\n7 y 0.00\n"
},
{
"answer_id": 74532337,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "groupby.cumcount ascending=False df.loc[df.groupby('key').cumcount(ascending=False).eq(0), 'id'] = 0\n key id\n0 x 0.60\n1 x 0.50\n2 x 0.43\n3 x 0.00\n4 y 13.00\n5 y 14.00\n6 y 0.40\n7 y 0.00\n key id cumcount eq(0)\n0 x 0.60 3 False\n1 x 0.50 2 False\n2 x 0.43 1 False\n3 x 0.56 0 True\n4 y 13.00 3 False\n5 y 14.00 2 False\n6 y 0.40 1 False\n7 y 0.10 0 True\n df.loc[df.groupby('key').cumcount(ascending=False).eq(1), 'id'] = 0\n df.loc[df.groupby('key').cumcount().eq(2), 'id'] = 0\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11022199/"
] |
74,532,304
|
<p>I have the following variable for class label in my dataset:</p>
<pre class="lang-py prettyprint-override"><code>y = np.array([3, 3, 3, 2, 3, 1, 3, 2, 3, 3, 3, 2, 2, 3, 2])
</code></pre>
<p>To determine the number of each class, I do:</p>
<pre class="lang-py prettyprint-override"><code>np.unique(y, return_counts=True)
(array([1, 2, 3]), array([1, 5, 9]))
</code></pre>
<p>How then do I manipulate this into a list of tuples for <code>(label, n_samples)</code>? So that I have:</p>
<pre class="lang-py prettyprint-override"><code>[ (1,1), (2,5), (3,9) ]
</code></pre>
|
[
{
"answer_id": 74532424,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "zip out = list(zip(*np.unique(y, return_counts=True)))\n [(1, 1), (2, 5), (3, 9)] np.vstack(np.unique(y, return_counts=True)).T\n array([[1, 1],\n [2, 5],\n [3, 9]])\n"
},
{
"answer_id": 74532453,
"author": "Gandhi",
"author_id": 16977407,
"author_profile": "https://Stackoverflow.com/users/16977407",
"pm_score": 0,
"selected": false,
"text": "list_1 = ['a', 'b', 'c']\nlist_2 = [1, 2, 3]\n\n# option 1\nlist_of_tuples = list(\n map(\n lambda x, y: (x, y),\n list_1,\n list_2\n )\n)\n\n#option 2\nlist_of_tuples = [\n (list_1[index], list_2[index]) for index in range(len(list_1))\n]\n\n# option 3\nlist_of_tuples = list(zip(list_1, list_2))\n\nprint(list_of_tuples)\n# output is [('a', 1), ('b', 2), ('c', 3)]\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17487457/"
] |
74,532,342
|
<p>I do have one domino group (Access Control List only), lets call them <code>Main_Group</code>.
This group includes all employees, that I want to know on which other domino groups they are member of.</p>
<p>Members of <code>Main_Group</code>:</p>
<pre><code>- John Smith/ORGANIZATION
- Peter Smith/ORGANIZATION
- Jeff Smith/ORGANIZATION
</code></pre>
<p>Of course this list is much longer then these 3 entries.</p>
<p>I would look for each member in this group, in which other domino group this user is member and put this information into a CSV. The CSV should have a format like this:</p>
<pre><code>UserName;DominoGroups
John Smith;Domino_Group1,Domino_Group2,Domino_Group3
Peter Smith;Domino_Group2
Jeff Smith;Domino_Group1,Domino_Group3
</code></pre>
<p>Whats the best way to achieve to this information? Lotus Script, any View with formula? Or is there already a notes database is doing this?</p>
|
[
{
"answer_id": 74576080,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 0,
"selected": false,
"text": "Group names.nsf visited getGroupsForUser getGroupsForUser Function getGroupsForUser(userName As String) As String\n If userName=\"\" Then Exit function\n \n Dim ns As New NotesSession, namesDatabase As NotesDatabase\n Dim visited As Variant, groupKeyValueStore List As Variant\n Dim returnString As String, separator As String, i As Integer\n \n Set namesDatabase = ns.getDatabase(ns.Currentdatabase.Server, \"names.nsf\", False)\n visited = Null\n \n Call getGroupKeyValues(groupKeyValueStore, namesDatabase)\n Call searchGroupsRecursive(userName, visited, groupKeyValueStore)\n\n i=0\n returnString = \"\"\n ForAll item In visited\n If i=0 Then separator = \"\"\n If i=1 Then separator = \";\"\n If i>1 Then separator = \",\" \n returnString = returnString + separator + item\n i = i + 1\n End forall\n\n getGroupsForUser = returnString\nEnd Function\n getGroupKeyValues Public Function getGroupKeyValues(groupKeyValueStore List As Variant , namesDatabase As NotesDatabase)\n Dim groupView As NotesView, doc As NotesDocument, members As Variant, groupName As String\n Dim separator As String, values As Variant, i As Integer, tempString(0) As String\n \n Set groupView = namesDatabase.getView(\"Groups\")\n Set doc=groupView.Getfirstdocument()\n \n Do Until doc Is Nothing\n groupName = doc.ListName(0)\n members = doc.getItemValue(\"Members\")\n ForAll member In members\n If IsElement(groupKeyValueStore(member)) Then\n If IsNull(ArrayGetIndex(groupKeyValueStore(member), groupName)) Then\n values = groupKeyValueStore(member)\n i = ubound(values) + 1\n ReDim Preserve values(i)\n values(i) = groupName\n groupKeyValueStore(member) = values\n End If\n Else\n tempString(0) = groupName\n groupKeyValueStore(member) = tempString\n End If\n End ForAll\n Set doc=groupView.getNextDocument(doc)\n Loop\nEnd Function\n searchGroupsRecursive Public Function searchGroupsRecursive(userName As String, visited As Variant, groupKeyValueStore List As Variant) As Variant\n Dim length As Integer, userNotesName As NotesName, fullUserName As String\n Dim tempArray(0) As String\n \n Set userNotesName = New NotesName(userName)\n fullUserName = userNotesName.Canonical\n \n If IsNull(visited) Then\n tempArray(0) = userName\n visited = tempArray\n Else\n length = UBound(visited)\n ReDim Preserve visited(length + 1)\n visited(length + 1) = userName \n End If\n \n If Not isElement(groupKeyValueStore(fullUserName)) Then Exit function\n\n ForAll item In groupKeyValueStore(fullUserName)\n Call searchGroupsRecursive(CStr(item), visited, groupKeyValueStore)\n End ForAll\nEnd Function\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9285015/"
] |
74,532,364
|
<p>Hi i have two datasets which represent to different groups:</p>
<pre><code>student_details <- c("John", "Henrick", "Maria", "Lucas", "Ali")
student_class <- c("High School", "College", "Preschool", "High School", "college")
df1 <- data.frame(student_details, student_class)
</code></pre>
<p>#another dataframe</p>
<pre><code>Student_details<-c("Bracy","Evin")
Student_class<-c("High school","College")
Student_rank<-c("A","A+")
df2<-data.frame(Student_class,Student_details,Student_rank)
df2
</code></pre>
<p>I need to rbind df1 and df2 even though the lenght is unequal and make a third column in the final called "dataset" which indicates which dataset it is from:</p>
|
[
{
"answer_id": 74532994,
"author": "Flap",
"author_id": 20520733,
"author_profile": "https://Stackoverflow.com/users/20520733",
"pm_score": 2,
"selected": false,
"text": "rbindlist() data.table #convert uppercase letters in column names to lower case. \nnames(df2) <- tolower(names(df2))\n library(data.table)\nfinal_df <- rbindlist(list(df1, df2), use.names = T, fill = T, idcol = \"dataset\")\nfinal_df \n dataset student_details student_class student_rank\n1: 1 John High School <NA>\n2: 1 Henrick College <NA>\n3: 1 Maria Preschool <NA>\n4: 1 Lucas High School <NA>\n5: 1 Ali college <NA>\n6: 2 Bracy High school A\n7: 2 Evin College A+\n"
},
{
"answer_id": 74533034,
"author": "chris jude",
"author_id": 14579051,
"author_profile": "https://Stackoverflow.com/users/14579051",
"pm_score": 2,
"selected": false,
"text": "student_details <- c(\"John\", \"Henrick\", \"Maria\", \"Lucas\", \"Ali\")\nstudent_class <- c(\"High School\", \"College\", \"Preschool\", \"High School\", \"college\")\ndf1 <- data.frame(student_details, student_class)\n\n\nstudent_details<-c(\"Bracy\",\"Evin\")\nstudent_class<-c(\"High school\",\"College\")\nstudent_rank<-c(\"A\",\"A+\")\ndf2<-data.frame(student_details,student_class,student_rank)\n\nlibrary(dplyr)\n\ndf_full<-bind_rows(df1,df2)\n"
},
{
"answer_id": 74533290,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "df1 df2 merge > merge(df1, df2, all = TRUE, sort = FALSE)\n student_details student_class student_rank\n1 John High School <NA>\n2 Henrick College <NA>\n3 Maria Preschool <NA>\n4 Lucas High School <NA>\n5 Ali college <NA>\n6 Bracy High school A\n7 Evin College A+\n data.table rbindlist"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19766411/"
] |
74,532,372
|
<p>I was discussing with a colleague if there is a built-in (or clean) way to use Pathlib to traverse through an arbitrary Path to find a given parent folder, for example the root of your repository (which may differ per user that has a local copy of said repo). I simulated the desired behaviour below:</p>
<pre><code>from pathlib import Path
def find_parent(path: Path, target_parent: str) -> Path:
for part in path.parts[::-1]:
if part != target_parent:
path = path.parent
else:
break
return path
path = Path("/some/arbitrarily/long/path/ROOT_FOLDER/subfolder1/subfolder2/file.py")
root = find_parent(path, "ROOT_FOLDER")
assert root == Path("/some/arbitrarily/long/path/ROOT_FOLDER")
</code></pre>
<p>Is there an easier way to achieve this?</p>
|
[
{
"answer_id": 74532549,
"author": "Chris",
"author_id": 354577,
"author_profile": "https://Stackoverflow.com/users/354577",
"pm_score": 2,
"selected": false,
"text": "path.parents def find_parent(path: Path, target_parent: str) -> Path | None:\n # `path.parents` does not include `path`, so we need to prepend it if it is\n # to be considered\n for parent in [path] + list(path.parents):\n if parent.name == target_parent:\n return parent\n"
},
{
"answer_id": 74532701,
"author": "Jerrit",
"author_id": 4464267,
"author_profile": "https://Stackoverflow.com/users/4464267",
"pm_score": 0,
"selected": false,
"text": "root = [parent for parent in path.parents if parent.name == \"ROOT_FOLDER\"][0] root = next((parent for parent in path.parents if parent.name == \"ROOT_FOLDER\"), None)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464267/"
] |
74,532,414
|
<p>I've got a Xamarin.Forms Project containing an Android and an iOS Platform Project.</p>
<p>I've got my whole application working on Android and I am now struggling on the iOS part. I can't get my images to display on iOS.</p>
<p>I've followed the <a href="https://learn.microsoft.com/de-de/xamarin/ios/app-fundamentals/images-icons/displaying-an-image?tabs=windows" rel="nofollow noreferrer">Microsoft guide</a> on how to work with images on Xamarin.iOS, but it's simply not working.</p>
<p>I have created a minimum example from a new project and <a href="https://github.com/daniel-streetec/Xamarin_ImageTest" rel="nofollow noreferrer">uploaded it to GitHub</a>, it can be found here.</p>
<p>Output: On Android, the image is being displayed fine, on iOS, the screen stays empty. In addition to that, the logs I've added to AppDelegate.cs show, that the images cannot be found by using <code>UIImage.FromBundle()</code></p>
<p>I've also checked the CSProject file of the iOS project, but it already contains the <code><ImageAsset></code> item groups.</p>
<p>I am on Visual Studio Professional 2022 (Windows) Version 17.4.1</p>
<p>Can someone please have a look into this? I am going crazy...</p>
|
[
{
"answer_id": 74532549,
"author": "Chris",
"author_id": 354577,
"author_profile": "https://Stackoverflow.com/users/354577",
"pm_score": 2,
"selected": false,
"text": "path.parents def find_parent(path: Path, target_parent: str) -> Path | None:\n # `path.parents` does not include `path`, so we need to prepend it if it is\n # to be considered\n for parent in [path] + list(path.parents):\n if parent.name == target_parent:\n return parent\n"
},
{
"answer_id": 74532701,
"author": "Jerrit",
"author_id": 4464267,
"author_profile": "https://Stackoverflow.com/users/4464267",
"pm_score": 0,
"selected": false,
"text": "root = [parent for parent in path.parents if parent.name == \"ROOT_FOLDER\"][0] root = next((parent for parent in path.parents if parent.name == \"ROOT_FOLDER\"), None)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16060704/"
] |
74,532,417
|
<p>I've a MongoDB collection that contains records with a field called <strong>createdAt</strong>, I want to get the last createdAt in the previous month of a given date using mongoTemplate aggregation in a spring boot application.</p>
<p>example of a record:</p>
<pre class="lang-json prettyprint-override"><code>{
createdAt: new Date('2022-11-01'),
//other fields ...
}
</code></pre>
<p><strong>Note:</strong></p>
<p>Let say for 22/11/2022 given date, and we have records with createdAt fields are 12/10/2022, 22/10/2022, 27/10/2022; I wanna get the date : 27/10/2022</p>
|
[
{
"answer_id": 74532549,
"author": "Chris",
"author_id": 354577,
"author_profile": "https://Stackoverflow.com/users/354577",
"pm_score": 2,
"selected": false,
"text": "path.parents def find_parent(path: Path, target_parent: str) -> Path | None:\n # `path.parents` does not include `path`, so we need to prepend it if it is\n # to be considered\n for parent in [path] + list(path.parents):\n if parent.name == target_parent:\n return parent\n"
},
{
"answer_id": 74532701,
"author": "Jerrit",
"author_id": 4464267,
"author_profile": "https://Stackoverflow.com/users/4464267",
"pm_score": 0,
"selected": false,
"text": "root = [parent for parent in path.parents if parent.name == \"ROOT_FOLDER\"][0] root = next((parent for parent in path.parents if parent.name == \"ROOT_FOLDER\"), None)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18290052/"
] |
74,532,418
|
<p>Per <a href="https://javascript.info/async-await" rel="nofollow noreferrer">javascript.info</a>, <code>await</code> "suspends the function execution until the promise settles, and then resumes it with the promise result." If this is the case, why do we sometimes need multiple <code>await</code> keywords within one function?</p>
<p>Consider the following example:</p>
<pre><code>async function fetchdata() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/")
const data = await response.json()
console.log(data)
}
fetchdata()
</code></pre>
<p>This returns an array of objects retrieved from the given URL. But if <code>await</code> really suspends execution of <code>fetchdata</code>, I would expect to get the same return value if I removed the second <code>await </code>keyword, since the resulting <code>const data = response.json()</code> should still only run once <code>response</code> is settled.</p>
<p>However, when I run the below code, <code>fetchdata()</code> returns a pending Promise, i.e. it appears <code>response.json()</code> was run before <code>response</code> was actually settled.</p>
<pre><code>async function fetchdata() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/")
const data = response.json()
console.log(data)
}
fetchdata()
</code></pre>
<p>Can someone explain to me what I am misunderstanding about the <code>await</code> keyword?</p>
|
[
{
"answer_id": 74532439,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "await json() fetch() body"
},
{
"answer_id": 74532477,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 0,
"selected": false,
"text": "json()"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511269/"
] |
74,532,432
|
<h2>Problem definition</h2>
<p>Assume we have a React component <code>C</code> that accepts properties <code>Props</code>. <code>Props</code> have a field named <code>edges</code>. <code>Edges</code> are defined as a tuple of length 1-4 composed of string literals <code>top</code>, <code>bottom</code>, <code>left</code>, <code>right</code>.</p>
<p>Task: restrict the <code>edges</code> param to a tuple with no duplicates.</p>
<p>E.g.:</p>
<p>This should compile fine:</p>
<pre class="lang-js prettyprint-override"><code><C edges={['top', 'bottom']} />
</code></pre>
<p>while this should fail:</p>
<pre class="lang-js prettyprint-override"><code><C edges={['top', 'top']} />
</code></pre>
<h2>What I have so far</h2>
<pre class="lang-js prettyprint-override"><code>
// Our domain types
type Top = 'top';
type Bottom = 'bottom';
type Left = 'left';
type Right = 'right';
type Edge = Top | Bottom | Left | Right;
// A helper types that determines if a certain tuple contains duplicate values
type HasDuplicate<TUPLE> = TUPLE extends [infer FIRST, infer SECOND]
? FIRST extends SECOND
? SECOND extends FIRST
? true
: false
: false
: TUPLE extends [first: infer FIRST, ...rest: infer REST]
? Contains<FIRST, REST> extends true
? true
: HasDuplicate<REST>
: never;
// Just some helper type for convenience
type Contains<X, TUPLE> = TUPLE extends [infer A]
? X extends A
? A extends X
? true
: false
: false
: TUPLE extends [a: infer A, ...rest: infer REST]
? X extends A
? A extends X
? true
: Contains<X, REST>
: Contains<X, REST>
: never;
</code></pre>
<p>With the above I can already get this:</p>
<pre class="lang-js prettyprint-override"><code>type DoesNotHaveDuplicates = HasDuplicate<[1, 2, 3]>; // === false
type DoesHaveDuplicates = HasDuplicate<[1, 0, 2, 1]>; // === true
</code></pre>
<h2>Where I am stuck</h2>
<p>Let's say we have a component C:</p>
<pre class="lang-js prettyprint-override"><code>
// For simple testing purposes, case of a 3-value tuple
type MockType<ARG> = ARG extends [infer T1, infer T2, infer T3]
? HasDuplicate<[T1, T2, T3]> extends true
? never
: [T1, T2, T3]
: never;
interface Props<T> {
edges: MockType<T>;
}
function C<T extends Edge[]>(props: Props<T>) {
return null;
}
</code></pre>
<p>The above works but only like this:</p>
<pre class="lang-js prettyprint-override"><code>// this compiles:
<C<[Top, Left, Right]> edges={['top', 'left', 'right']} />
// this does not (as expected):
<C<[Top, Left, Left]> edges={['top', 'left', 'left']} />
</code></pre>
<p>What I cannot figure out is how to get rid of the generics in component instantiation and make typescript deduce the types at compile time based on the value provided to the <code>edges</code> property.</p>
|
[
{
"answer_id": 74532598,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 3,
"selected": true,
"text": "MockType HasDuplicate<T> false edges [...T] interface Props<T extends Edge[]> {\n edges: HasDuplicate<T> extends false ? [...T] : never;\n}\n T T Edge // these compile\nconst a = (\n <>\n <C<[Top, Left, Right]> edges={['top', 'left', 'right']} />\n <C edges={['top', 'left', 'right']} />\n </>\n)\n\n// these do not compile\nconst b = (\n <>\n <C<[Top, Left, Left]> edges={['top', 'left', 'left']} />\n <C edges={['top', 'left', 'left']} />\n </>\n)\n HasDuplicate type HasDuplicate<TUPLE extends any[]> = \n TUPLE extends [infer L, ...infer R]\n ? L extends R[number]\n ? true\n : HasDuplicate<R>\n : false\n"
},
{
"answer_id": 74532856,
"author": "captain-yossarian from Ukraine",
"author_id": 8495254,
"author_profile": "https://Stackoverflow.com/users/8495254",
"pm_score": 1,
"selected": false,
"text": "edges import React from \"react\"\n\ntype Top = 'top';\ntype Bottom = 'bottom';\ntype Left = 'left';\ntype Right = 'right';\ntype Edge = Top | Bottom | Left | Right;\n\n// https://github.com/microsoft/TypeScript/issues/13298#issuecomment-692864087\ntype TupleUnion<U extends string, R extends any[] = []> = {\n [S in U]: Exclude<U, S> extends never ? [...R, S?] : TupleUnion<Exclude<U, S>, [...R, S?]>;\n}[U];\n\n\ninterface Props {\n edges: TupleUnion<Edge>\n}\n\nfunction C(props: Props) {\n return null;\n}\n\n(\n <>\n // this compiles:\n <C edges={['top', 'left', 'right']} />\n\n // this does not (as expected):\n <C edges={['top', 'left', 'left']} />\n\n // this compiles:\n <C edges={['top', 'left', 'right']} />\n\n // this does not\n <C edges={['top', 'left', 'left']} />\n </>\n)\n import React from \"react\"\n\ntype WithDuplicates<Keys extends string[], Acc extends string[] = []> =\n Keys extends []\n ? Acc\n : Keys extends [infer First extends string, ...infer Tail extends string[]]\n ? First extends Acc[number]\n ? WithDuplicates<Tail, [...Acc, never]>\n : WithDuplicates<Tail, [...Acc, First]>\n : Keys\n\ninterface Props<T extends string[]> {\n edges: T\n}\n\nfunction C<E extends string, Edges extends E[]>(props: Props<WithDuplicates<[...Edges]>>) {\n return null;\n}\n\n(\n <>\n // this compiles:\n <C edges={['top', 'left', 'right']} />\n\n // this does not (as expected):\n <C edges={['top', 'left', 'left']} />\n\n // this compiles:\n <C edges={['top', 'left', 'right']} />\n\n // this does not\n <C edges={['top', 'left', 'left']} />\n </>\n)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1721393/"
] |
74,532,441
|
<p>Here's the code I got so far:</p>
<pre><code>x = 2
y = 3
print('hi' + str(x) + 'hello' + str(y))
</code></pre>
<p>Is there any simpler way to concatenate strings and ints? I would like some examples.</p>
|
[
{
"answer_id": 74532466,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 1,
"selected": false,
"text": "x = 2\ny = 3\n\nprint(f'hi {x} hello {y}')\n"
},
{
"answer_id": 74532555,
"author": "user2094482",
"author_id": 2094482,
"author_profile": "https://Stackoverflow.com/users/2094482",
"pm_score": -1,
"selected": false,
"text": "# Concatenating a String and an Int in Python with f-strings\nword = 'datagy'\ninteger = 2022\nnew_word = f'{word}{integer}'\nprint(new_word)\n# Returns: datagy2022\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398610/"
] |
74,532,465
|
<p>Below specified is my data</p>
<pre><code>Id , Name , IsBillable
1 One 1
2 two 0
3. three 0
</code></pre>
<p>this will be the dropdown value below i'll share the html dropdown code</p>
<pre><code><mat-option *ngFor="let option of masterAppointmentTypes" [value]="option.id">
{{option.value}}
</mat-option>
</code></pre>
<p>the above html works. All i need to do is: get the IsBillable data at the below code</p>
<pre><code>if(this.appointmentForm.get('id').value == this.appointmentForm.get('id').value && this.appointmentForm.get('IsBillable').value){
this.openPaymentDialog(appointmentData, queryParams)
}
else{
this.createAppointment(appointmentData, queryParams);
}
</code></pre>
<p>at the above code i get the ID value according to the selected dropdown but i didn't get IsBillable data according to the selected id.Below code is my formBuilder.</p>
<pre><code>const configControls = {
'AppointmentTypeID': [appointmentObj.appointmentTypeID, Validators.required],
'IsBillable' : [appointmentObj.isBillable,Validators.required],
}
this.appointmentForm = this.formBuilder.group(configControls);
</code></pre>
|
[
{
"answer_id": 74532466,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 1,
"selected": false,
"text": "x = 2\ny = 3\n\nprint(f'hi {x} hello {y}')\n"
},
{
"answer_id": 74532555,
"author": "user2094482",
"author_id": 2094482,
"author_profile": "https://Stackoverflow.com/users/2094482",
"pm_score": -1,
"selected": false,
"text": "# Concatenating a String and an Int in Python with f-strings\nword = 'datagy'\ninteger = 2022\nnew_word = f'{word}{integer}'\nprint(new_word)\n# Returns: datagy2022\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19652485/"
] |
74,532,473
|
<p>I've certains amounts of item in list within a horizontal scrollbar. I want to load more item via a function when user reaches the end of scrollbar.
I've tried to implement it via (scroll)="onScroll()" but this function won't be called if scollbar can't be scollred further. So, how do I know about the end of an horizontal scollbar?</p>
<p>I've tried it via tracking how much distance, a scrollbar have crossed.</p>
|
[
{
"answer_id": 74532466,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 1,
"selected": false,
"text": "x = 2\ny = 3\n\nprint(f'hi {x} hello {y}')\n"
},
{
"answer_id": 74532555,
"author": "user2094482",
"author_id": 2094482,
"author_profile": "https://Stackoverflow.com/users/2094482",
"pm_score": -1,
"selected": false,
"text": "# Concatenating a String and an Int in Python with f-strings\nword = 'datagy'\ninteger = 2022\nnew_word = f'{word}{integer}'\nprint(new_word)\n# Returns: datagy2022\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572057/"
] |
74,532,474
|
<h2>No secrets</h2>
<p>All the documentation I have seen so far states <a href="https://stackoverflow.com/questions/62700005/safe-storage-of-app-secrets-for-blazor-webassembly-app">there is no way you could possibly securely store a secret or sensitive data</a>.</p>
<h2>What are others doing?</h2>
<p>I was wondering how others have attempted to resolve this issue so far. I have not been able to find a suggestions as to what an alternative would look like, just people saying it can't (or shouldn't) be done.</p>
<p>Should I even be using reCaptcha (or any other captcha system that required a site-key to be passed to it) in a Blazor WASM project, or should I be considering something through my Web API? I am not sure if this would be barking up the wrong tree though.</p>
<p>Even the aspnetcore repo is <a href="https://github.com/dotnet/aspnetcore/issues/23620" rel="nofollow noreferrer">less that helpful</a>, the same "just don't do it". For things like connection strings, I understand the solution of just calling a RESTful API that has the connection string details in, but I don't see how this solution could be applied to this issue.</p>
<p>Any help would be greatly appreciated.</p>
<p>I have not been able to find any reasonable solutions to try so far.</p>
|
[
{
"answer_id": 74532466,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 1,
"selected": false,
"text": "x = 2\ny = 3\n\nprint(f'hi {x} hello {y}')\n"
},
{
"answer_id": 74532555,
"author": "user2094482",
"author_id": 2094482,
"author_profile": "https://Stackoverflow.com/users/2094482",
"pm_score": -1,
"selected": false,
"text": "# Concatenating a String and an Int in Python with f-strings\nword = 'datagy'\ninteger = 2022\nnew_word = f'{word}{integer}'\nprint(new_word)\n# Returns: datagy2022\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18577622/"
] |
74,532,510
|
<p>I have file <code>IP.txt</code>:</p>
<pre><code>192.168.69.100
192.168.69.141
</code></pre>
<p>I also have file <code>Ports.txt</code>:</p>
<pre><code>open port: 21 on IP: 192.168.69.100 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.100 with banner:
SSH-OpenSSH
open port: 21 on IP: 192.168.69.141 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.141 with banner:
SSH-OpenSSH
</code></pre>
<p>I need the 2 files merged into <code>Results.txt</code>, like so:</p>
<pre><code>192.168.69.100
open port: 21 on IP: 192.168.69.100 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.100 with banner:
SSH-OpenSSH
192.168.69.141
open port: 21 on IP: 192.168.69.141 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.141 with banner:
SSH-OpenSSH
</code></pre>
<p>Note how there is a new line empty space after the port's banner and before the next IP.</p>
<p>So, to grab the <code>open port... on 192.168.69....</code> line and the line below it, then place them after the <code>192.168.69....</code> line, then finally adding a new empty line.</p>
<p>How can i achieve this?</p>
|
[
{
"answer_id": 74532466,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 1,
"selected": false,
"text": "x = 2\ny = 3\n\nprint(f'hi {x} hello {y}')\n"
},
{
"answer_id": 74532555,
"author": "user2094482",
"author_id": 2094482,
"author_profile": "https://Stackoverflow.com/users/2094482",
"pm_score": -1,
"selected": false,
"text": "# Concatenating a String and an Int in Python with f-strings\nword = 'datagy'\ninteger = 2022\nnew_word = f'{word}{integer}'\nprint(new_word)\n# Returns: datagy2022\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460608/"
] |
74,532,536
|
<p>I have a program that I run in two different pcs using the same version of Julia. I wouldn't like to put a specific snippet of the program because on the one hand is a little complicated and, on the other, I feel there must be something that depends on the machine rather than in my program itself.</p>
<p>So here are some results I get in both machines:</p>
<pre><code>1 1.0000000000582077 15.124999999941792
2 1.9999999999417923 27.536972172616515
3 3.000000000523869 45.722282028989866
</code></pre>
<hr />
<pre><code>1 1.0 15.125
2 2.0 27.53697217302397
3 3.0 45.722282028466
</code></pre>
<p>The problem is the rounding errors, I don't know at which point they are introduced that make the results slightly different. It cannot be a formatting error (I use exactly the same program in both cases) and it cannot be a machine epsilon error (the machine epsilon in both cases is <code>>2.220446049250313e-16</code>).</p>
<p>I can only think at the moment that the extra packages that I use, <code>SparseArrays</code>, <code>LinearAlgebra</code> or <code>FFTW</code> is introducing this artificial error, but I'm not sure of it.</p>
<hr />
<p>EDIT:</p>
<p>Ok so here it goes a minimal example (perhaps the arrays doesn't need to be like [a,a], where a is a sparse array itself). I had to modify my program in order to isolate the problem, so the results I will discuss below are slightly different than those I wrote above. Yet, both show the non-negligible error I mention.</p>
<pre><code>using LinearAlgebra
using SparseArrays
using FFTW
const Nsites = 10000
function Opbuild1(::Val{true})
Up = spzeros(Complex{Float64}, Nsites, Nsites)
N = div(Nsites,2)
ii = 1
for p in 0:(N-1)
Up[ii,ii] = exp(-1.0im*p^2*0.25)
Up[ii + N, ii + N] = exp(-1.0im*(p - N)^2*0.25)
ii += 1
end
return kron(sparse(Matrix(1.0I, 2, 2)), Up)
end
function Opbuild2(::Val{true})
pop = spzeros(Float64, Nsites, Nsites)
N = div(Nsites,2)
ii = 1
for p in 0:(N-1)
pop[ii,ii] = p
pop[ii+N,ii+N] = (p-N)
ii += 1
end
return kron(sparse(Matrix(1.0I, 2, 2)), pop)
end
function initst1(BoolN, irealiz)
psi = spzeros(Complex{Float64}, Nsites)
a = range(680,stop=783,step=1)
x = a[irealiz]
psi[x] = 1.0
psi = kron([1.0,1.0im]/sqrt(2), psi)
return psi, x
end
function ifftcustom(array)
array = Array(array)
array1 = copy(array)
array1[1:Nsites] = ifft(array[1:Nsites])
array1[Nsites+1:end] = ifft(array[Nsites+1:end])
return array1/norm(array1)
end
function fftcustom(array)
array = Array(array)
array1 = copy(array)
array1[1:Nsites] = fft(array[1:Nsites])
array1[Nsites+1:end] = fft(array[Nsites+1:end])
return array1/norm(array1)
end
function main()
boolN = rem(Nsites,2) == 0
Operator = Opbuild1(Val(boolN))
Operator_p = Opbuild2(Val(boolN))
#
psi0_inp, pinit = initst1(boolN, 1) #!
psi0_inp = round.(ifftcustom(Operator*psi0_inp), digits=15) # (*)See below
psi0_inp = round.(fftcustom(psi0_inp), digits=15)
psi0_inp = round.(psi0_inp, digits=15)
@show psi0_inp'*Operator_p*psi0_inp
end
main()
</code></pre>
<p>So the difference is the following. If in <code>(*)</code> I run instead the line
<code>psi0_inp = round.(ifftcustom(psi0_inp), digits=15)</code>, in the <code>@show</code> part I obtain <code>679.000000000001</code> in both machines. On the other hand, if I run it as I wrote it in the code, in one machine I get <code>679.0000000000001 + 0.0im</code> but in the other <code>679.0 + 1.2036944776504516e-16im</code>.</p>
<p>I don't care about the -16im because this is a "zero" in double precision, but indeed the real part is of the order of -13 which is not quite a zero in double precision.</p>
|
[
{
"answer_id": 74532850,
"author": "Kristoffer Carlsson",
"author_id": 6512648,
"author_profile": "https://Stackoverflow.com/users/6512648",
"pm_score": 2,
"selected": false,
"text": "--check-bounds=yes"
},
{
"answer_id": 74535127,
"author": "StefanKarpinski",
"author_id": 659248,
"author_profile": "https://Stackoverflow.com/users/659248",
"pm_score": 3,
"selected": false,
"text": "+ * (x + y) + z x + (y + z)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820579/"
] |
74,532,592
|
<p>i have a Table with Name, Date, Number, gender.
below are the values.
i just need to export them to another file.
the headline with "Name, Date, Number, gernder.below are the values" needs to be in "A",every value which needs to be in "B"</p>
<p>for example:</p>
<p>Old sheet</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Number</th>
<th>gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>01.01.01</td>
<td>7382</td>
<td>male</td>
</tr>
<tr>
<td>Peter</td>
<td>01,02,02</td>
<td>6482</td>
<td>male</td>
</tr>
</tbody>
</table>
</div>
<p>This is how is should look like in Sheet nr 2:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<td>John</td>
</tr>
<tr>
<td>Date</td>
<td>01.01.01</td>
</tr>
<tr>
<td>Number</td>
<td>7382</td>
</tr>
<tr>
<td>gender</td>
<td>male</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Name</td>
<td>Peter</td>
</tr>
<tr>
<td>Date</td>
<td>01.02.02,</td>
</tr>
<tr>
<td>Number</td>
<td>6482</td>
</tr>
<tr>
<td>gender</td>
<td>male</td>
</tr>
</tbody>
</table>
</div>
<p>I made a macro but I'm not able to make it full auto for the whole document.</p>
<pre><code>Sub Makro7()
'
' Makro7 Makro
'
'
Range("A1:O1,A2:O2").Select
Range("A2").Activate
Selection.Copy
Sheets("Export").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets("Exportieren").Select
Range("A1:O1,A3:O3").Select
Range("A3").Activate
Application.CutCopyMode = False
Selection.Copy
Sheets("Export").Select
Range("A16").Select
Range("A16").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
End Sub
</code></pre>
<p>thank you very much for your time</p>
<p>I tried my best, but i not that talented<3</p>
|
[
{
"answer_id": 74532850,
"author": "Kristoffer Carlsson",
"author_id": 6512648,
"author_profile": "https://Stackoverflow.com/users/6512648",
"pm_score": 2,
"selected": false,
"text": "--check-bounds=yes"
},
{
"answer_id": 74535127,
"author": "StefanKarpinski",
"author_id": 659248,
"author_profile": "https://Stackoverflow.com/users/659248",
"pm_score": 3,
"selected": false,
"text": "+ * (x + y) + z x + (y + z)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570518/"
] |
74,532,657
|
<p>I have problems in counting with a dictionary the occurrences of letters in a list of words of different length for each index of letters. The list is ordered from longest to shortest word. Like so:</p>
<pre class="lang-py prettyprint-override"><code>main_list = ['elephant','mouse','tiger','dog']
</code></pre>
<p>For index <code>0</code> the dictionary should be:<br />
<code>{'e':1,'m':,'t':1,'d':1}</code></p>
<p>For index <code>1</code>:<br />
<code>{'l':1,'o':2,'i':1}</code></p>
<p>For index <code>2</code>:<br />
<code>{'e':1,'u':1,'g':2}</code></p>
<p>and so on until the longest word is ended.</p>
<p>The output should be a list of dictionaries:</p>
<pre class="lang-py prettyprint-override"><code>main_list = [{'e':1,'m':1,'t':1,'d':1},{'l':1,'o':2,'i':1},{'e':1,'u':1,'g':2}...]
</code></pre>
<p>(also the shortest word should be included)</p>
<p>To solve the problem I created lists of letters for each index and then made a dictionary to count the occurrences of the letters for each list of letters, but I was wondering if there is a way to count directly in the list of words the occurrences of letters for each index.</p>
|
[
{
"answer_id": 74532850,
"author": "Kristoffer Carlsson",
"author_id": 6512648,
"author_profile": "https://Stackoverflow.com/users/6512648",
"pm_score": 2,
"selected": false,
"text": "--check-bounds=yes"
},
{
"answer_id": 74535127,
"author": "StefanKarpinski",
"author_id": 659248,
"author_profile": "https://Stackoverflow.com/users/659248",
"pm_score": 3,
"selected": false,
"text": "+ * (x + y) + z x + (y + z)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20494445/"
] |
74,532,675
|
<pre class="lang-none prettyprint-override"><code>> root# ps -ef | grep [j]ava | awk '{print $2,$9}'
> 45134 -Dapex=APEC
> 45135 -Dapex=JAAA
> 45136 -Dapex=APEC
</code></pre>
<p>I need to put the first APEC of first as First PID, third line of APEC and Second PID and last one as Third PID.</p>
<p>I've tried awk but no expected result.</p>
<pre class="lang-none prettyprint-override"><code>> First_PID =ps -ef | grep [j]ava | awk '{print $2,$9}'|awk '{if ($0 == "[^0-9]" || $1 == "APEC:") {print $0; exit;}}'
</code></pre>
<p>Expected result should look like this.</p>
<pre class="lang-none prettyprint-override"><code>> First_PID=45134
> Second_PID=45136
> Third_PID=45135
</code></pre>
|
[
{
"answer_id": 74532794,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk awk ps -ef | grep [j]ava | \nawk '\n{\n val=$2 OFS $9\n match(val,/([0-9]+) -Dapex=APEC ([0-9]+) -Dapex=JAAA\\s([0-9]+)/,arr)\n print \"First_PID=\"arr[1],\"Second_PID=\",arr[3],\"Third_PID=\",arr[2]\n}\n'\n"
},
{
"answer_id": 74535469,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 1,
"selected": false,
"text": "$ input=(\"1 APEC\" \"2 JAAA\" \"3 APEC\")\n$ printf '%s\\n' \"${input[@]}\" | grep APEC | sed -n '2p'\n3 APEC\n input=(...) printf '%s\\n' \"${input[@]}\" input grep APEC APEC sed -n sed sed -n '2p'"
},
{
"answer_id": 74539657,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 0,
"selected": false,
"text": "ps -ef |\n awk '/java[ ].* -Dapex=APEC/{print $2\" \"$9; next; }\n /java[ ]/{non[NR]=$2\" \"$9}\n END{ for (rec in non) print non[rec] }'\n mapfile -t pids < <( ps -ef | awk '/java[ ].* -Dapex=APEC/{print $2; next; }\n /java[ ]/{non[NR]=$2} END{ for (rec in non) print non[rec] }' )\n"
},
{
"answer_id": 74561665,
"author": "Teerawat ",
"author_id": 19145217,
"author_profile": "https://Stackoverflow.com/users/19145217",
"pm_score": 0,
"selected": false,
"text": "FIRST_PID=$(ps -ef | grep APEC | grep -v grep | awk '{print $2}'| sed -n '1p') \nSECOND_PID=$(ps -ef | grep APEC | grep -v grep | awk '{print $2}'| sed -n '2p') \nJAWS_PID=$(ps -ef | grep JAAA | grep -v grep | awk '{print $2}')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19145217/"
] |
74,532,678
|
<p>I am working on a txt file which and in between the data that I need there are also information that I want to delete. For instance the txt file is built like this:</p>
<pre><code>|important|data|that|I|need|to|keep|
-------------------------------
---------------
----------------
info|I|dont|need|
----------------
---------------
------------------------------
|important|data|that|I|need|to|keep
|I|want|to|keep|this|info|
-------------------------------
---------------
----------------
info|I|dont|need|
----------------
---------------
------------------------------
</code></pre>
<p>how can I delete everything between the dashes?</p>
<p>When I read the file I would like to have just something like this:</p>
<pre><code>|important|data|that|I|need|to|keep|
|important|data|that|I|need|to|keep
|I|want|to|keep|this|info|
</code></pre>
<p>update: is it possible to just delete everything in between the dashes? the format of the info between them can be different so I would like to find a one fits all solution</p>
|
[
{
"answer_id": 74532794,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk awk ps -ef | grep [j]ava | \nawk '\n{\n val=$2 OFS $9\n match(val,/([0-9]+) -Dapex=APEC ([0-9]+) -Dapex=JAAA\\s([0-9]+)/,arr)\n print \"First_PID=\"arr[1],\"Second_PID=\",arr[3],\"Third_PID=\",arr[2]\n}\n'\n"
},
{
"answer_id": 74535469,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 1,
"selected": false,
"text": "$ input=(\"1 APEC\" \"2 JAAA\" \"3 APEC\")\n$ printf '%s\\n' \"${input[@]}\" | grep APEC | sed -n '2p'\n3 APEC\n input=(...) printf '%s\\n' \"${input[@]}\" input grep APEC APEC sed -n sed sed -n '2p'"
},
{
"answer_id": 74539657,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 0,
"selected": false,
"text": "ps -ef |\n awk '/java[ ].* -Dapex=APEC/{print $2\" \"$9; next; }\n /java[ ]/{non[NR]=$2\" \"$9}\n END{ for (rec in non) print non[rec] }'\n mapfile -t pids < <( ps -ef | awk '/java[ ].* -Dapex=APEC/{print $2; next; }\n /java[ ]/{non[NR]=$2} END{ for (rec in non) print non[rec] }' )\n"
},
{
"answer_id": 74561665,
"author": "Teerawat ",
"author_id": 19145217,
"author_profile": "https://Stackoverflow.com/users/19145217",
"pm_score": 0,
"selected": false,
"text": "FIRST_PID=$(ps -ef | grep APEC | grep -v grep | awk '{print $2}'| sed -n '1p') \nSECOND_PID=$(ps -ef | grep APEC | grep -v grep | awk '{print $2}'| sed -n '2p') \nJAWS_PID=$(ps -ef | grep JAAA | grep -v grep | awk '{print $2}')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18939903/"
] |
74,532,685
|
<p>This is my test collection</p>
<pre><code>[
{
"_id": "637cbf94b4741277c3b53c6c",
"text": "outter",
"username": "test1",
"address": [
{
"text": "inner",
"username": "test2",
"_id": "637cbf94b4741277c3b53c6e"
}
],
"__v": 0
}
]
</code></pre>
<p>If I do</p>
<pre><code>t1 = await doc.find({}, 'text').exec();
console.log(JSON.stringify(t1, null, 2));
</code></pre>
<p>I get</p>
<pre><code>[
{
"_id": "637cbf94b4741277c3b53c6c",
"text": "outter"
}
]
</code></pre>
<p>So here it finds the parent <code>text</code>.</p>
<p><strong>Question</strong></p>
<p>How do I get Mongoose to query the sub document instead of the parent?</p>
|
[
{
"answer_id": 74532724,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 3,
"selected": true,
"text": "t1 = await doc.find({}, {'address.text':1}).exec();\n"
},
{
"answer_id": 74533128,
"author": "Wouter Lemcke",
"author_id": 1456056,
"author_profile": "https://Stackoverflow.com/users/1456056",
"pm_score": 1,
"selected": false,
"text": "await doc.find(\n {},\n {\n _id: 0,\n 'address.text': 1\n }\n).exec();`\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256439/"
] |
74,532,688
|
<p>I have a course project and I am not able to solve the following problem:</p>
<p>I need to create a linkedlist in which I can add a list of elements from a class called Person, and a list of elements from a class called Accounts using addAll()</p>
<pre><code>List<Person> persons= new LinkedList<Person>();
</code></pre>
<pre><code>List<Accounts> accounts= new LinkedList<Accounts>();
</code></pre>
<pre><code>List<???> elements = new LinkedList<>();
</code></pre>
<pre><code>elements.addAll(persons);
elements.addAll(accounts);
</code></pre>
<p>My teacher ordered to make a class ElementsOfTheBank to fill the place with ???, but I couldn't understand how to make it work :(</p>
|
[
{
"answer_id": 74532764,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 2,
"selected": true,
"text": "java.lang.Object public interface ElementOfBank class Person implements ElementOfBank {} List<ElementOfBank> elements = ...; .addAll(persons) class Person implements ElementOfBank"
},
{
"answer_id": 74532840,
"author": "7evy",
"author_id": 16586200,
"author_profile": "https://Stackoverflow.com/users/16586200",
"pm_score": 2,
"selected": false,
"text": "class ElementsOfTheBank {\n // common variables between Person and Account\n}\n\nclass Person extends ElementsOfTheBank {\n // ...\n}\n\nclass Account extends ElementsOfTheBank {\n // ...\n}\n List<ElementsOfTheBank> elements = new LinkedList<>();\nelements.addAll(persons);\nelements.addAll(accounts);\n"
},
{
"answer_id": 74532865,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "List<Object> Person Account Person Account class Bank public class Bank {\n private List<Person> persons= new LinkedList<>();\n private List<Accounts> accounts= new LinkedList<>();\n\n // constructors, getters\n \n public boolean createAccount() {\n // TO DO ...\n return ...;\n }\n\n public Person findPerson(SomeProperty id) {\n // TO DO ...\n return ...;\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572123/"
] |
74,532,708
|
<p><img src="https://i.stack.imgur.com/lcAZw.png" alt="enter image description here" /></p>
<p>I am using Plotly to plot a scatterplot of GWAS data and want to highlight a certain point a different colour to the rest of the data. I have tried multiple times but unable to find away around this in Plotly. Any advice would be great please.</p>
<p>input data looks like this:</p>
<p><img src="https://i.stack.imgur.com/bYTaK.png" alt="input data" /></p>
<pre><code>fig <- fig %>% add_trace(data=data_1, x = ~BP, y = ~log, name = "data", mode = "markers", type = "scatter",
y = c(117300000, 117900000), marker = list(size = 8, color = '#d62728'),
x = c(117558703), y = c(19.75696195), marker = list(color = 'blue',size = 8), type = "scatter")
fig
</code></pre>
|
[
{
"answer_id": 74532764,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 2,
"selected": true,
"text": "java.lang.Object public interface ElementOfBank class Person implements ElementOfBank {} List<ElementOfBank> elements = ...; .addAll(persons) class Person implements ElementOfBank"
},
{
"answer_id": 74532840,
"author": "7evy",
"author_id": 16586200,
"author_profile": "https://Stackoverflow.com/users/16586200",
"pm_score": 2,
"selected": false,
"text": "class ElementsOfTheBank {\n // common variables between Person and Account\n}\n\nclass Person extends ElementsOfTheBank {\n // ...\n}\n\nclass Account extends ElementsOfTheBank {\n // ...\n}\n List<ElementsOfTheBank> elements = new LinkedList<>();\nelements.addAll(persons);\nelements.addAll(accounts);\n"
},
{
"answer_id": 74532865,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "List<Object> Person Account Person Account class Bank public class Bank {\n private List<Person> persons= new LinkedList<>();\n private List<Accounts> accounts= new LinkedList<>();\n\n // constructors, getters\n \n public boolean createAccount() {\n // TO DO ...\n return ...;\n }\n\n public Person findPerson(SomeProperty id) {\n // TO DO ...\n return ...;\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11331055/"
] |
74,532,717
|
<p>I am trying to make pie chart as below which is working fine but I have issue with end path (which is orange in below image).</p>
<p><a href="https://i.stack.imgur.com/0l4dm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0l4dm.png" alt="enter image description here" /></a></p>
<p>What I want to do is make end of orange shape to below the green one so that I can achieve as below.</p>
<p><a href="https://i.stack.imgur.com/3Vy5a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Vy5a.png" alt="enter image description here" /></a></p>
<p>Any suggestion how this can be done?</p>
<p>Code can be found at below link.</p>
<p><a href="https://drive.google.com/file/d/1ST0zNooLgRaI8s2pDK3NMjBQYjBSRoXB/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1ST0zNooLgRaI8s2pDK3NMjBQYjBSRoXB/view?usp=sharing</a></p>
<p>Below is what I have.</p>
<pre><code>func drawBeizer(start_angle : CGFloat, end_angle : CGFloat, final_color : UIColor) {
let path1 : UIBezierPath = UIBezierPath()
path1.addArc(withCenter: CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2), radius: ((self.frame.size.width-main_view_width)/2), startAngle: start_angle, endAngle: end_angle, clockwise: true)
path1.lineWidth = main_view_width
path1.lineCapStyle = .round
final_color.setStroke()
path1.stroke()
}
</code></pre>
<p>This function I am passing start angle and end angle & color for the path.</p>
|
[
{
"answer_id": 74533129,
"author": "burnsi",
"author_id": 6950415,
"author_profile": "https://Stackoverflow.com/users/6950415",
"pm_score": 1,
"selected": false,
"text": "SwiftUI Path struct DonutElement: Shape{\n \n var width: CGFloat = 50\n var startAngle: Angle\n var endAngle: Angle\n \n func path(in rect: CGRect) -> Path {\n // define commonly used vars\n // the extend of the shape\n let outerRadius = min(rect.width, rect.height) / 2\n // the middle of the shape\n let midRadius = outerRadius - width / 2\n // the inner radius\n let innerRadius = outerRadius - width\n // centerpoint used to move coordinate system in to center\n let center = CGPoint(x: rect.width / 2, y: rect.height / 2)\n \n return Path{ path in\n // calculate the startpoint from the startAngle. startAngle is allready normalized\n let startPoint = startAngle.polarCoordinates(center: center, radius: outerRadius)\n\n // move the path without drawing to the starting position\n path.move(to: startPoint)\n \n // add the starting concav arc\n // the center point for this arc are the polar coordinates relative to midradius of the donut\n path.addArc(center: startAngle.polarCoordinates(center: center, radius: midRadius), radius: width / 2, startAngle: startAngle.normalizing(), endAngle: (.init(degrees: 180) - startAngle), clockwise: true)\n \n // add the arc that presents the inner donut line\n // center point is the center of the drawing rect with normalized angles\n path.addArc(center: center, radius: innerRadius, startAngle: startAngle.normalizing(), endAngle: endAngle.normalizing(), clockwise: true)\n \n // add the convex arc at the end of the donut element\n // switch clockwise to false and swap end and start angle\n // replace startAngle with endAngle\n path.addArc(center: endAngle.polarCoordinates(center: center, radius: midRadius), radius: width / 2, startAngle: (.init(degrees: 180) - endAngle), endAngle: endAngle.normalizing(), clockwise: false)\n \n // add the outer stroke to close the shape\n path.addArc(center: center, radius: outerRadius, startAngle: endAngle.normalizing(), endAngle: startAngle.normalizing(), clockwise: false)\n \n // just in case\n path.closeSubpath()\n }\n }\n}\n\nextension Shape {\n func fillWithStroke<Fill: ShapeStyle, Stroke: ShapeStyle>(_ fillStyle: Fill, strokeBorder strokeStyle: Stroke, lineWidth: Double = 1) -> some View {\n self\n .stroke(strokeStyle, lineWidth: lineWidth)\n .background(self.fill(fillStyle))\n }\n}\n\nstruct AngleContainer: Identifiable, Hashable{\n let id = UUID()\n var startAngle: Angle\n var endAngle: Angle\n var color: Color\n}\n\n\n\nstruct Donut: View{\n // each element ends here and starts at the previous or 0. Values in percent\n var elementStops: [(CGFloat , Color)] = [(0.4 , .blue), (45 , .red), (55 , .green), (78 , .gray), (100 , .white)]\n var width: CGFloat = 50.0\n private var angles: [AngleContainer] {\n var angles = [AngleContainer]()\n \n for (index, stop) in elementStops.enumerated(){\n if index == 0{\n let startAngle = Angle(degrees: 0)\n let endAngle = Angle(degrees: stop.0/100 * 360)\n \n angles.append(AngleContainer(startAngle: startAngle,endAngle: endAngle,color: stop.1))\n } else{\n let startAngle = Angle(degrees: elementStops[index - 1].0 / 100 * 360)\n let endAngle = Angle(degrees: stop.0/100 * 360)\n \n angles.append(AngleContainer(startAngle: startAngle,endAngle: endAngle,color: stop.1))\n }\n }\n \n return angles\n }\n var body: some View{\n ZStack{\n ForEach(angles){ angleContainer in\n DonutElement(width: width, startAngle: angleContainer.startAngle, endAngle: angleContainer.endAngle)\n .fillWithStroke(angleContainer.color, strokeBorder: .black.opacity(0.2))\n }\n }\n .background(.white)\n }\n}\n\n// used for transfering coordinate system\nextension CGPoint{\n mutating func transfered(to center: CGPoint){\n x = center.x + x\n y = center.y - y\n }\n \n func transfering(to center: CGPoint) -> CGPoint{\n .init(x: center.x + x, y: center.y - y)\n }\n\n}\n // convenience so angle feels more natural\nextension Angle{\n func normalizing() -> Angle {\n Angle(degrees: 0) - self\n }\n \n func polarCoordinates(center: CGPoint, radius: CGFloat) -> CGPoint{\n CGPoint(x: cos(self.radians) * radius, y: sin(self.radians) * radius )\n .transfering(to: center)\n }\n}\n"
},
{
"answer_id": 74533917,
"author": "Fahim Parkar",
"author_id": 1066828,
"author_profile": "https://Stackoverflow.com/users/1066828",
"pm_score": 0,
"selected": false,
"text": "import UIKit\n\nclass ViewController: UIViewController {\n\n @IBOutlet weak var myView: MyView!\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view.\n \n myView.setupData(inner_color: [.green, .purple, .blue, .orange], inner_view_width: self.view.frame.width/5.0, inner_angle: [0.0, 90.0, 180.0, 270.0])\n \n myView.backgroundColor = UIColor.white\n\n }\n \n}\n import UIKit\n\nclass MyView: UIView {\n \n var main_radius : CGFloat = 0.0\n \n var main_color : [UIColor] = [UIColor.black, UIColor.green]\n \n var main_view_width : CGFloat = 1.0\n \n var main_angle : [CGFloat] = [-CGFloat.pi, 0.0]\n var actual_angle : [CGFloat] = []\n \n func setupData(inner_color : [UIColor], inner_view_width : CGFloat, inner_angle : [CGFloat]) {\n main_color = inner_color\n \n main_view_width = inner_view_width\n \n main_angle = inner_angle\n \n actual_angle = inner_angle\n \n var temp_main_angle : [CGFloat] = []\n for i in 0..<main_angle.count {\n temp_main_angle.append(main_angle[i]*Double.pi/180)\n }\n main_angle = temp_main_angle\n \n draw(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.width))\n }\n \n override func draw(_ rect: CGRect) {\n \n if (main_color.count >= 2) {\n \n var inner_position : Int = 0\n \n // first draw with sharp corner\n for i in 0..<main_color.count {\n \n if (i == (main_color.count-1)) {\n inner_position = 0\n } else {\n inner_position = i+1\n }\n \n drawBeizer(start_angle: main_angle[i], end_angle: main_angle[inner_position], final_color: main_color[i])\n }\n \n \n // append with ending icons for circle\n for i in 0..<main_color.count {\n \n if (i == (main_color.count-1)) {\n inner_position = 0\n } else {\n inner_position = i+1\n }\n \n drawBeizer(start_angle: main_angle[inner_position], end_angle: main_angle[inner_position]+(1*Double.pi/180), final_color: main_color[i], withCircle: true) // make here final_color as .black to see what I am doing with this loop\n }\n }\n }\n \n func drawBeizer(start_angle : CGFloat, end_angle : CGFloat, final_color : UIColor, withCircle: Bool = false) {\n let path1 : UIBezierPath = UIBezierPath()\n \n path1.addArc(withCenter: CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2), radius: ((self.frame.size.width-main_view_width)/2), startAngle: start_angle, endAngle: end_angle, clockwise: true)\n path1.lineWidth = main_view_width\n if (withCircle) {\n path1.lineCapStyle = .round\n }\n final_color.setStroke()\n path1.stroke()\n \n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066828/"
] |
74,532,737
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
display: flex;
flex-direction: column;
gap: 20px;
padding: 50px; }
.wide-container, .narrow-container {
flex: none;
background-color: #f7f7f7;
border-radius: 5px;
padding: 10px 20px;
box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);
border: 1px #c2c2c2 solid;
}
.wide-container {
width: 600px;
}
.narrow-container {
width: 300px;
}
.flex {
display: flex;
flex-wrap: wrap;
gap: 10px 0;
}
.text {
flex: none;
padding: 5px 2px;
background-color: salmon;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="wide-container">
<div class="flex"><span class="text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>
</div>
<div class="narrow-container">
<div class="flex"><span class="text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I need to apply some styles to piece of a text, and it should be inside of a flex box, because I need some of its features. The problem is that when there is not enough space, text will overflow:</p>
<p><a href="https://i.stack.imgur.com/DSoqf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DSoqf.png" alt="enter image description here" /></a></p>
<p>So, I need to split text somehow, to keep the styling on a new line like this (did it manually here):
<a href="https://i.stack.imgur.com/5HdB7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5HdB7.png" alt="enter image description here" /></a></p>
<p>UPD:
Thanks for the answers, but the problem is a little bit more complex than it looks at first glance. Solution in answers (so far) leads to this result:</p>
<p><a href="https://i.stack.imgur.com/omDF7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/omDF7.png" alt="enter image description here" /></a></p>
<p>Which means that line breaks inside of a .text container. If you compare this result with the result I need (screenshot above), you will understand the issue.</p>
|
[
{
"answer_id": 74532845,
"author": "KLTR",
"author_id": 5277707,
"author_profile": "https://Stackoverflow.com/users/5277707",
"pm_score": -1,
"selected": false,
"text": ".text {\n padding: 5px 2px;\n background-color: salmon;\n color: white; \n}\n"
},
{
"answer_id": 74532867,
"author": "Alejandro Suárez",
"author_id": 17751007,
"author_profile": "https://Stackoverflow.com/users/17751007",
"pm_score": -1,
"selected": false,
"text": "</br> </br> flex: none background-color .wrapper {\n display: flex;\n flex-direction: column;\n gap: 20px;\n padding: 50px; }\n\n.wide-container, .narrow-container {\n flex: none;\n background-color: #f7f7f7;\n border-radius: 5px;\n padding: 10px 20px;\n box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);\n border: 1px #c2c2c2 solid; \n}\n\n.wide-container {\n width: 600px; \n}\n\n.narrow-container {\n width: 300px; \n}\n\n.flex {\n display: flex;\n flex-wrap: wrap;\n gap: 10px 0; \n}\n\n.text {\n padding: 5px 2px;\n line-height: 1.5;\n color: white; \n}\n\n.highlight {\n background-color: salmon; \n} <div class=\"wrapper\">\n <div class=\"wide-container\">\n <div class=\"flex\"><span class=\"text\"><span class=\"highlight\">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></span></div>\n </div>\n <div class=\"narrow-container\">\n <div class=\"flex\"><span class=\"text\"><span class=\"highlight\">Lorem ipsum dolor sit amet consectetur, </span><span class=\"highlight\">adipisicing elit.</span></span></div>\n </div>\n</div>"
},
{
"answer_id": 74533361,
"author": "Coopero",
"author_id": 2421346,
"author_profile": "https://Stackoverflow.com/users/2421346",
"pm_score": -1,
"selected": false,
"text": " .text {\n background-color: salmon;\n color: white;\n line-height: 2em!important;\n padding: 3px 0px;\n }\n"
},
{
"answer_id": 74536308,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 0,
"selected": false,
"text": ".wrapper {\n display: flex;\n flex-direction: column;\n gap: 20px;\n padding: 50px; }\n\n.wide-container, .narrow-container {\n flex: none;\n background-color: #f7f7f7;\n border-radius: 5px;\n padding: 10px 20px;\n box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);\n border: 1px #c2c2c2 solid; \n}\n\n.wide-container {\n width: 600px; \n}\n\n.narrow-container {\n width: 300px; \n}\n\n.flex {\n flex-wrap: wrap;\n flex:none;\n gap: 10px 0; \n}\n\n.text {\n flex: none;\n word-break: break-word;\n padding: 5px 2px;\n line-height:35px;\n background-color: salmon;\n color: white; \n} <div class=\"wrapper\">\n <div class=\"wide-container\">\n <div class=\"flex\"><span class=\"text\">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>\n </div>\n <div class=\"narrow-container\">\n <div class=\"flex\">\n <span class=\"text\">Lorem ipsum dolor sit amet consectetur, adipisicing elit. 3</span>\n </div>\n </div>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10173593/"
] |
74,532,745
|
<p>eg [:owes] instead of this i would like the amount they owe (row.amount)</p>
<p>couldnt come up with much</p>
|
[
{
"answer_id": 74532845,
"author": "KLTR",
"author_id": 5277707,
"author_profile": "https://Stackoverflow.com/users/5277707",
"pm_score": -1,
"selected": false,
"text": ".text {\n padding: 5px 2px;\n background-color: salmon;\n color: white; \n}\n"
},
{
"answer_id": 74532867,
"author": "Alejandro Suárez",
"author_id": 17751007,
"author_profile": "https://Stackoverflow.com/users/17751007",
"pm_score": -1,
"selected": false,
"text": "</br> </br> flex: none background-color .wrapper {\n display: flex;\n flex-direction: column;\n gap: 20px;\n padding: 50px; }\n\n.wide-container, .narrow-container {\n flex: none;\n background-color: #f7f7f7;\n border-radius: 5px;\n padding: 10px 20px;\n box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);\n border: 1px #c2c2c2 solid; \n}\n\n.wide-container {\n width: 600px; \n}\n\n.narrow-container {\n width: 300px; \n}\n\n.flex {\n display: flex;\n flex-wrap: wrap;\n gap: 10px 0; \n}\n\n.text {\n padding: 5px 2px;\n line-height: 1.5;\n color: white; \n}\n\n.highlight {\n background-color: salmon; \n} <div class=\"wrapper\">\n <div class=\"wide-container\">\n <div class=\"flex\"><span class=\"text\"><span class=\"highlight\">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></span></div>\n </div>\n <div class=\"narrow-container\">\n <div class=\"flex\"><span class=\"text\"><span class=\"highlight\">Lorem ipsum dolor sit amet consectetur, </span><span class=\"highlight\">adipisicing elit.</span></span></div>\n </div>\n</div>"
},
{
"answer_id": 74533361,
"author": "Coopero",
"author_id": 2421346,
"author_profile": "https://Stackoverflow.com/users/2421346",
"pm_score": -1,
"selected": false,
"text": " .text {\n background-color: salmon;\n color: white;\n line-height: 2em!important;\n padding: 3px 0px;\n }\n"
},
{
"answer_id": 74536308,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 0,
"selected": false,
"text": ".wrapper {\n display: flex;\n flex-direction: column;\n gap: 20px;\n padding: 50px; }\n\n.wide-container, .narrow-container {\n flex: none;\n background-color: #f7f7f7;\n border-radius: 5px;\n padding: 10px 20px;\n box-shadow: 0 5px 35px rgba(0, 0, 0, 0.2);\n border: 1px #c2c2c2 solid; \n}\n\n.wide-container {\n width: 600px; \n}\n\n.narrow-container {\n width: 300px; \n}\n\n.flex {\n flex-wrap: wrap;\n flex:none;\n gap: 10px 0; \n}\n\n.text {\n flex: none;\n word-break: break-word;\n padding: 5px 2px;\n line-height:35px;\n background-color: salmon;\n color: white; \n} <div class=\"wrapper\">\n <div class=\"wide-container\">\n <div class=\"flex\"><span class=\"text\">Lorem ipsum dolor sit amet consectetur, adipisicing elit. </span></div>\n </div>\n <div class=\"narrow-container\">\n <div class=\"flex\">\n <span class=\"text\">Lorem ipsum dolor sit amet consectetur, adipisicing elit. 3</span>\n </div>\n </div>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20378640/"
] |
74,532,760
|
<p>I've seen plenty of answers explaining how to override and add functionality to a back button press via user's interaction, but almost none of the answers explain how to programmatically trigger a back button press without any user input. Answers that do address it give somewhat deprecated code samples that don't really compute.</p>
|
[
{
"answer_id": 74532813,
"author": "Dhruv Sakariya",
"author_id": 13387235,
"author_profile": "https://Stackoverflow.com/users/13387235",
"pm_score": 1,
"selected": false,
"text": "//simply put this code where you want to make back intent\nsuper.onBackPressed();\n"
},
{
"answer_id": 74532831,
"author": "Mahmoud Gamal El-Din",
"author_id": 8239457,
"author_profile": "https://Stackoverflow.com/users/8239457",
"pm_score": 3,
"selected": true,
"text": "onBackPressed() activity?.onBackPressed()"
},
{
"answer_id": 74536073,
"author": "Ammar",
"author_id": 13174552,
"author_profile": "https://Stackoverflow.com/users/13174552",
"pm_score": 1,
"selected": false,
"text": "class YourActivity : AppCompatActivity() {\n\nlateinit var button: Button\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n\n button = findViewById(R.id.txt)\n button.setOnClickListener {\n onBackPressedCallback.handleOnBackPressed()\n }\n\n}\n\nprivate val onBackPressedCallback = object : OnBackPressedCallback(true) {\n override fun handleOnBackPressed() {\n finish() //this finishes the current activity\n // Your business logic to handle the back pressed event\n }\n\n }\n}\n buttonBack.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n YourActivity.super.onBackPressed();\n }\n });\n buttonBack.setOnClickListener{\n super.onBackPressed()\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17709311/"
] |
74,532,767
|
<p>I have a text file large with content format below, i want remove two first character 11, i try to search by dont know how to continue with my code. Looking for help. Thanks</p>
<p>file.txt</p>
<blockquote>
<p>11112345,67890,12345</p>
<p>115432,a123q,hs1230</p>
<p>11s1a123,qw321,98765321</p>
<p>342342,121sa,12123243</p>
<p>11023456,sa123,d32acas2</p>
</blockquote>
<p>My code</p>
<pre><code>import re
with open('in.txt') as oldfile, open('out.txt', 'w') as newfile:
for line in oldfile:
removed = re.sub(r'11', '', line[:2]):
newfile.write(removed)
</code></pre>
<p>Result expected:</p>
<blockquote>
<p>112345,67890,12345</p>
<p>115432,a123q,hs1230</p>
<p>s1a123,qw321,98765321</p>
<p>342342,121sa,12123243</p>
<p>023456,sa123,d32acas2</p>
</blockquote>
|
[
{
"answer_id": 74532962,
"author": "Laurent H.",
"author_id": 5270581,
"author_profile": "https://Stackoverflow.com/users/5270581",
"pm_score": 4,
"selected": true,
"text": "with open('in.txt', 'r') as oldfile, open('out.txt', 'w') as newfile:\n for line in oldfile:\n newfile.write(line[2:] if line.startswith('11') else line)\n line[6] != ','"
},
{
"answer_id": 74533394,
"author": "Matthieu",
"author_id": 20572421,
"author_profile": "https://Stackoverflow.com/users/20572421",
"pm_score": 0,
"selected": false,
"text": "removed = re.sub(r'11', '', line[:2]):\n removed = re.sub(r'^(11)','', line)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16608286/"
] |
74,532,801
|
<p>I have a tapBar with tabs, these tabs are clickable and I want to add divider between tabs but I don't understand how to do this in Flutter!</p>
<p>This is my tabBar:</p>
<pre><code>TabBar(
indicatorPadding: EdgeInsets.symmetric(vertical: 10),
indicator: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5)),
side: BorderSide(color: Colors.white)),
color: Color(0xFF1C1B20),
),
labelColor: AppColors.whiteE3EAF6,
labelStyle: TextStyle(color: Colors.white),
tabs: [
Tab(text: "1M",),
Tab(text: "5M",),
Tab(text: "15M",),
Tab(text: "30M",),
Tab(text: "1H",),
]
)
</code></pre>
<p>And I want to make it like this:</p>
<p><a href="https://i.stack.imgur.com/n157k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n157k.png" alt="This is what I want" /></a></p>
<p>I tried to add Container between Tabs but this container moves all my tabs and became clickable and this is not what I really want.</p>
<p>Also this TabBar is inside Container and width of Container is 350</p>
|
[
{
"answer_id": 74532930,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 0,
"selected": false,
"text": "Tab(\n child: Container(\n decoration: BoxDecoration(\n color: Colors.transparent,\n borderRadius: BorderRadius.circular(14),\n ),\n child: Padding(\n padding: const EdgeInsets.only(left: 19, right: 19, bottom: 2),\n child: Text(\n \"1M\",\n style: const TextStyle(fontSize: 14, fontFamily: \"PNU\"),\n ),\n ),\n ),\n),\n"
},
{
"answer_id": 74532936,
"author": "brook yonas",
"author_id": 14139196,
"author_profile": "https://Stackoverflow.com/users/14139196",
"pm_score": 0,
"selected": false,
"text": " Container(\n height: 50,\n decoration: BoxDecoration(border: Border(right: BorderSide(color: \n Colors.black, width: 1, style: BorderStyle.solid))),\n child: Padding(\n padding: const EdgeInsets.all(10),\n child: Tab(text: \"1M\"), //here the Tab widget\n )\n )\n"
},
{
"answer_id": 74533460,
"author": "Newbie",
"author_id": 9618445,
"author_profile": "https://Stackoverflow.com/users/9618445",
"pm_score": 3,
"selected": true,
"text": " Widget _tab(String text) {\n return Container(\n padding: const EdgeInsets.all(0),\n width: double.infinity,\n decoration: const BoxDecoration(\n border: Border(right: BorderSide(color: Colors.white, width: 1, style: BorderStyle.solid))),\n child: Tab(\n text: text,\n ),\n );\n }\n TabBar(\n indicatorPadding: EdgeInsets.symmetric(vertical: 10),\n indicator: ShapeDecoration(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.all(Radius.circular(5)),\n side: BorderSide(color: Colors.white)),\n color: Color(0xFF1C1B20),\n ),\n labelColor: AppColors.whiteE3EAF6,\n labelStyle: TextStyle(color: Colors.white),\n labelPadding: const EdgeInsets.all(0), // remember to add this line\n tabs: [\n _tab('1M'),\n _tab('5M'),\n _tab('15M'),\n _tab('30M'),\n _tab('1H'),\n ]\n )\n"
},
{
"answer_id": 74535052,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "int selectedTap = 0;\n Widget tabWidget(String label, int index) {\n return Container(\n height: 15,\n width: double.infinity,\n decoration: BoxDecoration(\n border: index == selectedTap\n ? null\n : Border(\n right: BorderSide(\n color: Color(0xFF454545),\n width: 1,\n style: BorderStyle.solid),\n )),\n child: Tab(\n text: label,\n ),\n );\n }\n TabBar(\n controller: _controller,\n indicatorPadding: EdgeInsets.symmetric(vertical: 10),\n labelPadding: EdgeInsets.zero,\n indicator: ShapeDecoration(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.all(Radius.circular(5)),\n side: BorderSide(color: Colors.white)),\n color: Color(0xFF1C1B20),\n ),\n labelColor: Colors.white,\n labelStyle: TextStyle(color: Colors.white),\n tabs: [\n tabWidget(\"1M\", 0),\n tabWidget(\"5M\", 1),\n tabWidget(\"15M\", 2),\n tabWidget(\"30M\", 3),\n Tab(\n text: \"1H\",\n ),\n ],\n onTap: (index) {\n setState(() {\n selectedTap = index;\n });\n },\n ),\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20478292/"
] |
74,532,805
|
<p>I'm now learning C# and making a couple of challenges, i managed to pass easily most of them but sometimes there are things i don't understand (i'm a python dev basically)...</p>
<blockquote>
<p>Create a function that takes an integer and outputs an n x n square solely consisting of the integer n.</p>
</blockquote>
<pre><code>E.G : SquarePatch(3) ➞ [
[3, 3, 3],
[3, 3, 3],
[3, 3, 3]
]
</code></pre>
<p>So i went trough docs about multidimentionnal arrays, jagged arrays.But i get an error (kind of errors i get the most while learning c#, i never had that kind of problems in python. It's about TYPES convertion !) I mean i often have problems of types.</p>
<p>So here's my code :</p>
<pre><code>public class Challenge
{
public static int[,] SquarePatch(int n)
{
int[ ][,] jaggedArray = new int[n][,];
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
return jaggedArray[i][j, k]=n;
}
}
}
}
}
</code></pre>
<p>What is actually very boring is that in that kind of challenges i don't know how to make equivalent to python "print tests" ! So i don't even know what's going on till the end...</p>
<p>And i get this error :</p>
<pre><code>Cannot implicitly convert type int to int[,]
</code></pre>
|
[
{
"answer_id": 74532930,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 0,
"selected": false,
"text": "Tab(\n child: Container(\n decoration: BoxDecoration(\n color: Colors.transparent,\n borderRadius: BorderRadius.circular(14),\n ),\n child: Padding(\n padding: const EdgeInsets.only(left: 19, right: 19, bottom: 2),\n child: Text(\n \"1M\",\n style: const TextStyle(fontSize: 14, fontFamily: \"PNU\"),\n ),\n ),\n ),\n),\n"
},
{
"answer_id": 74532936,
"author": "brook yonas",
"author_id": 14139196,
"author_profile": "https://Stackoverflow.com/users/14139196",
"pm_score": 0,
"selected": false,
"text": " Container(\n height: 50,\n decoration: BoxDecoration(border: Border(right: BorderSide(color: \n Colors.black, width: 1, style: BorderStyle.solid))),\n child: Padding(\n padding: const EdgeInsets.all(10),\n child: Tab(text: \"1M\"), //here the Tab widget\n )\n )\n"
},
{
"answer_id": 74533460,
"author": "Newbie",
"author_id": 9618445,
"author_profile": "https://Stackoverflow.com/users/9618445",
"pm_score": 3,
"selected": true,
"text": " Widget _tab(String text) {\n return Container(\n padding: const EdgeInsets.all(0),\n width: double.infinity,\n decoration: const BoxDecoration(\n border: Border(right: BorderSide(color: Colors.white, width: 1, style: BorderStyle.solid))),\n child: Tab(\n text: text,\n ),\n );\n }\n TabBar(\n indicatorPadding: EdgeInsets.symmetric(vertical: 10),\n indicator: ShapeDecoration(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.all(Radius.circular(5)),\n side: BorderSide(color: Colors.white)),\n color: Color(0xFF1C1B20),\n ),\n labelColor: AppColors.whiteE3EAF6,\n labelStyle: TextStyle(color: Colors.white),\n labelPadding: const EdgeInsets.all(0), // remember to add this line\n tabs: [\n _tab('1M'),\n _tab('5M'),\n _tab('15M'),\n _tab('30M'),\n _tab('1H'),\n ]\n )\n"
},
{
"answer_id": 74535052,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "int selectedTap = 0;\n Widget tabWidget(String label, int index) {\n return Container(\n height: 15,\n width: double.infinity,\n decoration: BoxDecoration(\n border: index == selectedTap\n ? null\n : Border(\n right: BorderSide(\n color: Color(0xFF454545),\n width: 1,\n style: BorderStyle.solid),\n )),\n child: Tab(\n text: label,\n ),\n );\n }\n TabBar(\n controller: _controller,\n indicatorPadding: EdgeInsets.symmetric(vertical: 10),\n labelPadding: EdgeInsets.zero,\n indicator: ShapeDecoration(\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.all(Radius.circular(5)),\n side: BorderSide(color: Colors.white)),\n color: Color(0xFF1C1B20),\n ),\n labelColor: Colors.white,\n labelStyle: TextStyle(color: Colors.white),\n tabs: [\n tabWidget(\"1M\", 0),\n tabWidget(\"5M\", 1),\n tabWidget(\"15M\", 2),\n tabWidget(\"30M\", 3),\n Tab(\n text: \"1H\",\n ),\n ],\n onTap: (index) {\n setState(() {\n selectedTap = index;\n });\n },\n ),\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7495742/"
] |
74,532,841
|
<p>I have two columns in an Excel spreadsheet that look like:-</p>
<pre><code>Key Values
f 1
f 2
u 3
g 4
g 5
h 6
h 7
j 8
j 9
k 10
k 11
k 12
</code></pre>
<p>I want to create apply formula which creates an average of first n numbers in ms excel.</p>
<p>I Try this:-</p>
<p>=AVERAGE(B:B,10)</p>
<p>but could not get the answer.</p>
<p>Please help me for give me appropriate answer.</p>
|
[
{
"answer_id": 74532984,
"author": "Jos Woolley",
"author_id": 17007704,
"author_profile": "https://Stackoverflow.com/users/17007704",
"pm_score": 3,
"selected": true,
"text": "OFFSET INDIRECT =AVERAGE(B2:INDEX(B:B,n+1)) =AVERAGE(TAKE(B:B,n+1))"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12030528/"
] |
74,532,926
|
<p>I am having issues with Flutter web when I use await statement,</p>
<pre><code>void main() async {
//debugPaintSizeEnabled = true;
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
</code></pre>
<p>this will not display anything on the browser and throws and error:</p>
<p>ChromeProxyService: Failed to evaluate expression 'title': InternalError: Expression evaluation in async frames is not supported. No frame with index 39..</p>
<p>I am stuck :(</p>
<p>debugging testing nothing worked</p>
|
[
{
"answer_id": 74532984,
"author": "Jos Woolley",
"author_id": 17007704,
"author_profile": "https://Stackoverflow.com/users/17007704",
"pm_score": 3,
"selected": true,
"text": "OFFSET INDIRECT =AVERAGE(B2:INDEX(B:B,n+1)) =AVERAGE(TAKE(B:B,n+1))"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20035186/"
] |
74,532,939
|
<p>Guys i need help because i dont understand.</p>
<p><a href="https://i.stack.imgur.com/xYavX.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/vuhaY.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I searched what the problem was but couldn't find it</p>
|
[
{
"answer_id": 74533205,
"author": "Anandh Krishnan",
"author_id": 5197712,
"author_profile": "https://Stackoverflow.com/users/5197712",
"pm_score": 0,
"selected": false,
"text": "gradle.properties android.overridePathCheck=true\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572389/"
] |
74,532,950
|
<p>I am trying to find a way to change SQL server from using UTC time to Local time. This is because I need to be getting Local time when I pull data using ODATA via excel.</p>
<p>Is there a way to configure the SQL server from UTC to local time?</p>
|
[
{
"answer_id": 74534008,
"author": "Dan Guzman",
"author_id": 3711162,
"author_profile": "https://Stackoverflow.com/users/3711162",
"pm_score": 1,
"selected": false,
"text": "datetime datetime2 smalldatetime AT TIME ZONE SELECT YourUTCDateTimeColumn AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS YourLocalDateTimeColumn\n AT TIME ZONE datetimeoffset datetimeoffset SELECT CAST(YourUTCDateTimeColumn AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS datetime2(3)) AS YourLocalDateTimeColumn\n"
},
{
"answer_id": 74541896,
"author": "Chris Schaller",
"author_id": 1690217,
"author_profile": "https://Stackoverflow.com/users/1690217",
"pm_score": 0,
"selected": false,
"text": "SELECT GetDate() DateTimeOffset DateTime DateTimeOffset AT TIME ZONE"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569442/"
] |
74,532,955
|
<p>I'm trying to test a component that is using the useLocation react hook, but even though I mocked it, useLocation().pathname results in an error, as useLocation is undefined.</p>
<p>Another question I have is if I successfully mock useLocation() in this test file, will it also work for the rest? Is there a way to mock modules only for a single jest test file?</p>
<pre><code>jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn().mockReturnValue({
pathname: '/route'
})
}));
describe('ComponentUsingLocation', () => {
test('should render', () => {
const wrapper = shallow(
<ComponentUsingLocation />
);
expect(wrapper).toMatchSnapshot();
});
});
</code></pre>
|
[
{
"answer_id": 74534008,
"author": "Dan Guzman",
"author_id": 3711162,
"author_profile": "https://Stackoverflow.com/users/3711162",
"pm_score": 1,
"selected": false,
"text": "datetime datetime2 smalldatetime AT TIME ZONE SELECT YourUTCDateTimeColumn AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS YourLocalDateTimeColumn\n AT TIME ZONE datetimeoffset datetimeoffset SELECT CAST(YourUTCDateTimeColumn AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS datetime2(3)) AS YourLocalDateTimeColumn\n"
},
{
"answer_id": 74541896,
"author": "Chris Schaller",
"author_id": 1690217,
"author_profile": "https://Stackoverflow.com/users/1690217",
"pm_score": 0,
"selected": false,
"text": "SELECT GetDate() DateTimeOffset DateTime DateTimeOffset AT TIME ZONE"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529259/"
] |
74,532,966
|
<p>I have the following components up and running in a kubernetes cluster</p>
<ul>
<li>A GoLang Application writing data to a mongodb statefulset replicaset in namespace <code>app1</code></li>
<li>A mongodb replicaset (1 replica) running as a statefulset in the namespace <code>ng-mongo</code></li>
</ul>
<p>What I need to do is, I need to access the mongodb database by the <code>golang</code> application for write/read opeations, so what I did was;</p>
<ol>
<li>Create a headless service for the <code>mongodb</code> in the <code>ng-mongo</code> namespace as below:</li>
</ol>
<pre><code># Source: mongo/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
name: mongo
namespace: ng-mongo
labels:
app: mongo
spec:
ports:
- port: 27017
targetPort: 27017
name: mongo
clusterIP: None
selector:
role: mongo
</code></pre>
<ol start="2">
<li>And then I deployed the <code>mongodb</code> statefulset and initialized the replicaset as below:</li>
</ol>
<pre><code>kubectl exec -it mongo-0 -n ng-mongo mongosh
rs.initiate({_id: "rs0",members: [{_id: 0, host: "mongo-0"}]})
// gives output
{ ok: 1 }
</code></pre>
<ol start="3">
<li>Then I created an <code>ExternalName</code> service in the <code>app1</code> namespace linking the above mongo service in step 1, look below:</li>
</ol>
<pre><code># Source: app/templates/svc.yaml
kind: Service
apiVersion: v1
metadata:
name: app1
namespace: app1
spec:
type: ExternalName
externalName: mongo.ng-mongo.svc.cluster.local
ports:
- port: 27017
</code></pre>
<ol start="4">
<li>And at last, I instrumented my <code>golang</code> application as follows;</li>
</ol>
<pre><code>// Connection URI
const mongo_uri = "mongodb://app1" <-- Here I used the app1, as the ExternalName service's name is `app1`
<RETRACTED-CODE>
</code></pre>
<p>And then I ran the application, and checked the logs. Here is what I found:</p>
<blockquote>
<p>2022/11/22 12:49:47 server selection error: server selection timeout, current topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: mongo-0:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: dial tcp: lookup mongo-0 on 10.96.0.10:53: no such host }, ] }</p>
</blockquote>
<p><strong>Update: I haven't set any usernames or passwords for the mongodb</strong></p>
<p>Can someone help me why this is happening?</p>
|
[
{
"answer_id": 74537726,
"author": "Devin Jeon",
"author_id": 20575260,
"author_profile": "https://Stackoverflow.com/users/20575260",
"pm_score": 0,
"selected": false,
"text": "app1 mongo-0 mongo-0 mongo-0 app1 mongo-0 mongo_uri mongodb://app1 mongo-0"
},
{
"answer_id": 74538332,
"author": "Jananath Banuka",
"author_id": 7084115,
"author_profile": "https://Stackoverflow.com/users/7084115",
"pm_score": 1,
"selected": false,
"text": "host rs.initiate({}) FQDN mongodb mongo-0 rs.initiate({_id: \"rs0\",members: [{_id: 0, host: \"mongo-0.mongo.ng-mongo.svc.cluster.local:27017\"}]})\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7084115/"
] |
74,532,973
|
<p>I have these 2 divs (<code>footer-txt</code> and <code>footer-img</code>), on the mobile it works perfectly because I want the text on top and the 2 images on the bottom, like side by side.</p>
<p>But when the screen gets wider, I want the 2 images side by side and also the text div. Like a row with the 2 images and the text.</p>
<p>Is there a way that I can do this?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#footer {
background-color: #98AFFF;
}
.footer-txt {
font-size: 14px;
color: #464646;
text-align: left;
}
.footer-img {
display: flex;
gap: 25px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer class="text-center text-lg-start" id="footer">
<div class="p-4" id="footer-content">
<div class="pb-2 footer-txt">
PROTESTE
</div>
<div class="pt-4 pb-2 justify-content-center footer-img">
<a href="#">
<img src="images/pag1/Mask group (1).png" alt="Google">
</a>
<a href="#">
<img src="images/pag1/Mask group.png" alt="Google">
</a>
</div>
</div>
</footer></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74533127,
"author": "GarfieldKlon",
"author_id": 1226705,
"author_profile": "https://Stackoverflow.com/users/1226705",
"pm_score": -1,
"selected": false,
"text": "#footer {\n background-color: #98AFFF;\n}\n\n.footer-txt {\n font-size: 14px;\n color: #464646;\n text-align: left;\n}\n\n#footer-content {\n display: flex;\n flex-wrap: wrap;\n} <footer id=\"footer\">\n <div id=\"footer-content\">\n <div class=\"footer-txt\">\n PROTESTE\n </div>\n <div class=\"footer-img\">\n <a href=\"#\">\n <img src=\"images/pag1/Mask group (1).png\" alt=\"Google\">\n </a>\n </div>\n <div class=\"footer-img\">\n <a href=\"#\">\n <img src=\"images/pag1/Mask group.png\" alt=\"Google\">\n </a>\n </div>\n </div>\n</footer>"
},
{
"answer_id": 74533160,
"author": "Reinaldo Peres",
"author_id": 11771801,
"author_profile": "https://Stackoverflow.com/users/11771801",
"pm_score": 0,
"selected": false,
"text": "#footer-content #footer-content {\n display: flex;\n flex-direction: row;\n}\n div @media screen and (min-width: 960px) {\n #footer-content {\n display: flex;\n flex-direction: row;\n }\n}\n"
},
{
"answer_id": 74533168,
"author": "Shivangam Soni",
"author_id": 16659219,
"author_profile": "https://Stackoverflow.com/users/16659219",
"pm_score": 0,
"selected": false,
"text": "Flex-Box Grid Media Queries #footer {\n background-color: #98AFFF;\n}\n\n#footer-content {\n display: flex;\n align-items: center;\n justify-content: flex-start;\n gap: 25px;\n}\n\n.footer-txt {\n font-size: 14px;\n color: #464646;\n text-align: left;\n}\n\n.footer-img {\n display: flex;\n gap: 25px;\n}\n\n/* Styling for Smaller Screens */\n@media screen and (max-width: 500px) {\n #footer-content {\n flex-direction: column;\n align-items: flex-start;\n gap: 10px;\n }\n} <footer class=\"text-center text-lg-start\" id=\"footer\">\n <div class=\"p-4\" id=\"footer-content\">\n <div class=\"pb-2 footer-txt\">\n PROTESTE\n </div>\n <div class=\"pt-4 pb-2 justify-content-center footer-img\">\n <a href=\"#\">\n <img src=\"images/pag1/Mask group (1).png\" alt=\"Google\">\n </a>\n <a href=\"#\">\n <img src=\"images/pag1/Mask group.png\" alt=\"Google\">\n </a>\n </div>\n </div>\n\n</footer>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74532973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20231504/"
] |
74,533,026
|
<p>I tried moving a file into a subfolder, and git sees that it has been just "renamed"... but also sees that <strong>its whole content got removed and then added.</strong></p>
<p>For some reason with some files I could move them without losing all of their lines' actual/correct/original <code>git blame</code>. But with some, I can't.</p>
<p>I'm on <strong>Windows</strong> and using <strong>SourceTree</strong>. It seems like that maybe it's not git's fault but SourceTree's?</p>
<p>I tried it on my <strong>other computer</strong>, using Windows 10 and SourceTree as well, and <strong>everything works there</strong>. I could move around everything everywhere without triggering changes, affecting git blames, etc.</p>
<p>Any recommendations? I guess commiting file movements with CLI would be the go-to, but I'm using SourceTree to avoid that. :\</p>
<p><a href="https://i.stack.imgur.com/GMTCa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMTCa.png" alt="enter image description here" /></a>
Anyway if there is no other solution, could you recommend a quick command to easily & safely commit a whole folder's and its subfolders' movement?</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74638195,
"author": "Zhubei Federer",
"author_id": 10769406,
"author_profile": "https://Stackoverflow.com/users/10769406",
"pm_score": 0,
"selected": false,
"text": "git mv myfile.txt subfolder/myfile.txt\n git mv -r mydir subfolder/mydir\n git config --global core.symlinks true git config --global core.symlinks false"
},
{
"answer_id": 74642960,
"author": "matt",
"author_id": 341994,
"author_profile": "https://Stackoverflow.com/users/341994",
"pm_score": 2,
"selected": false,
"text": "git show git log git diff git merge git cherry-pick git rebase git log git log --follow -B -M git log"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5359329/"
] |
74,533,041
|
<p>I want to post data with ajax request but it said internal server. I tried adding meta data and X-CSRF-TOKEN but still not working. Please take a look at my code</p>
<p>Ajax Code:</p>
<pre><code>$("#firstForm").on("submit", (e)=>{
e.preventDefault()
let dataString = $(this).serialize();
let email = document.getElementById("emailInput").value
let password = document.getElementById("passwordInput").value
var token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
type: 'POST',
url: '/register/create',
data: dataString,
dataType: 'json',
}).done(function(response){
console.log("Done");
});
return false;
})
</code></pre>
<p>HTML Form:</p>
<pre><code><form class="mt-5 text-start" id="firstForm" method="post">
<label class="text-white main-font">Email</label>
<input type="email" name="email" id="emailInput" class="form-control mb-2" placeholder="Enter your email here">
<label class="text-white main-font">Password</label>
<input type="password" name="password" id="passwordInput" class="form-control password mb-2" placeholder="Enter your password here">
<i class="d-none fa-solid fa-eye fs-5 eye" onclick="eyeOpen()"></i>
<i class="fa-solid fa-eye-slash fs-5 eye" onclick="eyeClose()"></i>
<div class="form-check text-start mb-5">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
<label class="form-check-label text-white" for="flexCheckDefault">
I've agree to the terms and conditions!
</label>
</div>
<button id="firstBtn" class="mb-3 mt-5 btn btn-lg btn-danger text-white main-font w-100">Next</button>
</form>
</code></pre>
<p>Laravel Route:</p>
<pre><code>Route::post('register/create', [AccountController::class, 'create']);
</code></pre>
<p>Laravel Controller:</p>
<pre><code>public function create(Request $request) {
$user = new User;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return view('accounts.login');
}
</code></pre>
<p>The Error:</p>
<pre><code>[2022-11-22 13:18:23] local.ERROR: SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (?, $2y$10$uwsmx9lDw4z9a0tGwUjBWeNM8zfNEkoa7oREGdCBgxTkF3Owlo5Uy, 2022-11-22 13:18:23, 2022-11-22 13:18:23)) {"exception":"[object] (Illuminate\\Database\\QueryException(code: HY000): SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (?, $2y$10$uwsmx9lDw4z9a0tGwUjBWeNM8zfNEkoa7oREGdCBgxTkF3Owlo5Uy, 2022-11-22 13:18:23, 2022-11-22 13:18:23)) at C:\\xampp\\htdocs\\dating\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:712)
</code></pre>
|
[
{
"answer_id": 74533619,
"author": "eraufi",
"author_id": 7549561,
"author_profile": "https://Stackoverflow.com/users/7549561",
"pm_score": 1,
"selected": false,
"text": "<form class=\"mt-5 text-start\" id=\"firstForm\" method=\"post\">\n@csrf\n <label class=\"text-white main-font\">Name</label>\n <input type=\"text\" name=\"name\" id=\"name\" class=\"form-control mb-2\" placeholder=\"Enter your Name here\">\n\n <label class=\"text-white main-font\">Email</label>\n <input type=\"email\" name=\"email\" id=\"emailInput\" class=\"form-control mb-2\" placeholder=\"Enter your email here\">\n <label class=\"text-white main-font\">Password</label>\n <input type=\"password\" name=\"password\" id=\"passwordInput\" class=\"form-control password mb-2\" placeholder=\"Enter your password here\">\n <i class=\"d-none fa-solid fa-eye fs-5 eye\" onclick=\"eyeOpen()\"></i>\n <i class=\"fa-solid fa-eye-slash fs-5 eye\" onclick=\"eyeClose()\"></i>\n <div class=\"form-check text-start mb-5\">\n <input class=\"form-check-input\" type=\"checkbox\" value=\"\" id=\"flexCheckDefault\">\n <label class=\"form-check-label text-white\" for=\"flexCheckDefault\">\n I've agree to the terms and conditions!\n </label>\n </div>\n <button id=\"firstBtn\" class=\"mb-3 mt-5 btn btn-lg btn-danger text-white main-font w-100\">Next</button>\n </form>\n public function create(Request $request) {\n $user = new User;\n $user->name= $request->name;\n $user->email = $request->email;\n $user->password = Hash::make($request->password);\n $user->save();\n\n return view('accounts.login');\n}\n let dataString = $(this).serialize();\n $.ajax({\n type: \"post\",\n url: '/register/create',\n data: dataString, // serializes the form's elements.\n success: function(data) {\n console.log(data);\n },\n error: function(data) {\n console.log(data['message']);\n },\n });\n"
},
{
"answer_id": 74534318,
"author": "Thant Htet Aung",
"author_id": 20110311,
"author_profile": "https://Stackoverflow.com/users/20110311",
"pm_score": 1,
"selected": true,
"text": "let dataString = \"email=\" + document.getElementById(\"emailInput\").value + \"&password=\" + document.getElementById(\"passwordInput\").value\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20110311/"
] |
74,533,047
|
<p>I have the following code</p>
<pre><code>mydict = {
"key": {
"k1": "v1",
"k2": "v2",
}
}
for k, (v1, v2) in mydict.items():
</code></pre>
<p><code>v1</code> and <code>v2</code> actaully equals to <code>k1</code> and <code>k2</code>, is there a way to extract <code>v1</code> and <code>v2</code> with any unpacking syntax?</p>
<p>I tried to search for unpacking syntax but found nothing</p>
|
[
{
"answer_id": 74533253,
"author": "Rajesh Kanna",
"author_id": 15656258,
"author_profile": "https://Stackoverflow.com/users/15656258",
"pm_score": 1,
"selected": false,
"text": "for k, (v1, v2) in mydict.items():\n print(\"Access the values for the key:\", k, \"--->\", mydict[k][v1], mydict[k][v2])\n Accessing the values for the key: key ---> v1 v2\n"
},
{
"answer_id": 74538063,
"author": "Сергей Кох",
"author_id": 18400908,
"author_profile": "https://Stackoverflow.com/users/18400908",
"pm_score": 0,
"selected": false,
"text": "mydict = {\n \"key\": {\n \"k1\": \"v1\",\n \"k2\": \"v2\",\n }\n}\n\nfor v1, v2 in mydict.popitem()[1].values():\n print(v1, v2)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16597971/"
] |
74,533,055
|
<p>It seems that eloquent uses a single query for "with" regardless of how many ids there are</p>
<pre><code>Book::with('author')->get();
</code></pre>
<p>This would trigger those two queries:</p>
<pre><code>SELECT * FROM books;
SELECT * FROM authors WHERE id IN (...);
</code></pre>
<p>The second query may have thousands of author ids in the where clause which might cause problems with performance.</p>
<p>Is there some way so it would chunk that when using with?</p>
<p>I am aware that it is generally not a good idea to query such big result sets.</p>
|
[
{
"answer_id": 74533253,
"author": "Rajesh Kanna",
"author_id": 15656258,
"author_profile": "https://Stackoverflow.com/users/15656258",
"pm_score": 1,
"selected": false,
"text": "for k, (v1, v2) in mydict.items():\n print(\"Access the values for the key:\", k, \"--->\", mydict[k][v1], mydict[k][v2])\n Accessing the values for the key: key ---> v1 v2\n"
},
{
"answer_id": 74538063,
"author": "Сергей Кох",
"author_id": 18400908,
"author_profile": "https://Stackoverflow.com/users/18400908",
"pm_score": 0,
"selected": false,
"text": "mydict = {\n \"key\": {\n \"k1\": \"v1\",\n \"k2\": \"v2\",\n }\n}\n\nfor v1, v2 in mydict.popitem()[1].values():\n print(v1, v2)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5661749/"
] |
74,533,075
|
<p>I am very new for Selenium WebDriver.</p>
<p>I have list of URL on the array and want to open the pages ( driver.get("url")) one by one. Here is an example:</p>
<pre><code>urls.forEach( (url) => {
driver.get(url); //=> want to wait here until done.
driver.getTitle(); //=> Here I want to get the title of current page before go to next url.
}
</code></pre>
<p>Actually, currently seems it's ran synchronization with the Promise() - it's open multiple windows one time. I want to wait until the page is done and continue. Any idea for that?</p>
|
[
{
"answer_id": 74533374,
"author": "Alex Karamfilov",
"author_id": 7031148,
"author_profile": "https://Stackoverflow.com/users/7031148",
"pm_score": 1,
"selected": false,
"text": "const {Builder} = require('selenium-webdriver');\nconst chrome = require('selenium-webdriver/chrome');\n\n(async function helloSelenium() {\nconst service = new chrome.ServiceBuilder('/Users/sanders/Desktop/chromedriver');\nconst driver = new Builder().forBrowser('chrome').setChromeService(service).build(); \n\nconst pages = ['https://google.com', 'https://abv.bg', 'https://facebook.com'];\nfor (page of pages){\nawait driver.get(page);\n}\n \n\nawait driver.quit();\n})();\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/987119/"
] |
74,533,121
|
<p>i have made a 2D array in c#. I want have a method to fill in some numbers and a method to print it. But this doesnt work. Since it is for school. The static void main cant be changed. Can anyone help me? the if statement is true and will say invalid number of arguments here is some code:</p>
<pre><code>static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("invalid number of arguments!");
Console.WriteLine("usage: assignment[1-3] <nr of rows> <nr of columns>");
return;
}
int numberOfRows = int.Parse(args[0]);
int numberOfColumns = int.Parse(args[1]);
Program myProgram = new Program();
myProgram.Start(numberOfRows, numberOfColumns);
}
void Start(int numberOfRows, int numberOfColumns)
{
int[,] matrix = new int[numberOfRows, numberOfColumns];
InitMatrix2D(matrix);
DisplayMatrix(matrix);
}
void InitMatrix2D(int[,] matrix)
{
int numberPlusOne = 1;
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int columns = 0; columns < matrix.GetLength(1); columns++)
{
matrix[rows, columns] = numberPlusOne++; // telkens vullen met +1
}
}
}
void DisplayMatrix(int[,] matrix)
{
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int columns = 0; columns < matrix.GetLength(1); columns++)
{
Console.Write($"{matrix[rows, columns]}");
}
}
}
</code></pre>
<p>The if statement is true.</p>
|
[
{
"answer_id": 74533478,
"author": "Peter - Reinstate Monica",
"author_id": 3150802,
"author_profile": "https://Stackoverflow.com/users/3150802",
"pm_score": 1,
"selected": false,
"text": "Main(string[] args) args myprog myprog 1 2 3 args Properties Main int Main Console.Error.WriteLine(\"invalid number of arguments!\"); *.exe program.exe program 5 7"
},
{
"answer_id": 74534927,
"author": "John Alexiou",
"author_id": 380384,
"author_profile": "https://Stackoverflow.com/users/380384",
"pm_score": 0,
"selected": false,
"text": "1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n16,17,18,19,20\n21,22,23,24,25\n26,27,28,29,30\n31,32,33,34,35\n\n| 1 2 3 4 5|\n| 6 7 8 9 10|\n| 11 12 13 14 15|\n| 16 17 18 19 20|\n| 21 22 23 24 25|\n| 26 27 28 29 30|\n| 31 32 33 34 35|\n DisplayDelimited() DisplayTable() public static class DisplayExtensions\n{\n public static string DisplayDelimited<T>(this T[,] matrix, string columnSeparator = \",\")\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < matrix.GetLength(0); i++)\n {\n for (int j = 0; j < matrix.GetLength(1); j++)\n {\n if (j > 0)\n {\n sb.Append(columnSeparator);\n }\n sb.Append(matrix[i, j]);\n }\n sb.AppendLine();\n }\n return sb.ToString();\n }\n\n public static string DisplayTable<T>(this T[,] matrix, int columnWidth = 8, string bracketSymbol = \"|\")\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < matrix.GetLength(0); i++)\n {\n sb.Append(bracketSymbol);\n for (int j = 0; j < matrix.GetLength(1); j++)\n {\n if (j > 0)\n {\n sb.Append(\" \");\n }\n sb.Append(matrix[i, j].ToString().PadLeft(columnWidth));\n }\n sb.AppendLine(bracketSymbol);\n }\n return sb.ToString();\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n int value = 0;\n int[,] matrix = new int[7, 5];\n for (int i = 0; i < 7; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n matrix[i, j] = ++value;\n }\n }\n\n Console.WriteLine(matrix.DisplayDelimited());\n\n Console.WriteLine(matrix.DisplayTable());\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572510/"
] |
74,533,134
|
<p>I have a data frame like this:</p>
<pre><code>Q1 <- c("A",NA,"A",NA,NA,"C","D","A","B", NA)#the right answer is A
Q2 <- c("D",NA,"D","C",NA,NA,"A","A","A","A")#the right answer is D
Q3 <- c("B","B","C","A",NA,"A","B","D","E",NA)#the right answer is B
Q4 <- c("B",NA,"C","C","C","C","D","B",NA,"A")#the right answer is C
mydf <- data.frame(Q1,Q2,Q3,Q4)
mydf
</code></pre>
<p>These are the questions in my test and what I want to do is create a new column named "pass" and give a pass to the participants as long as they answered at least 1 question correctly.</p>
<p>I know how to do it based on only 1 column like this:</p>
<pre><code>mydf_new <- mydf %>%
mutate(Pass = if_else(Q1 %in% c("A"),"yes","no"))
mydf_new
Q1 Q2 Q3 Q4 Pass
1 A D B B yes
2 <NA> <NA> B <NA> no
3 A D C C yes
4 <NA> C A C no
5 <NA> <NA> <NA> C no
6 C <NA> A C no
7 D A B D no
8 A A D B yes
9 B A E <NA> no
10 <NA> A <NA> A no
</code></pre>
<p>But I couldn't figure out how to include multiple columns in the code.</p>
<p>Thanks a lot!</p>
|
[
{
"answer_id": 74533478,
"author": "Peter - Reinstate Monica",
"author_id": 3150802,
"author_profile": "https://Stackoverflow.com/users/3150802",
"pm_score": 1,
"selected": false,
"text": "Main(string[] args) args myprog myprog 1 2 3 args Properties Main int Main Console.Error.WriteLine(\"invalid number of arguments!\"); *.exe program.exe program 5 7"
},
{
"answer_id": 74534927,
"author": "John Alexiou",
"author_id": 380384,
"author_profile": "https://Stackoverflow.com/users/380384",
"pm_score": 0,
"selected": false,
"text": "1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n16,17,18,19,20\n21,22,23,24,25\n26,27,28,29,30\n31,32,33,34,35\n\n| 1 2 3 4 5|\n| 6 7 8 9 10|\n| 11 12 13 14 15|\n| 16 17 18 19 20|\n| 21 22 23 24 25|\n| 26 27 28 29 30|\n| 31 32 33 34 35|\n DisplayDelimited() DisplayTable() public static class DisplayExtensions\n{\n public static string DisplayDelimited<T>(this T[,] matrix, string columnSeparator = \",\")\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < matrix.GetLength(0); i++)\n {\n for (int j = 0; j < matrix.GetLength(1); j++)\n {\n if (j > 0)\n {\n sb.Append(columnSeparator);\n }\n sb.Append(matrix[i, j]);\n }\n sb.AppendLine();\n }\n return sb.ToString();\n }\n\n public static string DisplayTable<T>(this T[,] matrix, int columnWidth = 8, string bracketSymbol = \"|\")\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < matrix.GetLength(0); i++)\n {\n sb.Append(bracketSymbol);\n for (int j = 0; j < matrix.GetLength(1); j++)\n {\n if (j > 0)\n {\n sb.Append(\" \");\n }\n sb.Append(matrix[i, j].ToString().PadLeft(columnWidth));\n }\n sb.AppendLine(bracketSymbol);\n }\n return sb.ToString();\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n int value = 0;\n int[,] matrix = new int[7, 5];\n for (int i = 0; i < 7; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n matrix[i, j] = ++value;\n }\n }\n\n Console.WriteLine(matrix.DisplayDelimited());\n\n Console.WriteLine(matrix.DisplayTable());\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19838934/"
] |
74,533,136
|
<p>So I am going through logs and I want to find IPs that have only logged in after a certain date, but do not show up at all before. I am not sure how to do this in Splunk but I know it is possible. Let's say that the date is 10/1/2022 and the field is IP.</p>
|
[
{
"answer_id": 74535545,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "index=ndx sourcetype=srctp ip=* \n| stats min(_time) as early by ip\n| where early>strptime(\"10/01/2022\",\"%m/%d/%Y\")\n"
},
{
"answer_id": 74585418,
"author": "Hakan",
"author_id": 6215824,
"author_profile": "https://Stackoverflow.com/users/6215824",
"pm_score": 0,
"selected": false,
"text": "index=<yourIndex>\nsource=<yourSource>\nearliest=01/10/2022:00:00:00\nlatest=now\n| < ... rest of your search ... >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5848304/"
] |
74,533,161
|
<p>I have several list objects, each containing 31 dataframes, which I have names 'file1980 through to 'file2010'. These were made by splitting the original (11315 rows) data frame into 31 equal sized (365 rows) data frames using the following:</p>
<pre><code>n <- 31
dataList <- split(MainData, factor(sort(rank(row.names(MainData))%%n)))
names(dataList) <- paste0("file",1980:2010)
</code></pre>
<p>The individual data frames look like this:</p>
<pre><code> jDate V1 V2 V3 V4 V5 V6 V7
1 001 -6.83 -5.83 -7.83 0.05 0.8217593 8.101852 100.0
2 002 -6.33 -4.83 -7.83 0.10 2.2453704 9.259259 100.0
3 003 -5.83 -4.83 -6.83 0.30 1.9444444 8.101852 94.7
4 004 -5.83 -4.83 -6.83 0.10 1.0416667 8.101852 97.5
5 005 -6.33 -4.83 -7.83 0.00 1.1226852 9.259259 98.5
6 006 -7.83 -5.83 -9.83 0.03 2.0949074 10.416667 100.0
</code></pre>
<p>They will be exported with row names removed into *.txt files for use in another piece of software. However, this software starts by reading the first row (which is the column names incsv or txt formats), as the file name, but for the software to run the first row needs to be the file name, so 'file1980' and so on.</p>
<p>I'm hoping to split the list into 31 equally sized files that look like this (with sequential file names, file1980 to file 2010, in the top row):</p>
<pre><code> file1980
1 001 -6.83 -5.83 -7.83 0.05 0.8217593 8.101852 100.0
2 002 -6.33 -4.83 -7.83 0.10 2.2453704 9.259259 100.0
3 003 -5.83 -4.83 -6.83 0.30 1.9444444 8.101852 94.7
4 004 -5.83 -4.83 -6.83 0.10 1.0416667 8.101852 97.5
5 005 -6.33 -4.83 -7.83 0.00 1.1226852 9.259259 98.5
6 006 -7.83 -5.83 -9.83 0.03 2.0949074 10.416667 100.0
7 007 -5.33 -4.83 -5.83 0.00 1.4930556 8.101852 97.6
8 008 -7.33 -5.83 -8.83 0.00 0.9027778 9.259259 100.0
9 009 -7.33 -6.83 -7.83 0.03 0.8217593 8.101852 90.2
</code></pre>
<p>I have now seen two methods which add a new row1 with the file name, but the results here both failed to replace/remove the column names, or replaced them with NA. ON an individual file it is easy to just use names(main file) <- NULL, but this only solves half the problem.</p>
<p>The resulting files all need to be sent along a preset filepath.</p>
|
[
{
"answer_id": 74533273,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 0,
"selected": false,
"text": "dataList <- list(iris, iris, iris) \nnames(dataList) <- paste0(\"file\",1980:1982)\n \npurrr::imap(dataList, ~.x |> \n mutate(Sepal.Length = Sepal.Length |> as.character()) |> \n tibble::add_row(.before = 1, Sepal.Length = .y))\n $file1980\n Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 file1980 NA NA NA <NA>\n2 5.1 3.5 1.4 0.2 setosa\n"
},
{
"answer_id": 74533618,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "tibble::add_row(.before = 1) character data.frame type library(tidyverse)\n\nl <- list(a = data.frame(matrix(1:4, 2)),\n b = data.frame(matrix(1:4, 2)))\n\nl <- l %>% \n map2(.x = ., \n .y = names(.), \n ~.x %>% \n mutate(across(1, as.character)) %>% \n add_row(X1 = .y, .before = 1))\n\nl\n#> $a\n#> X1 X2\n#> 1 a NA\n#> 2 1 3\n#> 3 2 4\n#> \n#> $b\n#> X1 X2\n#> 1 b NA\n#> 2 1 3\n#> 3 2 4\n"
},
{
"answer_id": 74533713,
"author": "moodymudskipper",
"author_id": 2270475,
"author_profile": "https://Stackoverflow.com/users/2270475",
"pm_score": 3,
"selected": true,
"text": "write.table() # data prep, taking 2 chunks of iris\nMainData <- head(iris, 10)\n# optional if you want columns with equal width in the csv :\nMainData[] <- lapply(MainData, format)\nn <- 2 \ndataList <- split(\n MainData, \n factor(sort(rank(row.names(MainData_formatted))%%n))\n)\nnames(dataList) <- paste0(\"file\",seq(n))\ndataList\n\n# print to file\nfor (file in names(dataList)) {\n # define the path, here in the working directory\n path <- paste0(file, \".csv\")\n # print(path) # uncomment to see the path\n # print string to file\n writeLines(file, path)\n # append the data, without headers, quotes or row names\n write.table(\n dataList[[file]], path, \n col.names = FALSE, row.names = FALSE, quote = FALSE, append = TRUE\n )\n}\n\n# in file1.csv :\n\n# file1\n# 5.1 3.5 1.4 0.2 setosa\n# 4.9 3.0 1.4 0.2 setosa\n# 4.7 3.2 1.3 0.2 setosa\n# 4.6 3.1 1.5 0.2 setosa\n# 5.0 3.6 1.4 0.2 setosa\n\n# cleanup\nfile.remove(c(\"file1.csv\", \"file2.csv\"))\n write.table() \" \" sep = \"\\t\""
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17438953/"
] |
74,533,169
|
<p>I have a pre-defined invited guest list. I ask a user for their name and check if the name is in the list. If it is, we simply print welcome. If not, we print the statement in the else condition. After that I want to add looping of name.</p>
<p>What should I add in this? The program should work repeatedly when run once.</p>
<pre><code>guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']
name= input('enter your name please ')
if name in guest_list:
print( "welcome sir/ma'am")
else:
print('sorry you are not invited')
</code></pre>
|
[
{
"answer_id": 74533262,
"author": "Achille G",
"author_id": 10687907,
"author_profile": "https://Stackoverflow.com/users/10687907",
"pm_score": 1,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\n#infinite loop\nwhile True:\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
},
{
"answer_id": 74533291,
"author": "Kupofty",
"author_id": 12134984,
"author_profile": "https://Stackoverflow.com/users/12134984",
"pm_score": 0,
"selected": false,
"text": "while(true) guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\ncondition=True\nwhile(condition):\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n condition=False\n"
},
{
"answer_id": 74533388,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 0,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\nname= input('enter your name please ')\nfor i in range(10): #the loop would run for 10 times starting from 0 to 9\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20070011/"
] |
74,533,182
|
<p>I am trying to create a one dimensional vector which contains references to the elements of a 2d dimensional vector. This is because I later want to iteratively sort the elements of the grid and then perform some operations on the data.</p>
<p>So far I have tried something like the following</p>
<pre class="lang-rust prettyprint-override"><code>let mut grid: Vec<Vec<DataStruct>> = Vec::new();
// initialise the grid
let cell_stack: Vec<&DataStruct> = &field.into_iter.flatten.collect::<Vec<&DataStruct>();
for i in 0..cell_stack.len() {
// sort
// some_func(cell_stack.pop());
}
</code></pre>
<p>However this doesn't work as the line creating <code>cell_stack</code> gives a datatype of <code>&Vec<DataStruct></code> and the collect method is understandably not able to do its thing.</p>
<p>Any help would be appreciated or if I'm just approaching it incorrectly.</p>
|
[
{
"answer_id": 74533262,
"author": "Achille G",
"author_id": 10687907,
"author_profile": "https://Stackoverflow.com/users/10687907",
"pm_score": 1,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\n#infinite loop\nwhile True:\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
},
{
"answer_id": 74533291,
"author": "Kupofty",
"author_id": 12134984,
"author_profile": "https://Stackoverflow.com/users/12134984",
"pm_score": 0,
"selected": false,
"text": "while(true) guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\ncondition=True\nwhile(condition):\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n condition=False\n"
},
{
"answer_id": 74533388,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 0,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\nname= input('enter your name please ')\nfor i in range(10): #the loop would run for 10 times starting from 0 to 9\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20390007/"
] |
74,533,185
|
<p>I have a dashboard very similar to this one-</p>
<pre><code>import datetime
import dash
from dash import dcc, html
import plotly
from dash.dependencies import Input, Output
# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('TERRA')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
html.Div([
html.H4('TERRA Satellite Live Feed'),
html.Div(id='live-update-text'),
dcc.Graph(id='live-update-graph'),
dcc.Interval(
id='interval-component',
interval=1*1000, # in milliseconds
n_intervals=0
)
])
)
# Multiple components can update everytime interval gets fired.
@app.callback(Output('live-update-graph', 'figure'),
Input('live-update-graph', 'relayout'),
Input('interval-component', 'n_intervals'))
def update_graph_live(relayout, n):
if ctx.triggered_id == 'relayout':
* code that affects the y axis *
return fig
else:
satellite = Orbital('TERRA')
data = {
'time': [],
'Latitude': [],
'Longitude': [],
'Altitude': []
}
# Collect some data
for i in range(180):
time = datetime.datetime.now() - datetime.timedelta(seconds=i*20)
lon, lat, alt = satellite.get_lonlatalt(
time
)
data['Longitude'].append(lon)
data['Latitude'].append(lat)
data['Altitude'].append(alt)
data['time'].append(time)
# Create the graph with subplots
fig = plotly.tools.make_subplots(rows=2, cols=1, vertical_spacing=0.2)
fig['layout']['margin'] = {
'l': 30, 'r': 10, 'b': 30, 't': 10
}
fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}
fig.append_trace({
'x': data['time'],
'y': data['Altitude'],
'name': 'Altitude',
'mode': 'lines+markers',
'type': 'scatter'
}, 1, 1)
fig.append_trace({
'x': data['Longitude'],
'y': data['Latitude'],
'text': data['time'],
'name': 'Longitude vs Latitude',
'mode': 'lines+markers',
'type': 'scatter'
}, 2, 1)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
</code></pre>
<p>I want to setup a job queue. Right now, the "code that affects the y axis" part never runs because the interval component fires before it finishes processing. I want to setup logic that says "add every callback to a queue and then fire them one at a time in the order that they were called".</p>
<p>Two questions</p>
<p>1- Can I achieve this with celery?</p>
<p>2- If so, what does a small working example look like?</p>
|
[
{
"answer_id": 74533262,
"author": "Achille G",
"author_id": 10687907,
"author_profile": "https://Stackoverflow.com/users/10687907",
"pm_score": 1,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\n#infinite loop\nwhile True:\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
},
{
"answer_id": 74533291,
"author": "Kupofty",
"author_id": 12134984,
"author_profile": "https://Stackoverflow.com/users/12134984",
"pm_score": 0,
"selected": false,
"text": "while(true) guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\ncondition=True\nwhile(condition):\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n condition=False\n"
},
{
"answer_id": 74533388,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 0,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\nname= input('enter your name please ')\nfor i in range(10): #the loop would run for 10 times starting from 0 to 9\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11117255/"
] |
74,533,195
|
<p>here is my dummy data <a href="https://i.stack.imgur.com/R9tM7.png" rel="nofollow noreferrer">df</a></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>parent</th>
<th>children</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>a</td>
<td>c</td>
</tr>
<tr>
<td>a</td>
<td>d</td>
</tr>
<tr>
<td>b</td>
<td>e</td>
</tr>
<tr>
<td>b</td>
<td>f</td>
</tr>
<tr>
<td>c</td>
<td>g</td>
</tr>
<tr>
<td>c</td>
<td>h</td>
</tr>
<tr>
<td>c</td>
<td>i</td>
</tr>
<tr>
<td>d</td>
<td>j</td>
</tr>
<tr>
<td>d</td>
<td>k</td>
</tr>
<tr>
<td>e</td>
<td>l</td>
</tr>
<tr>
<td>e</td>
<td>m</td>
</tr>
<tr>
<td>f</td>
<td>n</td>
</tr>
<tr>
<td>f</td>
<td>o</td>
</tr>
<tr>
<td>f</td>
<td>p</td>
</tr>
</tbody>
</table>
</div>
<pre><code>import pandas as pd
df=pd.read_csv("myfile.csv")
dfnew=pd.DataFrame(columns=["parent","children"])
x=input("enter the name of root parent : ")
generation=int(input("how many generations you want in the network : "))
mylist=[x]
for i in mylist:
dfntemp=df[df["parent"]==i]
dfnew=pd.concat([dfnew,dfntemp])
mylist2=list(dfntemp["children"])
for j in mylist2:
mylist.append(j)
#I need a condition to break the loop after specific number of generations
</code></pre>
<p>here is the new df which will be used to make graph, <a href="https://i.stack.imgur.com/WvRYs.png" rel="nofollow noreferrer">dfnew</a></p>
<p>I have tried the code mentioned above but my code is fetching all the generations.
I want to break the loop after specific number of generations</p>
<p><strong>EDIT 2</strong>
I have already used this code to make the graph</p>
<p>import networkx as nx
from pyvis.network import Network</p>
<p>G = nx.from_pandas_edgelist(dfnew,'parent','children')
net=Network(height='400px',width='50%',bgcolor='#222222',font_color='white',directed = 'True')
net.from_nx(G)
net.save_graph('network.html')</p>
<p><a href="https://i.stack.imgur.com/YKTZs.png" rel="nofollow noreferrer">pyvis graph</a></p>
<p>The problem is the original data i am working on for my research has around 2 billion rows, so I'm fetching the children from MySQl table using mysql connector so I can not use the original df in python to make generate the graph.</p>
|
[
{
"answer_id": 74533262,
"author": "Achille G",
"author_id": 10687907,
"author_profile": "https://Stackoverflow.com/users/10687907",
"pm_score": 1,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\n#infinite loop\nwhile True:\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
},
{
"answer_id": 74533291,
"author": "Kupofty",
"author_id": 12134984,
"author_profile": "https://Stackoverflow.com/users/12134984",
"pm_score": 0,
"selected": false,
"text": "while(true) guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\ncondition=True\nwhile(condition):\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n condition=False\n"
},
{
"answer_id": 74533388,
"author": "Umair Ali Khan",
"author_id": 15814754,
"author_profile": "https://Stackoverflow.com/users/15814754",
"pm_score": 0,
"selected": false,
"text": "guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\nname= input('enter your name please ')\nfor i in range(10): #the loop would run for 10 times starting from 0 to 9\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19593917/"
] |
74,533,218
|
<p>I have a dataframe as below</p>
<pre><code>year district
2017 arrah
2017 buxar
2017 rohtas
2018 rohtas
2018 arwal
2018 seohar
2019 nawda
2019 buxar
2019 jamui
</code></pre>
<p>I want to subset data in a way that repeated district in 2018 or 2019 should not appear in the subset as shown below</p>
<pre><code>year district
2017 arrah
2017 buxar
2017 rohtas
2018 arwal
2018 seohar
2019 nawda
2019 jamui
</code></pre>
<p>I have tried <code>anti_join</code> function but it is not solving my problem.</p>
|
[
{
"answer_id": 74533339,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nquux %>%\n group_by(district) %>%\n slice_min(year) %>%\n ungroup()\n# # A tibble: 7 x 2\n# year district\n# <int> <chr> \n# 1 2017 arrah \n# 2 2018 arwal \n# 3 2017 buxar \n# 4 2019 jamui \n# 5 2019 nawda \n# 6 2017 rohtas \n# 7 2018 seohar \n quux[ave(quux$year, quux$district, FUN = function(y) y == min(y)) > 0, ]\n# year district\n# 1 2017 arrah\n# 2 2017 buxar\n# 3 2017 rohtas\n# 5 2018 arwal\n# 6 2018 seohar\n# 7 2019 nawda\n# 9 2019 jamui\n quux <- structure(list(year = c(2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L), district = c(\"arrah\", \"buxar\", \"rohtas\", \"rohtas\", \"arwal\", \"seohar\", \"nawda\", \"buxar\", \"jamui\")), class = \"data.frame\", row.names = c(NA, -9L))\n"
},
{
"answer_id": 74533347,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\ndf <- data.frame(\n year = c ( \n 2017, \n 2017, \n 2017,\n 2018, \n 2018, \n 2018, \n 2019, \n 2019, \n 2019\n ),\n district = c (\n \"arrah\",\n \"buxar\",\n \"rohtas\",\n \"rohtas\",\n \"arwal\",\n \"seohar\",\n \"nawda\",\n \"buxar\",\n \"jamui\"\n )\n)\n\n\ndf %>% group_by(district) %>% \n summarise(year = min(year))\n"
},
{
"answer_id": 74533576,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "data.table > library(data.table)\n\n> setcolorder(setDT(df)[, .SD[which.min(year)], district], \"year\")[]\n year district\n1: 2017 arrah\n2: 2017 buxar\n3: 2017 rohtas\n4: 2018 arwal\n5: 2018 seohar\n6: 2019 nawda\n7: 2019 jamui\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6757815/"
] |
74,533,221
|
<p>I'm trying to make an add to cart function on products that are on cards which are loaded dynamically. I have buttons of class add-cart. I am trying to append the products to a UL on click, but testing my code with a simple alert. Here's my HTML:</p>
<pre><code>function loadCard(id, name, imgSrc, price) {
var template =
'<div class="pork-items col-lg-3 col-md-4 col-sm-6">\
<div class="card h-100">\
<div class="card-header">'+ name + '</div>\
<img src="' + imgSrc + '" alt="' + name + '">\
<div class="card-body">\
<h2>' + price + '</h2>\
<div class="d-grid gap-2">\
<button type="button" id="cart'+id+'" class="add-cart btn btn-lg btn-danger">Add to cart</button>\
</div>\
</div>\
</div>\
</div>' ;
var cardContainer = document.getElementById('cardContainer');
cardContainer.innerHTML += template;
}
</code></pre>
<p>And this is what I've tried so far with jquery. Simply trying to get it to alert before I actually make the cart do something meaningful:</p>
<pre><code>$(document).ready(function(){
$(document).on('click', '.add-cart', function(){
alert ("added to cart");
})
});
</code></pre>
<p>The buttons don't respond the way I want them do. Anybody know the solution for this?</p>
|
[
{
"answer_id": 74533339,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nquux %>%\n group_by(district) %>%\n slice_min(year) %>%\n ungroup()\n# # A tibble: 7 x 2\n# year district\n# <int> <chr> \n# 1 2017 arrah \n# 2 2018 arwal \n# 3 2017 buxar \n# 4 2019 jamui \n# 5 2019 nawda \n# 6 2017 rohtas \n# 7 2018 seohar \n quux[ave(quux$year, quux$district, FUN = function(y) y == min(y)) > 0, ]\n# year district\n# 1 2017 arrah\n# 2 2017 buxar\n# 3 2017 rohtas\n# 5 2018 arwal\n# 6 2018 seohar\n# 7 2019 nawda\n# 9 2019 jamui\n quux <- structure(list(year = c(2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L), district = c(\"arrah\", \"buxar\", \"rohtas\", \"rohtas\", \"arwal\", \"seohar\", \"nawda\", \"buxar\", \"jamui\")), class = \"data.frame\", row.names = c(NA, -9L))\n"
},
{
"answer_id": 74533347,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\ndf <- data.frame(\n year = c ( \n 2017, \n 2017, \n 2017,\n 2018, \n 2018, \n 2018, \n 2019, \n 2019, \n 2019\n ),\n district = c (\n \"arrah\",\n \"buxar\",\n \"rohtas\",\n \"rohtas\",\n \"arwal\",\n \"seohar\",\n \"nawda\",\n \"buxar\",\n \"jamui\"\n )\n)\n\n\ndf %>% group_by(district) %>% \n summarise(year = min(year))\n"
},
{
"answer_id": 74533576,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "data.table > library(data.table)\n\n> setcolorder(setDT(df)[, .SD[which.min(year)], district], \"year\")[]\n year district\n1: 2017 arrah\n2: 2017 buxar\n3: 2017 rohtas\n4: 2018 arwal\n5: 2018 seohar\n6: 2019 nawda\n7: 2019 jamui\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572457/"
] |
74,533,263
|
<p>Im trying to add hours to midnight of today eg: like 27 hours</p>
<p>I have tried various methods from the internet but am getting the trunc of the dated expected. eg 23-nov-2022 not 23-nov-2022 03:00. when i run it outside my pl/sql procedure/block i get the desired output</p>
<p>the select:</p>
<p>select to_char(to_date(sysdate,'DD-MON-RRRR HH:MI')+hours/24,'DD-MON-RRRR HH:MI') into v_from from dual;</p>
<p>I need some expert assistance</p>
|
[
{
"answer_id": 74533339,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nquux %>%\n group_by(district) %>%\n slice_min(year) %>%\n ungroup()\n# # A tibble: 7 x 2\n# year district\n# <int> <chr> \n# 1 2017 arrah \n# 2 2018 arwal \n# 3 2017 buxar \n# 4 2019 jamui \n# 5 2019 nawda \n# 6 2017 rohtas \n# 7 2018 seohar \n quux[ave(quux$year, quux$district, FUN = function(y) y == min(y)) > 0, ]\n# year district\n# 1 2017 arrah\n# 2 2017 buxar\n# 3 2017 rohtas\n# 5 2018 arwal\n# 6 2018 seohar\n# 7 2019 nawda\n# 9 2019 jamui\n quux <- structure(list(year = c(2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L), district = c(\"arrah\", \"buxar\", \"rohtas\", \"rohtas\", \"arwal\", \"seohar\", \"nawda\", \"buxar\", \"jamui\")), class = \"data.frame\", row.names = c(NA, -9L))\n"
},
{
"answer_id": 74533347,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\ndf <- data.frame(\n year = c ( \n 2017, \n 2017, \n 2017,\n 2018, \n 2018, \n 2018, \n 2019, \n 2019, \n 2019\n ),\n district = c (\n \"arrah\",\n \"buxar\",\n \"rohtas\",\n \"rohtas\",\n \"arwal\",\n \"seohar\",\n \"nawda\",\n \"buxar\",\n \"jamui\"\n )\n)\n\n\ndf %>% group_by(district) %>% \n summarise(year = min(year))\n"
},
{
"answer_id": 74533576,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "data.table > library(data.table)\n\n> setcolorder(setDT(df)[, .SD[which.min(year)], district], \"year\")[]\n year district\n1: 2017 arrah\n2: 2017 buxar\n3: 2017 rohtas\n4: 2018 arwal\n5: 2018 seohar\n6: 2019 nawda\n7: 2019 jamui\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/828067/"
] |
74,533,298
|
<p>I have an array</p>
<pre><code>array = (Testcase_5_Input_Packets Testcase_3_Input_Packets
Testcase_1_Input_Packets Testcase_4_Input_Packets Testcase_2_Input_Packets)
</code></pre>
<p>i want to sort its elements and save its sorted contents in an array to be like:</p>
<pre><code>array = Testcase_1_Input_Packets
Testcase_2_Input_Packets
Testcase_3_Input_Packets
Testcase_4_Input_Packets
Testcase_5_Input_Packets
</code></pre>
<p>How do i do that in bash ?</p>
|
[
{
"answer_id": 74534002,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 2,
"selected": false,
"text": "readarray -t sorted_array < <(printf '%s\\n' \"${array[@]}\" | sort)\n"
},
{
"answer_id": 74534221,
"author": "Jack Simth",
"author_id": 2640003,
"author_profile": "https://Stackoverflow.com/users/2640003",
"pm_score": -1,
"selected": false,
"text": "rawdata=(\"Data 1\" \"Data 3\" \"Data 2\" \"Data 4\")\ntmpfile=/dev/shm/tmp.$$\ntouch \"$tmpfile\"\nchmod 600 \"$tmpfile\"\nfor e in \"${rawdata[@]}\" \ndo\n echo \"$e\" >> \"$tmpfile\"\ndone\nsortdata=$(cat \"$tmpfile\" | sort)\necho \"$sortdata\" > \"$tmpfile\"\nsortedarray=()\nwhile read line\ndo\n sortedarray+=(\"$line\")\ndone < \"$tmpfile\"\nrm -f \"$tmpfile\"\n rawdata=(\"Data 1\" \"Data 3\" \"Data 2\" \"Data 4\")\ntmpfile=/dev/shm/tmp.$$\ntouch \"$tmpfile\"\nchmod 600 \"$tmpfile\"\nfor element in \"${rawdata[@]}\" \ndo\n alteration=$(echo \"$element\" | sed 's/\\n/NEWLINEMARKER/g')\n alteration=$(echo \"$alteration\" | sed 's/NEWLINEMARKER$//g')\n echo \"$alteration\" >> \"$tmpfile\"\ndone\nsortdata=$(cat \"$tmpfile\" | sort)\necho \"$sortdata\" > \"$tmpfile\"\nsortedarray=()\nwhile read line\ndo\n element=$(echo \"$line\" | sed 's/NEWLINEMARKER/\\n/g')\n sortedarray+=(\"$element\")\ndone < \"$tmpfile\"\nrm -f \"$tmpfile\"\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7974136/"
] |
74,533,345
|
<p>When i run this query:</p>
<pre><code>db.friendRequests.aggregate([
$lookup: {
from: "users",
localField: "author",
foreignField: "_id",
pipeline: [
{
$match: {
$expr: {
friend_id: new mongoose.Types.ObjectId(userid),
},
},
},
],
as: "userdata",
}
])
</code></pre>
<p>It returns every entry in the collection, but theres a pipeline in it. Then why is it not working?</p>
<p>Can you help me? Thanks!</p>
<p><strong>Playground:</strong>
<a href="https://mongoplayground.net/p/Eh2j8lU4IQl" rel="nofollow noreferrer">https://mongoplayground.net/p/Eh2j8lU4IQl</a></p>
|
[
{
"answer_id": 74533400,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 0,
"selected": false,
"text": "$lookup localField foreignField pipeline let"
},
{
"answer_id": 74534041,
"author": "user20042973",
"author_id": 20042973,
"author_profile": "https://Stackoverflow.com/users/20042973",
"pm_score": 2,
"selected": true,
"text": "friend_id friendRequests users $lookup $match $lookup db.friendRequests.aggregate([\n {\n $match: {\n \"friend_id\": ObjectId(\"636a88de3e45346191cf4257\")\n }\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"author\",\n foreignField: \"_id\",\n as: \"userdata\"\n }\n }\n])\n inventory users $match: { \n $expr: {\n friend_id: new mongoose.Types.ObjectId(userid),\n },\n}\n $match: { \n friend_id: new mongoose.Types.ObjectId(userid),\n}\n $match: { \n $expr: {\n $eq: [ \n \"$friend_id\", new mongoose.Types.ObjectId(userid)\n ]\n },\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20150565/"
] |
74,533,357
|
<p>I have a EventHub trigger function app using Elastic Premium tier and I'm getting a bottleneck on the EventHub side because the function doesn't scale more than 20 instances(Maximum of Minimum Instances Always Ready) to process messages, even reaching a high CPU percentage.</p>
<p>Is there any way to "force" this scaling to hit the Maximum Burst?
Because as I'm using EventHub trigger, I need a larger number of instances to consume more messages.</p>
<p><a href="https://i.stack.imgur.com/Gx4eR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gx4eR.png" alt="[](https://i.stack.imgur.com/R3PZi.png)" /></a></p>
<p>FYI: I'm using Runtime Scale Monitoring as Microsoft recommends here: <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-networking-options?tabs=azure-cli#virtual-network-triggers-non-http" rel="nofollow noreferrer">Runtime Scale Monitoring</a></p>
<p>I'm trying to scale my Elastic Premium Azure Function to consume my EventHub messages without any lag.</p>
|
[
{
"answer_id": 74533400,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 0,
"selected": false,
"text": "$lookup localField foreignField pipeline let"
},
{
"answer_id": 74534041,
"author": "user20042973",
"author_id": 20042973,
"author_profile": "https://Stackoverflow.com/users/20042973",
"pm_score": 2,
"selected": true,
"text": "friend_id friendRequests users $lookup $match $lookup db.friendRequests.aggregate([\n {\n $match: {\n \"friend_id\": ObjectId(\"636a88de3e45346191cf4257\")\n }\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"author\",\n foreignField: \"_id\",\n as: \"userdata\"\n }\n }\n])\n inventory users $match: { \n $expr: {\n friend_id: new mongoose.Types.ObjectId(userid),\n },\n}\n $match: { \n friend_id: new mongoose.Types.ObjectId(userid),\n}\n $match: { \n $expr: {\n $eq: [ \n \"$friend_id\", new mongoose.Types.ObjectId(userid)\n ]\n },\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9434572/"
] |
74,533,364
|
<p>I want to program a game where the user has 10 days. I have an int main and a LOT of int functions. The user can visit a lot of functions everytime easily and the functions represent the locations in the game. What I want to do is for the day to increase by 1 everytime I leave a location. lets say that my first location is function1, in here it will state that it is day 1, once i leave the location, it will bring me to another function and it will state day 2.</p>
<p>I havent tried to actually code it as I am a bit lost on how the other functions will know the values of the other. I think that the code I want will need to make use of pointers and paramenters but I'm not very sure on how to get that work. This is what I have for now.</p>
<pre><code>int function1()
{
int day = 1;
printf ("today is day %d", day);
}
</code></pre>
|
[
{
"answer_id": 74533400,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 0,
"selected": false,
"text": "$lookup localField foreignField pipeline let"
},
{
"answer_id": 74534041,
"author": "user20042973",
"author_id": 20042973,
"author_profile": "https://Stackoverflow.com/users/20042973",
"pm_score": 2,
"selected": true,
"text": "friend_id friendRequests users $lookup $match $lookup db.friendRequests.aggregate([\n {\n $match: {\n \"friend_id\": ObjectId(\"636a88de3e45346191cf4257\")\n }\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"author\",\n foreignField: \"_id\",\n as: \"userdata\"\n }\n }\n])\n inventory users $match: { \n $expr: {\n friend_id: new mongoose.Types.ObjectId(userid),\n },\n}\n $match: { \n friend_id: new mongoose.Types.ObjectId(userid),\n}\n $match: { \n $expr: {\n $eq: [ \n \"$friend_id\", new mongoose.Types.ObjectId(userid)\n ]\n },\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20117789/"
] |
74,533,385
|
<p>I am trying to filter my dataframe based on IQR for a few selected features. The code I use is the following:</p>
<pre><code>import pandas as pd
import numpy as np
# Load data
df = pd.read_csv("dataframe.csv")
features = df.loc[:, ('col1, col2, col3, col4, col5')]
print("Old Shape: ", df.shape)
def filtering(column_name):
print(column_name)
Q1 = np.percentile(df[column_name], 25,
interpolation = 'midpoint')
Q3 = np.percentile(df[column_name], 75,
interpolation = 'midpoint')
IQR = Q3 - Q1
# Upper bound
upper = np.where(df[column_name] >= (Q3+1.5*IQR))
# Lower bound
lower = np.where(df[column_name] <= (Q1-1.5*IQR))
''' Removing the Outliers '''
df.drop(upper[0], inplace = True)
df.drop(lower[0], inplace = True)
print("New Shape: ", df.shape)
print('==== done ====')
for col in features.columns:
filtering(col)
</code></pre>
<p>The error (on line 28, df.drop(lower[0], inplace=True):</p>
<blockquote>
<p>KeyError: '[14] not found in axis'</p>
</blockquote>
<p>The KeyError is caused by the fact that an index is already dropped because it is an outlier in one of the features, after which it is detected again. Since it is already dropped, this index cannot be found. I am however unsure how it is detected as an outlier after already being dropped. Therefore I am unaware how to tackle this problem.</p>
|
[
{
"answer_id": 74533547,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 1,
"selected": false,
"text": "try:\n # Your code\nexcept KeyError:\n # Do what you want to do in case a KeyError occurs e.g. log something or print something\n\n"
},
{
"answer_id": 74534766,
"author": "SanderJ",
"author_id": 19969414,
"author_profile": "https://Stackoverflow.com/users/19969414",
"pm_score": 1,
"selected": true,
"text": "indices = []\ndef outlier_indices(column_name):\n Q1 = np.percentile(df[column_name], 25, interpolation = 'midpoint')\n Q3 = np.percentile(df[column_name], 75, interpolation = 'midpoint')\n IQR = Q3 - Q1\n \n # Upper bound\n upper = np.where(df[column_name].tolist() >= (Q3+1.5*IQR))[0].tolist()\n # Lower bound\n lower = np.where(df[column_name].tolist() <= (Q1-1.5*IQR))[0].tolist()\n indices.extend(upper)\n indices.extend(lower)\n\nfor col in features.columns:\n outlier_indices(col)\n\nindices = set(indices)\ndf.drop(indices, inplace=True)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19969414/"
] |
74,533,407
|
<p>I am using modal to answer if the user want to delete some data. I need his answer to continue the function and delete or not depending on what was chosen.
Here is my code:
I am using an imagem to call the function:</p>
<pre><code><img src={deletes} width="25" height="25" alt="Edit" onClick={(e)=>deleteHandler()} className="imagemEnter"/>
</code></pre>
<p>This is the function called:</p>
<pre><code>const [modal, setModal] = useState({
isOpen: false,
type: "",
frase: "",
confirm: ""
});
function deleteHandler(){
setModal({ isOpen: true, type: "sure?", frase:"Are you sure that you want to remove this data?", confirm:false });
console.log(modal.confirm);
}
</code></pre>
<p>This is my modal:</p>
<pre><code>function ModalConfirm(props) {
const { modal, setModal } = props;
function closeModal() {
setModal({ ...modal, isOpen: false });
}
function backPage(){
setModal({ ...modal, isOpen: false, confirm true});
}
return (
<div>
if (props.modal.tipo === "sure?") {
return (
<div>
<Modal
ariaHideApp={false}
isOpen={modal.isOpen}
onRequestClose={closeModal}
style={{
overlay: {
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
opacity: 1,
},
content: {
textAlign: "center",
position: "absolute",
width: "500px",
height: "360px",
top: "130px",
left: "550px",
right: "500px",
bottom: "200px",
border: "1px solid #ccc",
overflow: "auto",
WebkitOverflowScrolling: "touch",
borderRadius: "10px",
outline: "none",
padding: "20px",
},
}}
>
<img src={question} width="150" height="150" alt="Question" />
<p></p>
<p className="title">{props.modal.frase}</p>
<div>
<button
onClick={closeModal}
titulo="Cancel"
></button>
<button
onClick={backPage}
titulo="Confirm"
></button>
</div>
</Modal>
</div>
);
}
})()}
</div>
);
</code></pre>
<p>At first click on remove image, the console.log(modal.confirm) works first than the modal is closed and so it prints empty.
If I close the modal by clicking in the confirm button and try again to click on remove image, it shows true.
How can I make the rest of the function depending on what the modal returns?</p>
<p><strong>Resolution</strong>:</p>
<p>Modal:</p>
<pre><code>const { confirmDelete, modal, setModal } = props;
function backPage(){
confirmDelete(true);
setModal({ ...modal, isOpen: false});
}
</code></pre>
<p>Main:</p>
<pre><code>const [confirmDelete, setConfirmDelete] = useState(false);
const [modal, setModal] = useState({
isOpen: false,
type: "",
frase: ""
});
function delete(valor) {
if (valor) {
//delete fetch
}
function deleteHandler() {
setModal({
isOpen: true,
tipo: "sure?",
frase: "Are you sure that you want to remove this data?",
});
}
return(
....
<Modal
confirmDelete={confirmDelete}
modal={modal}
setModal={setModal}
/>
)
</code></pre>
|
[
{
"answer_id": 74533547,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 1,
"selected": false,
"text": "try:\n # Your code\nexcept KeyError:\n # Do what you want to do in case a KeyError occurs e.g. log something or print something\n\n"
},
{
"answer_id": 74534766,
"author": "SanderJ",
"author_id": 19969414,
"author_profile": "https://Stackoverflow.com/users/19969414",
"pm_score": 1,
"selected": true,
"text": "indices = []\ndef outlier_indices(column_name):\n Q1 = np.percentile(df[column_name], 25, interpolation = 'midpoint')\n Q3 = np.percentile(df[column_name], 75, interpolation = 'midpoint')\n IQR = Q3 - Q1\n \n # Upper bound\n upper = np.where(df[column_name].tolist() >= (Q3+1.5*IQR))[0].tolist()\n # Lower bound\n lower = np.where(df[column_name].tolist() <= (Q1-1.5*IQR))[0].tolist()\n indices.extend(upper)\n indices.extend(lower)\n\nfor col in features.columns:\n outlier_indices(col)\n\nindices = set(indices)\ndf.drop(indices, inplace=True)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20520826/"
] |
74,533,434
|
<pre><code>phoneError(): string {
return this.userForm.get('phonenumber').hasError('required')
? $localize`:|Validation message: Only number`
: this.userForm.get('phonenumber').hasError('minlength') ||
this.userForm.get('phonenumber').hasError('maxLength')
? $localize`:|Validation message: 3 min`
: '3 min';
}
<mat-form-field appearance="fill">
<input matInput formControlName="phonenumber" required />
<mat-label>Phone number</mat-label>
<mat-error *ngIf="'userForm.get('phonenumbern').invalid">{{ phoneError() }}</mat-error>
</mat-form-field>
</div>
</code></pre>
<p>How short this ? those are messages for input required</p>
<p>I want functional input if somone don't put anything in input I want see on Required:
Only number. If someone enters too many digits or too few I want see 3 min</p>
|
[
{
"answer_id": 74533547,
"author": "Chris",
"author_id": 14408656,
"author_profile": "https://Stackoverflow.com/users/14408656",
"pm_score": 1,
"selected": false,
"text": "try:\n # Your code\nexcept KeyError:\n # Do what you want to do in case a KeyError occurs e.g. log something or print something\n\n"
},
{
"answer_id": 74534766,
"author": "SanderJ",
"author_id": 19969414,
"author_profile": "https://Stackoverflow.com/users/19969414",
"pm_score": 1,
"selected": true,
"text": "indices = []\ndef outlier_indices(column_name):\n Q1 = np.percentile(df[column_name], 25, interpolation = 'midpoint')\n Q3 = np.percentile(df[column_name], 75, interpolation = 'midpoint')\n IQR = Q3 - Q1\n \n # Upper bound\n upper = np.where(df[column_name].tolist() >= (Q3+1.5*IQR))[0].tolist()\n # Lower bound\n lower = np.where(df[column_name].tolist() <= (Q1-1.5*IQR))[0].tolist()\n indices.extend(upper)\n indices.extend(lower)\n\nfor col in features.columns:\n outlier_indices(col)\n\nindices = set(indices)\ndf.drop(indices, inplace=True)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15515293/"
] |
74,533,447
|
<p>This is an example scenario and we wanted to understand if it would be possible to recover it. And also understand better about the schema.</p>
<p>In a hypothetical scenario of just 1 node, Cassandra 3.11. I have 1 keyspace and 1 table.</p>
<pre><code>root@dd85fa9a3c41:/# cqlsh -k cycling -e "describe tables;"
rank_by_year_and_name
</code></pre>
<p>Now I reset my schema and restart Cassandra: (I have no nodes to replicate it again)</p>
<pre><code>root@dd85fa9a3c41:/# nodetool resetlocalschema
</code></pre>
<p>With the new schema, I no longer "see" my keyspace+table:</p>
<pre><code>root@dd85fa9a3c41:/# cqlsh -e "describe keyspaces;"
system_traces system_schema system_auth system system_distributed
</code></pre>
<p>I lost my original schema, where was my keyspace+table. But, they are still on disk:</p>
<pre><code>root@dd85fa9a3c41:/# ls -l /var/lib/cassandra/data/cycling/
total 0
drwxr-xr-x 1 root root 14 Nov 22 11:32 rank_by_year_and_name-4eedbbf0
</code></pre>
<p>How could I restore that keyspace in this scenario? With sstableloader I could recreate keyspace+table and import.</p>
<p>I would like to recover this schema and see my keyspace+table again.
I haven't found any way to do this without manually recreating and importing with sstableloader.
Thank you if you help me!</p>
|
[
{
"answer_id": 74536831,
"author": "Jeremy",
"author_id": 6493269,
"author_profile": "https://Stackoverflow.com/users/6493269",
"pm_score": 1,
"selected": false,
"text": "nodetool snapshot schema.cql"
},
{
"answer_id": 74554235,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": true,
"text": "resetlocalschema resetlocalschema nodetool snapshot snapshots/ manifest.json schema.cql data/\n community/\n users-6140f420a4a411ea9212efde68e7dd4b/\n snapshots/\n 1591083719993/\n manifest.json\n mc-1-big-CompressionInfo.db\n mc-1-big-Data.db\n mc-1-big-Digest.crc32\n mc-1-big-Filter.db\n mc-1-big-Index.db\n mc-1-big-Statistics.db\n mc-1-big-Summary.db\n mc-1-big-TOC.txt\n schema.cql\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572046/"
] |
74,533,457
|
<p>for exmaple if the path in the string textBoxRadarPath.txt is D:\test\test1\test2
i want to get only the part D:\test</p>
<p>using root is not what i needed root give me D:\ but i want to first path level.</p>
<pre><code>Directory.CreateDirectory(Path.GetPathRoot(textBoxPath.Text) + "\\" + urlsListFolder);
</code></pre>
|
[
{
"answer_id": 74536831,
"author": "Jeremy",
"author_id": 6493269,
"author_profile": "https://Stackoverflow.com/users/6493269",
"pm_score": 1,
"selected": false,
"text": "nodetool snapshot schema.cql"
},
{
"answer_id": 74554235,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": true,
"text": "resetlocalschema resetlocalschema nodetool snapshot snapshots/ manifest.json schema.cql data/\n community/\n users-6140f420a4a411ea9212efde68e7dd4b/\n snapshots/\n 1591083719993/\n manifest.json\n mc-1-big-CompressionInfo.db\n mc-1-big-Data.db\n mc-1-big-Digest.crc32\n mc-1-big-Filter.db\n mc-1-big-Index.db\n mc-1-big-Statistics.db\n mc-1-big-Summary.db\n mc-1-big-TOC.txt\n schema.cql\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9890333/"
] |
74,533,481
|
<p>I'm currently trying to extract information from lots of PDF forms such as this:</p>
<p><a href="https://i.stack.imgur.com/lEsG9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lEsG9.jpg" alt="enter image description here" /></a></p>
<p>The text 'female' should be extracted here. So contrary to my title, I'm actually trying to extract text with no strikethroughs rather than text that with strikethroughs. But if I can identify which words with strikethroughs, I can easily identify the inverse.</p>
<p>Gaining inspiration from <a href="https://stackoverflow.com/questions/72601927/how-to-identify-strike-out-text-from-pdf-files-using-python">this post</a>, I came up with this set of codes:</p>
<pre><code>import os
import glob
from pdf2docx import parse
from docx import Document
lst = []
files = glob.glob(os.getcwd() + r'\PDFs\*.pdf')
for i in range(len(files)):
filename = files[i].split('\\')[-1].split('.')[-2]
parse(files[i])
document = Document(os.getcwd() + rf'\PDFs\{filename}.docx')
for p in document.paragraphs:
for run in p.runs:
if run.font.strike:
lst.append(run.text)
os.remove(os.getcwd() + rf'\PDFs\{filename}.docx')
</code></pre>
<p>What the above code does is to convert all my PDF files into word documents (docx), and then search through the word documents for text with strikethroughs, extract those text, then delete the word document.</p>
<p>As you may have rightfully suspected, this set of code is very slow and inefficient, taking about 30s to run on my sample set of 4 PDFs with less than 10 pages combined.</p>
<p>I don't believe this is the best way to do this. However, when I did some research online, <a href="https://pypi.org/project/pdf2docx/" rel="nofollow noreferrer">pdf2docx extracts data from PDFs using PyMuPDF</a>, but yet <a href="https://github.com/pymupdf/PyMuPDF/issues/515" rel="nofollow noreferrer">PyMuPDF do not come with the capability to recognise strikethroughs in PDF text</a>. How could this be so? When pdf2docx could perfectly convert strikethroughs in PDFs into docx document, indicating that the strikethroughs are being recognised at some level.</p>
<p>All in all, I would like to seek advice on whether or not it is possible to extract text with strikethroughs in PDF using Python. Thank you!</p>
|
[
{
"answer_id": 74536831,
"author": "Jeremy",
"author_id": 6493269,
"author_profile": "https://Stackoverflow.com/users/6493269",
"pm_score": 1,
"selected": false,
"text": "nodetool snapshot schema.cql"
},
{
"answer_id": 74554235,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": true,
"text": "resetlocalschema resetlocalschema nodetool snapshot snapshots/ manifest.json schema.cql data/\n community/\n users-6140f420a4a411ea9212efde68e7dd4b/\n snapshots/\n 1591083719993/\n manifest.json\n mc-1-big-CompressionInfo.db\n mc-1-big-Data.db\n mc-1-big-Digest.crc32\n mc-1-big-Filter.db\n mc-1-big-Index.db\n mc-1-big-Statistics.db\n mc-1-big-Summary.db\n mc-1-big-TOC.txt\n schema.cql\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16377721/"
] |
74,533,538
|
<p>I am try to do autocomplete using <a href="https://stackblitz.com/edit/angular-ypmnoj-whmsis?file=src%2Fapp%2Fautocomplete-filter-example.ts,src%2Fapp%2Fautocomplete-filter-example.html" rel="nofollow noreferrer">this </a>code.</p>
<p>Now, the issue is I receiving option as <code>[object objecct]</code>, I understood that's because I need to specify the field like <code>option.name</code> but when I do getting <code>does not exist error</code>. To check I options empty or Not I print it. like below</p>
<pre><code>private _filter(value: string): string[] {
if (value && value !== '') {
const filterValue = value.toLowerCase();
console.log('this',options)
return this.options.filter(
(option) =>
option.name.toLowerCase().includes(filterValue) ||
option.clock.toString().startsWith(filterValue)
);
} else {
return [];
}
</code></pre>
<p>output:</p>
<p><a href="https://i.stack.imgur.com/aSMeQ.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><strong>Note:</strong> My code is almost same as above reference, just I am map specific fields from another array.</p>
<pre><code> retrieveAbsence():void{
this.employeeService.getAll()
.subscribe(
data => {
this.employee = data;
console.log(data);
},
error => {
console.log(error);
});
}
</code></pre>
<pre><code>this.options = this.employee.map(((i) => {
return {
id: i.id,
clock: i.clock,
payroll:i.payroll,
name: i.firstName+' '+i.surName
}}));
</code></pre>
<p>Output: James Smith</p>
|
[
{
"answer_id": 74536831,
"author": "Jeremy",
"author_id": 6493269,
"author_profile": "https://Stackoverflow.com/users/6493269",
"pm_score": 1,
"selected": false,
"text": "nodetool snapshot schema.cql"
},
{
"answer_id": 74554235,
"author": "Erick Ramirez",
"author_id": 4269535,
"author_profile": "https://Stackoverflow.com/users/4269535",
"pm_score": 1,
"selected": true,
"text": "resetlocalschema resetlocalschema nodetool snapshot snapshots/ manifest.json schema.cql data/\n community/\n users-6140f420a4a411ea9212efde68e7dd4b/\n snapshots/\n 1591083719993/\n manifest.json\n mc-1-big-CompressionInfo.db\n mc-1-big-Data.db\n mc-1-big-Digest.crc32\n mc-1-big-Filter.db\n mc-1-big-Index.db\n mc-1-big-Statistics.db\n mc-1-big-Summary.db\n mc-1-big-TOC.txt\n schema.cql\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20412540/"
] |
74,533,544
|
<p>Situation:
I have Model have a relation 1-1, sample:</p>
<pre><code>class User(models.Model):
user_namme = models.CharField(max_length=40)
type = models.CharField(max_length=255)
created_at = models.DatetimeField()
...
class Book(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
</code></pre>
<p>And I have a around 200,000 records.</p>
<ul>
<li>Languague: Python</li>
<li>Framework: Django</li>
<li>Database: Postgres</li>
</ul>
<p>Question:</p>
<ul>
<li>How can I delete 200,000 records above with minimal cost?</li>
</ul>
<p>Solution I have tried:</p>
<pre><code>user_ids = Users.objects.filter(type='sample', created_date__gte='2022-11-15 08:00', created_date__lt="2022-11-15 08:30").values_list('id',flat=True)[:200000] # Fetch 200,000 user ids.
for i, _ in enumerate(user_ids[:: 1000]):
with transaction.atomic():
batch_start = i * self.batch_size
batch_end = batch_start + self.batch_size
_, deleted = Users.objects.filter(id__in=user_ids[batch_start,batch_end]
</code></pre>
<p><strong>With this solution, my server use arround:</strong></p>
<ul>
<li>600MB CPU</li>
<li>300MB RAM</li>
<li>Take more 15 minutes to finish workload.</li>
</ul>
<hr />
<p>I wonder do anyone have a better solution?</p>
|
[
{
"answer_id": 74544214,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 3,
"selected": false,
"text": "if Variable.exists():\n\n Variable.delete()\n"
},
{
"answer_id": 74557618,
"author": "Thành Lý",
"author_id": 15654520,
"author_profile": "https://Stackoverflow.com/users/15654520",
"pm_score": 0,
"selected": false,
"text": "user_ids = Users.objects.filter(type='sample', created_date__gte='2022-11-15 08:00', created_date__lt=\"2022-11-15 08:30\").values_list('id',flat=True)[:200000] # Fetch 200,000 user ids. \n\nfor i in range(0, 3):\n user_ids_str = \"\"\n for user_id in user_ids.iterator(chunk_size=5000):\n user_ids_str += f\"{user_id},\"\n query = f\"\"\"\n DELETE FROM \"user\" WHERE \"user\".\"id\" IN ({user_ids_str});\n DELETE FROM \"book\" WHERE \"user\".\"id\" IN ({user_ids_str});\n \"\"\"\n with transaction.atomic():\n with connection.cursor() as c:\n c.execute(\"SET statement_timeout = '10min';\")\n c.execute(query)\n"
},
{
"answer_id": 74579425,
"author": "Robert Moskal",
"author_id": 775345,
"author_profile": "https://Stackoverflow.com/users/775345",
"pm_score": 0,
"selected": false,
"text": "DELETE FROM \"book\" WHERE \"user\".\"id\" IN (select id from user where created_date >= '2022-11-15 08:00' and...)\nDELETE FROM \"user\" WHERE created_date >= '2022-11-15 08:00' and...\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15654520/"
] |
74,533,549
|
<p>I'm trying to implement an <code>Array</code>-like linked list (same methods). I have the following two classes:</p>
<pre><code>class Node {
constructor(value, next_node=null, prev_node=null) {
this.value = value;
this.next_node = next_node;
this.prev_node = prev_node;
}
}
class List {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
}
</code></pre>
<p>I'm trying to implement <code>values()</code>, <code>entries()</code> and <code>keys()</code> similar to of <code>Array</code>. My code:</p>
<pre><code> [Symbol.iterator]() {
let current = this.head;
return {
next() {
if (current) {
let value = current.value;
current = current.next;
return {value: value, done: false};
}
return {done: true};
}
};
}
entries() {
return this._entries();
}
keys() {
return this._keys();
}
values() {
return this._values();
}
* _entries() {
var node = this.head;
var counter = 0;
while (node) {
yield [counter,node.value];
node = node.next_node;
counter += 1;
}
}
* _keys() {
var node = this.head;
var counter = 0;
while (node) {
yield counter;
node = node.next_node;
counter += 1;
}
}
* _values() {
var node = this.head;
while (node) {
yield node.value;
node = node.next_node;
}
}
</code></pre>
<p>Comparing between <code>array.entries()</code> and <code>list.entries()</code> I see:</p>
<pre><code>Object [Array Iterator] {}
Object [Generator] {}
</code></pre>
<p>I understand that there is a difference between an iterator and generator. Two questions:</p>
<ol>
<li>Should I keep it as <code>Generator</code>? Why <code>Array</code> uses <code>Array Iterator</code> instead of a <code>Generator</code>?</li>
<li>If I should switch to an iterator, how it should be done for those methods? As you can see, I implemented <code>[Symbol.iterator]()</code>, but how do I use it in <code>entries()</code>, <code>keys()</code> and <code>values()</code>?</li>
</ol>
|
[
{
"answer_id": 74544214,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 3,
"selected": false,
"text": "if Variable.exists():\n\n Variable.delete()\n"
},
{
"answer_id": 74557618,
"author": "Thành Lý",
"author_id": 15654520,
"author_profile": "https://Stackoverflow.com/users/15654520",
"pm_score": 0,
"selected": false,
"text": "user_ids = Users.objects.filter(type='sample', created_date__gte='2022-11-15 08:00', created_date__lt=\"2022-11-15 08:30\").values_list('id',flat=True)[:200000] # Fetch 200,000 user ids. \n\nfor i in range(0, 3):\n user_ids_str = \"\"\n for user_id in user_ids.iterator(chunk_size=5000):\n user_ids_str += f\"{user_id},\"\n query = f\"\"\"\n DELETE FROM \"user\" WHERE \"user\".\"id\" IN ({user_ids_str});\n DELETE FROM \"book\" WHERE \"user\".\"id\" IN ({user_ids_str});\n \"\"\"\n with transaction.atomic():\n with connection.cursor() as c:\n c.execute(\"SET statement_timeout = '10min';\")\n c.execute(query)\n"
},
{
"answer_id": 74579425,
"author": "Robert Moskal",
"author_id": 775345,
"author_profile": "https://Stackoverflow.com/users/775345",
"pm_score": 0,
"selected": false,
"text": "DELETE FROM \"book\" WHERE \"user\".\"id\" IN (select id from user where created_date >= '2022-11-15 08:00' and...)\nDELETE FROM \"user\" WHERE created_date >= '2022-11-15 08:00' and...\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808098/"
] |
74,533,558
|
<p>I have a ListView but when I call it only the get_context_data method works (the news and category model, not the product) when I try to display the information of the models in the templates.</p>
<p>view:</p>
<pre><code>class HomeView(ListView):
model = Product
context_object_name='products'
template_name = 'main/home.html'
paginate_by = 25
def get_context_data(self, **kwargs):
categories = Category.objects.all()
news = News.objects.all()
context = {
'categories' : categories,
'news' : news,
}
context = super().get_context_data(**kwargs)
return context
</code></pre>
<p>There is also this piece of code:
context = super().get_context_data(**kwargs)
If it's written before:
categories = Category.objects.all()
The Product model is show but not the others.</p>
<p>base.html</p>
<pre><code><body>
...
{% include "base/categories.html" %}
{% block content %}{% endblock %}
</body>
</code></pre>
<p>home.html</p>
<pre><code>{% extends 'main/base.html' %}
{% block content %}
<div>
...
<div>
{% for product in products %}
{% if product.featured == True %}
<div>
<div>
<a href="">{{ product.author }}</a>
<small>{{ product.date_posted|date:"F d, Y" }}</small>
</div>
<p>Some text..</p>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endblock content %}
</code></pre>
<p>categories.html</p>
<pre><code><div>
...
<div>
{% for category in categories %}
<p>{{ category.name }}</p>
{% endfor %}
</div>
<div>
{% for new in news %}
<p>{{ new.title }}</p>
{% endfor %}
</div>
</div>
</code></pre>
|
[
{
"answer_id": 74533595,
"author": "neverwalkaloner",
"author_id": 641249,
"author_profile": "https://Stackoverflow.com/users/641249",
"pm_score": 2,
"selected": true,
"text": "def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n categories = Category.objects.all()\n news = News.objects.all()\n context.update({\n 'categories' : categories,\n 'news' : news,\n })\n \n return context\n"
},
{
"answer_id": 74534267,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 2,
"selected": false,
"text": "class HomeView(ListView):\n model = Product\n context_object_name='products'\n template_name = 'main/home.html'\n paginate_by = 25\n\n def get_context_data(self, **kwargs):\n categories = Category.objects.all()\n news = News.objects.all()\n context = super().get_context_data(**kwargs)\n context[\"categories\"]=categories\n context[\"news\"]=news\n return context\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19881162/"
] |
74,533,565
|
<p>I want to calculate all values in the column <code>C</code> and place it at the bottom on the same Column C as total sum.</p>
<p>I'm generating excel with data from database - some orders and their amount. Want to calculate the total amount.</p>
<p>My script is</p>
<pre><code>$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
$i = 1;
$excel->getActiveSheet()->setCellValue('A'.$i, '#');
$excel->getActiveSheet()->setCellValue('B'.$i, 'Date');
$excel->getActiveSheet()->setCellValue('C'.$i, 'Amount');
$excel->getActiveSheet()->setCellValue('D'.$i, '');
$stmt = $mysqli->prepare("SELECT id, date, order_sum, SUM(order_sum) as totalSum FROM orders ");
$stmt->execute();
$stmt->bind_result($id, $date, $order_sum, $totalSum );
while ($stmt->fetch())
{
$i++;
$excel->getActiveSheet()->setCellValue('A'.$i, $id);
$excel->getActiveSheet()->setCellValue('B'.$i, $date);
$excel->getActiveSheet()->setCellValue('C'.$i, $order_sum);
$excel->getActiveSheet()->setCellValue('D'.$i, '=SUM(C2:C'.($totalSum -1).')' );
}
$stmt->close();
header('Content-Type: text/html; charset=UTF8');
header('Content-disposition: attachment; filename=orders.xls');
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Cache-Control: max-age=0');
$file = PHPExcel_IOFactory::createWriter($excel,'Excel2007');
$file->setPreCalculateFormulas(true);
$file->save('php://output');
</code></pre>
<p>But got error</p>
<blockquote>
<p>PHP Fatal error: Uncaught PHPExcel_Calculation_Exception: Worksheet!D2 -> undefined variable '.'</p>
</blockquote>
|
[
{
"answer_id": 74534229,
"author": "Juan",
"author_id": 6510866,
"author_profile": "https://Stackoverflow.com/users/6510866",
"pm_score": 2,
"selected": false,
"text": "<?\n$excel = new PHPExcel(); \n$excel->setActiveSheetIndex(0); \n \n$i = 1;\n$generalSum = 0;\n\n$excel->getActiveSheet()->setCellValue('A'.$i, '#');\n$excel->getActiveSheet()->setCellValue('B'.$i, 'Date');\n$excel->getActiveSheet()->setCellValue('C'.$i, 'Amount');\n\n$stmt = $mysqli->prepare(\"SELECT id, date, order_sum, SUM(order_sum) as totalSum FROM orders \");\n$stmt->execute();\n$stmt->bind_result($id, $date, $order_sum, $totalSum );\n \nwhile ($stmt->fetch()) \n{\n $i++; \n $excel->getActiveSheet()->setCellValue('A'.$i, $id);\n $excel->getActiveSheet()->setCellValue('B'.$i, $date);\n $excel->getActiveSheet()->setCellValue('C'.$i, $order_sum);\n\n // Incrementation Sum\n $generalSum = bcadd($generalSum, $order_sum);\n}\n\n// Incrementation\n$i++; \n\n// Display Bottom Line with Sum\n$excel->getActiveSheet()->setCellValue('A'.$i,0);\n$excel->getActiveSheet()->setCellValue('B'.$i,0);\n$excel->getActiveSheet()->setCellValue('C'.$i,$generalSum);\n\n$stmt->close();\n\nheader('Content-Type: text/html; charset=UTF8');\nheader('Content-disposition: attachment; filename=orders.xls');\nheader('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');\nheader('Cache-Control: max-age=0');\n$file = PHPExcel_IOFactory::createWriter($excel,'Excel2007'); \n$file->setPreCalculateFormulas(true);\n$file->save('php://output');\n?>\n"
},
{
"answer_id": 74535392,
"author": "Travis",
"author_id": 20263317,
"author_profile": "https://Stackoverflow.com/users/20263317",
"pm_score": 2,
"selected": false,
"text": "$column = \"D\";\n$column_total = \"C\";\n$row = $i+1;\n$excel->getActiveSheet()->setCellValue($column_total.$row, 'Total: ');\n$excel->getActiveSheet()->setCellValue($column.$row , '=SUM(C3:C'.$i.')');\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20263317/"
] |
74,533,579
|
<p>I want to 'group by' beers so that they are grouped together, with the respect aggregate rating and tasters (people who review the beers) listed in separate columns.</p>
<p>Here is my code:</p>
<pre><code>create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
;
</code></pre>
<p>Yet my output looks like this:</p>
<pre><code>beers=# select * from tasters_avg_ratings1;
taster | beer | rating
--------+------------------------+--------
Peter | XXXX | 5.0
Sarah | James Squire Pilsener | 3.0
Raghu | Sierra Nevada Pale Ale | 3.0
Hector | Fosters | 3.0
John | Chimay Red | 3.0
John | Sierra Nevada Pale Ale | 5.0
Geoff | James Squire Pilsener | 4.0
Ramez | Sierra Nevada Pale Ale | 4.0
John | 80/- | 4.0
John | Rasputin | 4.0
Adam | Old | 4.0
John | Crown Lager | 2.0
Jeff | Sierra Nevada Pale Ale | 4.0
Sarah | Burragorang Bock | 4.0
Sarah | Scharer's Lager | 3.0
Sarah | New | 2.0
Geoff | Redback | 4.0
Adam | Victoria Bitter | 1.0
Sarah | Victoria Bitter | 1.0
Raghu | Rasputin | 3.0
Ramez | Bigfoot Barley Wine | 3.0
Hector | Sierra Nevada Pale Ale | 4.0
Sarah | Old | 3.0
Jeff | Burragorang Bock | 3.0
John | Empire | 3.0
Sarah | James Squire Amber Ale | 3.0
Rose | Redback | 5.0
Geoff | Empire | 3.0
Adam | New | 1.0
Jeff | Rasputin | 1.0
Raghu | Old Tire | 5.0
John | Victoria Bitter | 1.0
(32 rows)
</code></pre>
<p>As you can see, the beers are NOT grouped together. Ideally for example, the 'Victoria Bitter' beers should be displayed as a group, not separated.</p>
<p>The desired result is achieved using 'order by'. For example:</p>
<pre><code>create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
order by a.beer
;
</code></pre>
<p>OUTPUT:</p>
<pre><code>beers=# select * from tasters_avg_ratings1;
taster | beer | rating
--------+------------------------+--------
John | 80/- | 4.0
Ramez | Bigfoot Barley Wine | 3.0
Jeff | Burragorang Bock | 3.0
Sarah | Burragorang Bock | 4.0
John | Chimay Red | 3.0
John | Crown Lager | 2.0
Geoff | Empire | 3.0
John | Empire | 3.0
Hector | Fosters | 3.0
Sarah | James Squire Amber Ale | 3.0
Geoff | James Squire Pilsener | 4.0
Sarah | James Squire Pilsener | 3.0
Adam | New | 1.0
Sarah | New | 2.0
Adam | Old | 4.0
Sarah | Old | 3.0
Raghu | Old Tire | 5.0
Jeff | Rasputin | 1.0
John | Rasputin | 4.0
Raghu | Rasputin | 3.0
Geoff | Redback | 4.0
Rose | Redback | 5.0
Sarah | Scharer's Lager | 3.0
Hector | Sierra Nevada Pale Ale | 4.0
Jeff | Sierra Nevada Pale Ale | 4.0
John | Sierra Nevada Pale Ale | 5.0
Raghu | Sierra Nevada Pale Ale | 3.0
Ramez | Sierra Nevada Pale Ale | 4.0
Adam | Victoria Bitter | 1.0
John | Victoria Bitter | 1.0
Sarah | Victoria Bitter | 1.0
Peter | XXXX | 5.0
(32 rows)
</code></pre>
<p>So while I know order by achieves my result, why doesn't 'group by' do the same thing? It is frustrating because I have seen numerous examples on the internet using 'group by' and succeeding especially in cases similar to mine with non-aggregate and aggregate columns. For example: <a href="https://learnsql.com/blog/error-with-group-by/" rel="nofollow noreferrer">https://learnsql.com/blog/error-with-group-by/</a> , at tip #3.</p>
<p>Any help would be appreciated, thanks!</p>
|
[
{
"answer_id": 74533885,
"author": "Ali Ibrahim",
"author_id": 19427487,
"author_profile": "https://Stackoverflow.com/users/19427487",
"pm_score": 1,
"selected": false,
"text": "GROUP BY a.beers create or replace view tasters_avg_ratings1\nas\nselect a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating \nfrom allratings a\ngroup by a.beer\norder by 1,3;\n"
},
{
"answer_id": 74533955,
"author": "SebDieBln",
"author_id": 10171966,
"author_profile": "https://Stackoverflow.com/users/10171966",
"pm_score": 1,
"selected": false,
"text": "SELECT ORDER BY GROUP BY ORDER BY ORDER BY"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16791848/"
] |
74,533,587
|
<p>i'm doing a compareTo() method for a string the way i was taught but it's giving me an error, it seems that the way i formulated it similar to how you would usually do for a number doesn't go well with a string.
Class Car(implements the interface: Comparable<> )
- Attributes:
o Unique number plate (final) : String
o Brand: String
o Rental rate: double
o Extra three (from your choice)
- Methods:
o Constructors: zero-arg and multi-arg
o getters
o setters (if needed)
o toString()
o equals(): compare plate numbers
o compareTo(): compare plate numbers</p>
<pre><code>import java.io.*;
import java.util.*;
public class RentalCars implements Comparable<RentalCars> {
private final String UNP;
private String brandName;
private double rental_Rates;
private int wheel_Drive;
private String color;
private int milage;
public RentalCars(){
this(null,null, 0.0, 0, null, 0);
}
public RentalCars(String UNP, String brandName, double rental_Rates, int wheel_Drive,
String color, int milage){
this.UNP = UNP;
this.brandName=brandName;
this.rental_Rates=rental_Rates;
this.wheel_Drive=wheel_Drive;
this.color=color;
this.milage=milage;
}
public String getUNP() {
return UNP;
}
public String getbrandName() {
return brandName;
}
public void setbrandname(String brandName) {
this.brandName=brandName;
}
public double getrental_Rates() {
return rental_Rates;
}
public void setrental_Rates(double rental_Rates) {
this.rental_Rates=rental_Rates;
}
public int getwheel_Drive() {
return wheel_Drive;
}
public void setwheel_Drive(int wheel_Drive) {
this.wheel_Drive=wheel_Drive;
}
public String getcolor() {
return color;
}
public void setcolor(String color) {
this.color=color;
}
public int getmilage() {
return milage;
}
public void setmilage(int milage) {
this.milage=milage;
}
@Override
public String toString()
{
return "the Number Plate of the car is "+UNP+"the Car brand is "+brandName+
"the rent rate of this car is "+rental_Rates+"the wheel drive is "+
wheel_Drive+"the color of the car is "+color+"the milage is "+milage;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (!super.equals(obj)) {
return false;
}
RentalCars other = (RentalCars) obj;
return Objects.equals(UNP, other.UNP);
}
public int compareTo(RentalCars rc){
if(UNP>rc.UNP)return 1;
if(UNP<rc.UNP)return -1;
return 0;
}
}
</code></pre>
|
[
{
"answer_id": 74533648,
"author": "Elliott Frisch",
"author_id": 2970947,
"author_profile": "https://Stackoverflow.com/users/2970947",
"pm_score": 2,
"selected": false,
"text": "UNP String > < String compareTo String public int compareTo(RentalCars rc){\n return UNP.compareTo(rc.UNP);\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15566755/"
] |
74,533,589
|
<p>If I have this collection</p>
<pre><code>[
{
"_id": "637cbf94b4741277c3b53c6c",
"text": "outter",
"username": "test1",
"address": [
{
"text": "inner",
"username": "test2",
"_id": "637cbf94b4741277c3b53c6e"
}
],
"__v": 0
}
]
</code></pre>
<p>and would like to search for the nested document by <code>_id</code> and return all of the nested document. If I do</p>
<pre><code>db.collection.find({
_id: "637cbf94b4741277c3b53c6c"
},
{
address: {
$eq: {
_id: "637cbf94b4741277c3b53c6e"
}
}
})
</code></pre>
<p>I get</p>
<pre><code>query failed: (Location16020) Expression $eq takes exactly 2 arguments. 1 were passed in.
</code></pre>
<p><a href="https://mongoplayground.net/p/koKFRuSpqob" rel="nofollow noreferrer">Playground link</a></p>
<p><strong>Question</strong></p>
<p>Can anyone see what I am doing wrong?</p>
|
[
{
"answer_id": 74533648,
"author": "Elliott Frisch",
"author_id": 2970947,
"author_profile": "https://Stackoverflow.com/users/2970947",
"pm_score": 2,
"selected": false,
"text": "UNP String > < String compareTo String public int compareTo(RentalCars rc){\n return UNP.compareTo(rc.UNP);\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256439/"
] |
74,533,590
|
<p>I have a macOS electron app that is based on this electron-forge Webpack + Typescript <a href="https://www.electronforge.io/templates/typescript-+-webpack-template" rel="nofollow noreferrer">boilerplate</a>, integrated with React, as documented <a href="https://www.electronforge.io/guides/framework-integration/react-with-typescript#create-the-app-and-setup-the-typescript-config" rel="nofollow noreferrer">here</a>.</p>
<h3>TL;DR</h3>
<p>I'm able to spawn a binary node module in dev mode (<code>yarn start</code>) but not able to in production mode (<code>yarn package</code>).</p>
<h3>A bit further</h3>
<p>A binary node module that is being <code>spawn</code>ed but not imported is not being packed by <code>webpack</code>.</p>
<h3>The Full Problem:</h3>
<p>In my code, I use the NodeJS <a href="https://nodejs.org/docs/latest-v14.x/api/child_process.html" rel="nofollow noreferrer">spawn</a> module to run a child process in the background. This child process is an installed dependency node module (btw it's <a href="https://www.npmjs.com/package/@loadmill/agent" rel="nofollow noreferrer">@loadmill/agent</a> npm package, but the problem could be applied to any package that is being called by a binary file, instead of a js file).</p>
<pre><code>spawn('loadmill-agent', ['start', '-t', token])
</code></pre>
<p>But I don't explicitly import this package into the code. (i.e there is no
<code>import '@loadmill/agent'</code> line anywhere in the code)</p>
<p>It works well in development mode. When I run <code>yarn start</code>, the child process is spawned and I can communicate with it and all is well under the sun.</p>
<p>However, when I package the app and run the same line of code, I get an error.</p>
<pre><code>Uncaught Exception:
Error: spawn loadmill-agent ENOENT
at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
at onErrorNT (node:internal/child_process:477:16)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
</code></pre>
<p>I searched a bit and found that I can debug spawned process errors in NodeJS like so:</p>
<pre><code> spawn('loadmill-agent', ['start', '-t', token], {
env: { NODE_DEBUG: 'child_process', },
}
);
</code></pre>
<p>Now instead of the error popup dialog, I get the actual error output:
<code>/bin/sh: loadmill-agent: command not found</code>
Which means the command is either not installed, or not on the PATH, or not executable without a shell.</p>
<p>Furthermore, the <code>@loadmill/agent</code> node module was not even packed by webpack as a dependency. I know this because I don't see it in the dependencies of the packaged electron app contents/resources.</p>
<h3>To recap:</h3>
<ol>
<li>The <code>loadmill-agent</code> node module is not being packed by <code>webpack</code>.</li>
<li>The <code>spawn</code>ed process outputs
<code>/bin/sh: loadmill-agent: command not found</code></li>
</ol>
<h3>My assumption of a solution:</h3>
<ol>
<li>Get webpack to somehow package <code>@loadmill/agent</code>.</li>
<li>figure out how to spawn <code>@loadmill/agent</code> with-the-right-path-to-binary-file.
This issue can probably be resolved by configuring the PATH env var or by using the <a href="https://www.npmjs.com/package/fix-path" rel="nofollow noreferrer">fix-path</a> npm package.</li>
</ol>
|
[
{
"answer_id": 74603180,
"author": "keymap",
"author_id": 1609474,
"author_profile": "https://Stackoverflow.com/users/1609474",
"pm_score": 1,
"selected": false,
"text": "packagerConfig.extraResource extraResource app.isPackaged process.resourcesPath dependencies node_modules"
},
{
"answer_id": 74640381,
"author": "Gilad Gur",
"author_id": 10223524,
"author_profile": "https://Stackoverflow.com/users/10223524",
"pm_score": 1,
"selected": true,
"text": "const { start } = require('@loadmill/agent');\nconst stop = start({\n token: 'INSERT_TOKEN_HERE'\n});\n\n// Stop the agent at a later time\n loadmill-agent.ts spawn fork fork fork const childProcess = fork('loadmill-agent', // args & options ...\n index.js loadmill-agent.js fork loadmill-agent.ts webpack.main.config.js module.exports = {\n...\n entry: {\n index: './src/index.ts',\n 'loadmill-agent': './src/loadmill-agent.ts',\n },\n...\n}\n index.js loadmill-agent.js app.getAppPath() + '/.webpack/main/' + 'loadmill-agent'\n app.getAppPath() '/.webpack/main/' 'loadmill-agent' .js const childProcess = fork(app.getAppPath() + '/.webpack/main/' + 'loadmill-agent', // args & options ...\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10223524/"
] |
74,533,645
|
<p>I need convert the date in NiFi:</p>
<p>2022-11-22 00:00:00</p>
<p>To:</p>
<p>2022-11-22T00:00:00.000Z (ISO 8601)</p>
<p>can someone help me convert this date?</p>
|
[
{
"answer_id": 74603180,
"author": "keymap",
"author_id": 1609474,
"author_profile": "https://Stackoverflow.com/users/1609474",
"pm_score": 1,
"selected": false,
"text": "packagerConfig.extraResource extraResource app.isPackaged process.resourcesPath dependencies node_modules"
},
{
"answer_id": 74640381,
"author": "Gilad Gur",
"author_id": 10223524,
"author_profile": "https://Stackoverflow.com/users/10223524",
"pm_score": 1,
"selected": true,
"text": "const { start } = require('@loadmill/agent');\nconst stop = start({\n token: 'INSERT_TOKEN_HERE'\n});\n\n// Stop the agent at a later time\n loadmill-agent.ts spawn fork fork fork const childProcess = fork('loadmill-agent', // args & options ...\n index.js loadmill-agent.js fork loadmill-agent.ts webpack.main.config.js module.exports = {\n...\n entry: {\n index: './src/index.ts',\n 'loadmill-agent': './src/loadmill-agent.ts',\n },\n...\n}\n index.js loadmill-agent.js app.getAppPath() + '/.webpack/main/' + 'loadmill-agent'\n app.getAppPath() '/.webpack/main/' 'loadmill-agent' .js const childProcess = fork(app.getAppPath() + '/.webpack/main/' + 'loadmill-agent', // args & options ...\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18716709/"
] |
74,533,664
|
<p>I am attempting to limit my dataframe to the days of each month between the 20th and the 25th . I got a big dataset with many dates ranging over many years. It looks something like this:</p>
<pre><code>Event Date
Football 20.12.2016
Work 15.10.2019
Holiday 30.11.2018
Running 24.01.2020
</code></pre>
<p>I would then like to restrict my results to:</p>
<pre><code>Event Date
Football 20.12.2016
Running 24.01.2020
</code></pre>
<p>Any tips on how to do this?</p>
|
[
{
"answer_id": 74533757,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 0,
"selected": false,
"text": "Date # base R\nsubset(quux, between(as.integer(sub(\"\\\\..*\", \"\", Date)), 20, 25))\n# Event Date\n# 1 Football 20.12.2016\n# 4 Running 24.01.2020\n\n# dplyr\nquux %>% \n filter(between(as.integer(sub(\"\\\\..*\", \"\", Date)), 20, 25))\n between dplyr:: data.table:: between <- function(x, y, z) y <= x & x <= z\n NA quux <- structure(list(Event = c(\"Football\", \"Work\", \"Holiday\", \"Running\"), Date = c(\"20.12.2016\", \"15.10.2019\", \"30.11.2018\", \"24.01.2020\")), class = \"data.frame\", row.names = c(NA, -4L))\n"
},
{
"answer_id": 74533798,
"author": "cgvoller",
"author_id": 17144974,
"author_profile": "https://Stackoverflow.com/users/17144974",
"pm_score": 2,
"selected": false,
"text": "dplyr lubridate Date as.Date df <-\n data.frame(\n Event = c(\"Football\", \"Work\", \"Holiday\", \"Running\"),\n Date = c(\"20.12.2016\", \"15.10.2019\", \"30.11.2018\", \"24.01.2020\")\n )\n\ndf$Date <- as.Date(df$Date, format = \"%d.%m.%Y\")\n\ndf %>% filter(day(Date) >= 20 & day(Date) <= 25)\n 1 Football 2016-12-20\n2 Running 2020-01-24\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18705501/"
] |
74,533,678
|
<p>Is it possible to create an a curved element like this with border radius ruler if so what is it? <a href="https://i.stack.imgur.com/RJk7s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJk7s.png" alt="enter image description here" /></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
width: 500px;
height: 100px;
border: solid 0 #000;
border-color: #000 transparent transparent transparent;
border-radius: 100%/0 100px 0 0px;
background-color: #FF7C07;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code></pre>
</div>
</div>
</p>
<p>i tried doing it with this code but i cant seem to make it work.</p>
|
[
{
"answer_id": 74534708,
"author": "Romualds Cirsis",
"author_id": 1031255,
"author_profile": "https://Stackoverflow.com/users/1031255",
"pm_score": 1,
"selected": false,
"text": ".box {\n height: 200px;\n overflow:hidden;\n background-color: #FF7C07;\n position:relative;\n z-index:10;\n}\n.box:before {\n content: \"\";\n position: absolute;\n left: -25%;\n right: -125%;\n top: -200%;\n bottom: 30%;\n background-color: #FFF;\n border-radius: 100%;\n z-index: -1;\n} <div class=\"box\">123</div>"
},
{
"answer_id": 74534793,
"author": "MNTL",
"author_id": 20572137,
"author_profile": "https://Stackoverflow.com/users/20572137",
"pm_score": 1,
"selected": false,
"text": ".box {\n width: 500px;\n height: 100px;\n border: solid 0 #000;\n border-color: #000 transparent transparent transparent;\n background-color: #FF7C07;\n}\n\n.top-right {\n margin-top: -125px;\n margin-left: -35px;\n width: 535px;\n height: 80px;\n border-bottom-left-radius: 100%;\n background-color: #FFFFFF;\n} <div class=\"box\"></div>\n<div class=\"top-right\"></div>"
},
{
"answer_id": 74538671,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 3,
"selected": true,
"text": ".box {\n width: 500px;\n height: 200px;\n background: radial-gradient(110% 50% at top right,#0000 99%,#FF7C07);\n} <div class=\"box\"></div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893404/"
] |
74,533,740
|
<p>I'm trying to figure out how to make sure that the consecutive values are not the same in a list. Expected output: [1, 2, 3]
<strong>Actual output</strong>: [1, 1, 3, 3]</p>
<p>I also tried using <code>next()</code> but that gave me "list object is not an iterator"</p>
<p>What is best practices here and what am I doing wrong?</p>
<pre><code>def unique_in_order(iterable):
return [x for x in iterable if not iterable[x] == iterable[x+1]]
print(unique_in_order([1,1,2,2,3,3]))
</code></pre>
|
[
{
"answer_id": 74533880,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 3,
"selected": true,
"text": "def unique_in_order(iterable):\n lst = [iterable[0]]\n for x in range(len(iterable) - 1):\n if iterable[x] != iterable[x + 1]:\n lst.append(iterable[x + 1])\n return lst\n zip def unique_in_order(iterable):\n lst = [iterable[0]]\n for x, y in zip(iterable, iterable[1:]):\n if x != y:\n lst.append(y)\n return lst\n"
},
{
"answer_id": 74533920,
"author": "Marcello Zago",
"author_id": 16872314,
"author_profile": "https://Stackoverflow.com/users/16872314",
"pm_score": 0,
"selected": false,
"text": "def unique_in_order(iterable):\n list = []\n\n for index, x in enumerate(iterable):\n if index == len(iterable) -1:\n list.append(x)\n elif iterable[index] != iterable[index+1]:\n list.append(x)\n\n return list\n"
},
{
"answer_id": 74533973,
"author": "Kurt",
"author_id": 18648900,
"author_profile": "https://Stackoverflow.com/users/18648900",
"pm_score": 0,
"selected": false,
"text": "def unique(lst):\n prev = None\n for val in lst:\n if val != prev:\n prev = val\n yield val\n\nprint(list(unique([1,1,2,2,3,3,1,1])))\n"
},
{
"answer_id": 74534028,
"author": "CodeKorn",
"author_id": 10882128,
"author_profile": "https://Stackoverflow.com/users/10882128",
"pm_score": 0,
"selected": false,
"text": "def unique_in_order(lst):\n return [lst[i] for i in range(len(lst)-1) if lst[i] != lst[i+1]] + [lst[-1]]\n"
},
{
"answer_id": 74534483,
"author": "bereal",
"author_id": 770830,
"author_profile": "https://Stackoverflow.com/users/770830",
"pm_score": 0,
"selected": false,
"text": "itertools.groupby() from itertools import groupby\n\ndef unique_in_order(iterable):\n return [i[0] for i in groupby(iterable)]\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18714330/"
] |
74,533,763
|
<p>After so many tries I still can't figure out how to do the following.</p>
<p>The situation is as follows:</p>
<p>I have a Catalogue that contains hardware that is stored in a Sheet called "Catalogus_Hardware", all the hardware is located in column A.
I want that hardware to show up in my ComboBox called ComboBox1.</p>
<p>Currently I have it "configured" like this:</p>
<pre><code>Private Sub UserForm_Activate()
With Me.ComboBox1
.Clear
.AddItem ""
.AddItem "Device1
.AddItem "Device2"
.AddItem "Device3"
.AddItem "Device4"
End With
Call Refresh_Data
End Sub
</code></pre>
<p>But I don't want it that way because adding an item one by one just takes too much time.</p>
<p>What I want is when I update my catalogue it automatically updates the hardware in my ComboBox as well.</p>
<p>Thanks in advance</p>
<p>I watched several tutorials, guides etc,... But I keep doing something wrong and I have no idea what.</p>
|
[
{
"answer_id": 74533880,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 3,
"selected": true,
"text": "def unique_in_order(iterable):\n lst = [iterable[0]]\n for x in range(len(iterable) - 1):\n if iterable[x] != iterable[x + 1]:\n lst.append(iterable[x + 1])\n return lst\n zip def unique_in_order(iterable):\n lst = [iterable[0]]\n for x, y in zip(iterable, iterable[1:]):\n if x != y:\n lst.append(y)\n return lst\n"
},
{
"answer_id": 74533920,
"author": "Marcello Zago",
"author_id": 16872314,
"author_profile": "https://Stackoverflow.com/users/16872314",
"pm_score": 0,
"selected": false,
"text": "def unique_in_order(iterable):\n list = []\n\n for index, x in enumerate(iterable):\n if index == len(iterable) -1:\n list.append(x)\n elif iterable[index] != iterable[index+1]:\n list.append(x)\n\n return list\n"
},
{
"answer_id": 74533973,
"author": "Kurt",
"author_id": 18648900,
"author_profile": "https://Stackoverflow.com/users/18648900",
"pm_score": 0,
"selected": false,
"text": "def unique(lst):\n prev = None\n for val in lst:\n if val != prev:\n prev = val\n yield val\n\nprint(list(unique([1,1,2,2,3,3,1,1])))\n"
},
{
"answer_id": 74534028,
"author": "CodeKorn",
"author_id": 10882128,
"author_profile": "https://Stackoverflow.com/users/10882128",
"pm_score": 0,
"selected": false,
"text": "def unique_in_order(lst):\n return [lst[i] for i in range(len(lst)-1) if lst[i] != lst[i+1]] + [lst[-1]]\n"
},
{
"answer_id": 74534483,
"author": "bereal",
"author_id": 770830,
"author_profile": "https://Stackoverflow.com/users/770830",
"pm_score": 0,
"selected": false,
"text": "itertools.groupby() from itertools import groupby\n\ndef unique_in_order(iterable):\n return [i[0] for i in groupby(iterable)]\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572889/"
] |
74,533,775
|
<p>I am having trouble finding good resources for what best practices would be for Flutter development, specifically for form handling.</p>
<p>Everything I find on form submissions is fairly clear, but the problem is they all have the validation logic and submission logic directly in the form widget. I don't like this as it seems it would get very convoluted very quickly with more than say 3 inputs and any sort of more than basic validation logic. It also seems to violate the separation of concerns thinking that I though was supposed to be a big thing in Flutter/Dar (at least from what I have read).</p>
<p>So my chosen solution for this was my FormHandler class, which I defined in the form_handler.dart file. It has some static methods for validation of input, some methods for submission handling, and a formInput of type Map<String, dynamic> for storing key value pairs of user input.</p>
<p>It works like this:</p>
<ol>
<li>An instance of the FormHandler is created</li>
<li>The user inputs the data</li>
<li>On form.save(), for each user input, the input data is stored in the formInput map, with key being the title of the input, and the value being the user's input.</li>
<li>The submission button would run the validation and save functions and then take the data from formInput and send it to something like a database handler that would store it on the db</li>
</ol>
<p>form_handler.dart:</p>
<pre><code>class FormHandler {
// make new form handler with empty map
FormHandler({required this.formInput});
// for storing input key value pairs
Map<String, dynamic> formInput;
// Form submissions
// new course
void submitCourse({required formKey}){
final form = formKey.currentState;
// save on validate
if( form.validate() ){
form.save();
// then make new course via the database controller
}
}
// Input validations
static String? validateTextInput(String? input){
if( input == null || input.isEmpty ){
return 'Field must not be empty';
} else {
return null;
}
}
}
</code></pre>
<p>I'm just wondering if this is a good solution, what are some potential pitfalls, any suggestions etc.</p>
<p>It seems like a good solution to me, but I would like feedback from someone with more experience than me.</p>
<p>Thanks, Seth.</p>
|
[
{
"answer_id": 74533880,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 3,
"selected": true,
"text": "def unique_in_order(iterable):\n lst = [iterable[0]]\n for x in range(len(iterable) - 1):\n if iterable[x] != iterable[x + 1]:\n lst.append(iterable[x + 1])\n return lst\n zip def unique_in_order(iterable):\n lst = [iterable[0]]\n for x, y in zip(iterable, iterable[1:]):\n if x != y:\n lst.append(y)\n return lst\n"
},
{
"answer_id": 74533920,
"author": "Marcello Zago",
"author_id": 16872314,
"author_profile": "https://Stackoverflow.com/users/16872314",
"pm_score": 0,
"selected": false,
"text": "def unique_in_order(iterable):\n list = []\n\n for index, x in enumerate(iterable):\n if index == len(iterable) -1:\n list.append(x)\n elif iterable[index] != iterable[index+1]:\n list.append(x)\n\n return list\n"
},
{
"answer_id": 74533973,
"author": "Kurt",
"author_id": 18648900,
"author_profile": "https://Stackoverflow.com/users/18648900",
"pm_score": 0,
"selected": false,
"text": "def unique(lst):\n prev = None\n for val in lst:\n if val != prev:\n prev = val\n yield val\n\nprint(list(unique([1,1,2,2,3,3,1,1])))\n"
},
{
"answer_id": 74534028,
"author": "CodeKorn",
"author_id": 10882128,
"author_profile": "https://Stackoverflow.com/users/10882128",
"pm_score": 0,
"selected": false,
"text": "def unique_in_order(lst):\n return [lst[i] for i in range(len(lst)-1) if lst[i] != lst[i+1]] + [lst[-1]]\n"
},
{
"answer_id": 74534483,
"author": "bereal",
"author_id": 770830,
"author_profile": "https://Stackoverflow.com/users/770830",
"pm_score": 0,
"selected": false,
"text": "itertools.groupby() from itertools import groupby\n\ndef unique_in_order(iterable):\n return [i[0] for i in groupby(iterable)]\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7304712/"
] |
74,533,777
|
<p>Im currently trying to write a "controller" File with a macro, that opens other files and just calls 3 Macros in each file.
All these files have the same structure.
My Problem is that I can't see the VBA structure, but I do know the Macronames as they are shown to me.
But everytime I try to call these macros im getting the following Error Message:</p>
<blockquote>
<p>Runtimeerror 1004 The Makro !xxxx can't run. It's maybe not available
in this file or all macros have been deactivated.</p>
</blockquote>
<p>Macros are activated. If I click the button in that File the macro that gets triggered works perfectly fine.</p>
<p>Any suggestions welcome</p>
<p>Thanks</p>
<p>I've tried everything with wrong filenames with false characters and single commatas.
The Opening of the File via
Set wb = Workboos.open
works perfectly fine, so the file name probably can't be a part of the problem.</p>
|
[
{
"answer_id": 74534352,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": 1,
"selected": false,
"text": "Public Sub macro1()\n MsgBox \"macro1 launched from \" & ThisWorkbook.Name\nEnd Sub\n\nPublic Sub macro2()\n MsgBox \"macro2 launched from \" & ThisWorkbook.Name\nEnd Sub\n controller Sub launcher()\n Dim wb As Workbook\n \n Set wb = Workbooks.Open(\"C:\\Users\\<username>\\Desktop\\Workbook1.xlsm\")\n \n Application.Run wb.Name & \"!\" & \"macro1\" 'the distant macro which you know the name\nEnd Sub\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16797867/"
] |
74,533,783
|
<p>This is my app code:</p>
<pre><code>library(shiny)
library(tidyverse)
source('module.R')
ui <- fluidPage(
tabpanel_UI("mod1")
)
server <- function(input, output, session) {
tabpanel_Server("mod1")
}
shinyApp(ui, server)
</code></pre>
<p>This is my module file: 'module.R'</p>
<pre><code>tabpanel_function <- function(x,n){
tabPanel(paste0("Panel",x),
plotOutput(paste0("chart_",n))
)
}
tabpanel_UI <- function(id) {
ns <- NS(id)
tagList(
tabsetPanel(id = ns("x"),
tabPanel("Panela"),
tabPanel("Panelb"),
tabPanel("Panelc")
)
)
}
tabpanel_Server <- function(id) {
moduleServer(
id,
function(input, output, session) {
1:4 %>% map(~ tabpanel_function(.x, n = .x) %>% appendTab("x", .))
output$chart_1 <- renderPlot({
ggplot(mtcars, aes(cyl,mpg)) + geom_line(color ='red')
})
output$chart_2 <- renderPlot({
ggplot(mtcars, aes(cyl,mpg)) + geom_line(color ='green')
})
output$chart_3 <- renderPlot({
ggplot(mtcars, aes(cyl,mpg)) + geom_line(color ='blue')
})
output$chart_4 <- renderPlot({
ggplot(mtcars, aes(cyl,mpg)) + geom_line(color ='yellow')
})
}
)
}
</code></pre>
<p>What am I missing here?</p>
<p>This is a question: <a href="https://stackoverflow.com/questions/74532454/in-r-shiny-how-to-create-others-panels-with-purrrmap">In R/Shiny how to create others panels with purrr::map</a> that I create but not considering Modules. Turns out that I will need to use modules and the charts are not been displayed. Any help?</p>
|
[
{
"answer_id": 74534673,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 3,
"selected": true,
"text": "tabpanel_function <- function(id, x, n){ \n ns <- NS(id) \n tabPanel(paste0(\"Panel\", x), \n plotOutput(ns(paste0(\"chart_\", n)))\n ) \n}\n 1:4 %>% map(~ tabpanel_function(id, .x, n = .x) %>% appendTab(\"x\", .)) \n"
},
{
"answer_id": 74534686,
"author": "thothal",
"author_id": 4125751,
"author_profile": "https://Stackoverflow.com/users/4125751",
"pm_score": 1,
"selected": false,
"text": "plotOutputs tabpanel_function <- function(x, n, ns){ \n tabPanel(paste0(\"Panel\",x), \n plotOutput(ns(paste0(\"chart_\",n)))\n ) \n}\n\n## [....]\n\n1:4 %>% map(~ tabpanel_function(.x, n = .x, session$ns) %>% appendTab(\"x\", .)) \n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20359538/"
] |
74,533,804
|
<p>I have an application which some web pages are out of the window and need to scroll right to see the full content.When I scroll right to see the full content,I find the <code>h1</code> element width is not equal to the full window size which is according to the content of <code>p</code> element.How to adjust <code>h1</code> element width automatically with CSS?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
white-space: nowrap;
font-size: 12pt;
color: #390F39;
padding: 12px 0 12px 12px;
margin: 0 0 12px -12px;
width: auto;
background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;
text-shadow: -1px -1px 1px #FFFFFF;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="h">CSS width</h1>
<p>
<strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
</p></code></pre>
</div>
</div>
</p>
<p>Note:If you test this code and it doesn't show the problem what I describe,then try w3cshool.</p>
|
[
{
"answer_id": 74533921,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "width: fit-content; body {\n width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>"
},
{
"answer_id": 74534031,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body{width:fit-content;}\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: auto;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n}\n</style>\n \n\n</head>\n<body>\n\n<h1 id=\"h\">CSS width</h1>\n\n<p><strong>Note:</strong>The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>\n\n\n</body>\n</html>"
},
{
"answer_id": 74534470,
"author": "Mr Cahyadi",
"author_id": 20570238,
"author_profile": "https://Stackoverflow.com/users/20570238",
"pm_score": 0,
"selected": false,
"text": "style <style>\n html {\n max-width: 100%;\n }\n</style>\n max-width:100%"
},
{
"answer_id": 74536224,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 2,
"selected": true,
"text": "h1 {\n /* white-space: nowrap; */\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: 100%;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p> body {\n width: fit-content;\n}\n\n.main-cont {\n min-width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <div class=\"main-cont\">\n<h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12652914/"
] |
74,533,869
|
<p>I take 20% above and below the base-case value for each of a set of parameters I have as follows:</p>
<p>`d_e</p>
<p>Minimum_d_e <- d_e - 0.20<em>d_e
Maximum_d_e <- d_e + 0.20</em>d_e`</p>
<p>Once I have the maximum and minimum values (20% either side of the base-case value) I then create a min parameter values and max parameter values vector as follows:</p>
<p><code> min = c(Minimum_HR_FP_Exp, Minimum_HR_FP_SoC, Minimum_HR_PD_SoC, Minimum_HR_PD_Exp, Minimum_P_OSD_SoC, Minimum_P_OSD_Exp, Minimum_p_FA1_STD, Minimum_p_FA2_STD, Minimum_p_FA3_STD, Minimum_p_FA1_EXPR, Minimum_p_FA2_EXPR, Minimum_p_FA3_EXPR, Minimum_administration_cost, Minimum_c_PFS_Folfox, Minimum_c_PFS_Bevacizumab, Minimum_c_OS_Folfiri, Minimum_c_AE1, Minimum_c_AE2, Minimum_c_AE3, Minimum_d_e, Minimum_d_c, Minimum_u_F, Minimum_u_P, Minimum_AE1_DisUtil, Minimum_AE2_DisUtil, Minimum_AE3_DisUtil)</code></p>
<p><code> max = c(Maximum_HR_FP_Exp, Maximum_HR_FP_SoC, Maximum_HR_PD_SoC, Maximum_HR_PD_Exp, Maximum_P_OSD_SoC, Maximum_P_OSD_Exp, Maximum_p_FA1_STD, Maximum_p_FA2_STD, Maximum_p_FA3_STD, Maximum_p_FA1_EXPR, Maximum_p_FA2_EXPR, Maximum_p_FA3_EXPR, Maximum_administration_cost, Maximum_c_PFS_Folfox, Maximum_c_PFS_Bevacizumab, Maximum_c_OS_Folfiri, Maximum_c_AE1, Maximum_c_AE2, Maximum_c_AE3, Maximum_d_e, Maximum_d_c, Maximum_u_F, Maximum_u_P, Maximum_AE1_DisUtil, Maximum_AE2_DisUtil, Maximum_AE3_DisUtil) </code>
The utility values I have above should (Maximum_AE3_DisUtil) not be any greater than 1 (100%) or lower than 0 (0%), I was going to manually replace each one as:</p>
<p>`Maximum_AE3_DisUtil<- replace(Maximum_AE3_DisUtil, Maximum_AE3_DisUtil<0, 0)</p>
<p>Maximum_AE3_DisUtil<- replace(Maximum_AE3_DisUtil, Maximum_AE3_DisUtil>1, 1)`</p>
<p>I tried the above manual approach, which does work, but is probably less efficient than it could be.</p>
|
[
{
"answer_id": 74533921,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "width: fit-content; body {\n width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>"
},
{
"answer_id": 74534031,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body{width:fit-content;}\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: auto;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n}\n</style>\n \n\n</head>\n<body>\n\n<h1 id=\"h\">CSS width</h1>\n\n<p><strong>Note:</strong>The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>\n\n\n</body>\n</html>"
},
{
"answer_id": 74534470,
"author": "Mr Cahyadi",
"author_id": 20570238,
"author_profile": "https://Stackoverflow.com/users/20570238",
"pm_score": 0,
"selected": false,
"text": "style <style>\n html {\n max-width: 100%;\n }\n</style>\n max-width:100%"
},
{
"answer_id": 74536224,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 2,
"selected": true,
"text": "h1 {\n /* white-space: nowrap; */\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: 100%;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p> body {\n width: fit-content;\n}\n\n.main-cont {\n min-width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <div class=\"main-cont\">\n<h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16978411/"
] |
74,533,905
|
<p>I have data that looks like this:</p>
<pre><code>library(dplyr)
Data <- tibble(
ID = c("Code001", "Code001","Code001","Code002","Code002","Code002","Code002","Code002","Code003","Code003","Code003","Code003"),
Value = c(107,107,107,346,346,346,346,346,123,123,123,123))
</code></pre>
<p>I need to work out the average value per group per row. However, the value needs to be rounded (so no decimal places) and the group sum needs to equal the group sum of <code>Value</code>.</p>
<p>So solutions like this won't work:</p>
<pre><code> Data %>%
add_count(ID) %>%
group_by(ID) %>%
mutate(Prop_Value_1 = Value/n,
Prop_Value_2 = round(Value/n))
</code></pre>
<p>Is there a solution that can produce an output like this:</p>
<pre><code>Data %>%
mutate(Prop_Value = c(35,36,36,69,69,69,69,70,30,31,31,31))
</code></pre>
|
[
{
"answer_id": 74533921,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "width: fit-content; body {\n width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>"
},
{
"answer_id": 74534031,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body{width:fit-content;}\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: auto;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n}\n</style>\n \n\n</head>\n<body>\n\n<h1 id=\"h\">CSS width</h1>\n\n<p><strong>Note:</strong>The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>\n\n\n</body>\n</html>"
},
{
"answer_id": 74534470,
"author": "Mr Cahyadi",
"author_id": 20570238,
"author_profile": "https://Stackoverflow.com/users/20570238",
"pm_score": 0,
"selected": false,
"text": "style <style>\n html {\n max-width: 100%;\n }\n</style>\n max-width:100%"
},
{
"answer_id": 74536224,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 2,
"selected": true,
"text": "h1 {\n /* white-space: nowrap; */\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: 100%;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p> body {\n width: fit-content;\n}\n\n.main-cont {\n min-width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <div class=\"main-cont\">\n<h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968484/"
] |
74,533,934
|
<p>Trying to detect if user input is a special character, Have Tried a couple different things but cant get the code to run correctly keeps outputting user character is a capital letter.</p>
<pre><code>let user_character = prompt("Enter either a Capital Letter, Lowercase Letter, or a Number.");
//Checks if the input character is an integer.
if(Number.isInteger(user_character)){
console.log(`You input: ${user_character} \nThat is a number.`);
}
//Checks if the input character is a capital letter.
else if(user_character === user_character.toUpperCase()){
console.log(`You input: ${user_character} \nThat is an upper case letter.`);
}
//Checks to see if the input character is a lower case letter.
else if(user_character === user_character.toLowerCase()){
console.log(`You input: ${user_character} \nThat is a lower case letter`);
}
//Checks to see if the input is a special Character
else if(user_character ===){
console.log("You input: " + user_character + ", That is a special character");
}
else{
console.log("Unfortunately: " + user_character + ", Does not match the requested input.");
}
</code></pre>
|
[
{
"answer_id": 74533921,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "width: fit-content; body {\n width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>"
},
{
"answer_id": 74534031,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body{width:fit-content;}\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: auto;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n}\n</style>\n \n\n</head>\n<body>\n\n<h1 id=\"h\">CSS width</h1>\n\n<p><strong>Note:</strong>The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>\n\n\n</body>\n</html>"
},
{
"answer_id": 74534470,
"author": "Mr Cahyadi",
"author_id": 20570238,
"author_profile": "https://Stackoverflow.com/users/20570238",
"pm_score": 0,
"selected": false,
"text": "style <style>\n html {\n max-width: 100%;\n }\n</style>\n max-width:100%"
},
{
"answer_id": 74536224,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 2,
"selected": true,
"text": "h1 {\n /* white-space: nowrap; */\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: 100%;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p> body {\n width: fit-content;\n}\n\n.main-cont {\n min-width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <div class=\"main-cont\">\n<h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20477742/"
] |
74,533,939
|
<p>Let I have the following np.array:</p>
<pre><code>>>>a=np.array([20, 10,5,10,5,10])
>>>array([20, 10, 5, 10, 5, 10])
</code></pre>
<p>Now, I want to replace 20 and 10 by 1 and 5 by 0.</p>
<p>Is there a function that can do that in one step?</p>
<p>Here is what I have tried:</p>
<pre><code>>>>a[a==10]=1
>>>a[a==10]=1
>>>a[a==5]=0
</code></pre>
<p>and I am getting my desired output, which is:</p>
<pre><code>>>>array([1, 1, 0, 1, 0, 1])
</code></pre>
<p>As you can see, I had to follow three steps in order to get my result. But I want to get my result only in one step. Is there a function that can deliver my result in one step?</p>
<p>** Edit: As suggested by Salvatore, I tried the following: **</p>
<pre><code>import pandas as pd
>>>a=np.array([[20, 5, 10, 5, 10, 7, 5]])
>>>a = pd.Series(a).replace([20,10,7,5],[1,1,1,0]).values
</code></pre>
<p>But with the above method I am getting the following error:</p>
<pre><code>ValueError: Data must be 1-dimensional
</code></pre>
|
[
{
"answer_id": 74533921,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "width: fit-content; body {\n width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>"
},
{
"answer_id": 74534031,
"author": "Tohirul Islam",
"author_id": 16414128,
"author_profile": "https://Stackoverflow.com/users/16414128",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body{width:fit-content;}\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: auto;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n}\n</style>\n \n\n</head>\n<body>\n\n<h1 id=\"h\">CSS width</h1>\n\n<p><strong>Note:</strong>The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>\n\n\n</body>\n</html>"
},
{
"answer_id": 74534470,
"author": "Mr Cahyadi",
"author_id": 20570238,
"author_profile": "https://Stackoverflow.com/users/20570238",
"pm_score": 0,
"selected": false,
"text": "style <style>\n html {\n max-width: 100%;\n }\n</style>\n max-width:100%"
},
{
"answer_id": 74536224,
"author": "Giorgi Shalamberidze",
"author_id": 20248276,
"author_profile": "https://Stackoverflow.com/users/20248276",
"pm_score": 2,
"selected": true,
"text": "h1 {\n /* white-space: nowrap; */\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n width: 100%;\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p> body {\n width: fit-content;\n}\n\n.main-cont {\n min-width: fit-content;\n}\n\nh1 {\n white-space: nowrap;\n font-size: 12pt;\n color: #390F39;\n padding: 12px 0 12px 12px;\n margin: 0 0 12px -12px;\n /*width: auto;*/\n background: rgba(0, 0, 0, 0) linear-gradient(45deg, rgb(220, 220, 220) 35%, rgba(220, 220, 220, 0.95) 100%) repeat scroll 0 0;\n text-shadow: -1px -1px 1px #FFFFFF;\n box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5);\n} <div class=\"main-cont\">\n<h1 id=\"h\">CSS width</h1>\n\n<p>\n <strong>Note:</strong> The h1 element's width is not equal to the full window size!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n</p>\n</div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20539038/"
] |
74,533,942
|
<p>So I am doing a sample exam question in preparation for my stats exam and I have hit a dead end.</p>
<p>The question is asking:</p>
<blockquote>
<p>If you roll two 6-sided fair dice until you get all possible outcomes (i.e. all sums 2-12 have occurred at least once). Estimate the expected number of dice rolls needed.</p>
</blockquote>
<p>This question needs to be answered using a simulation study in R.</p>
<p>So far I have simulated two dice being rolled and have also obtained the sum of each roll. I am unsure how to modify my code to check for expected number of rolls needed to get each sum at least once</p>
<p>My code so far:</p>
<pre class="lang-r prettyprint-override"><code>d <- data.frame(a=sample(1:6, 1000000, replace=TRUE),
b=sample(1:6, 1000000, replace=TRUE))
d$sum <- d$a + d$b
hist(d$sum)
</code></pre>
<p>Any help would be great :))</p>
|
[
{
"answer_id": 74534476,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 2,
"selected": false,
"text": "sample(6, 10, TRUE)\n replicate replicate(2, sample(6, 10, TRUE))\n#> [,1] [,2]\n#> [1,] 1 1\n#> [2,] 4 5\n#> [3,] 1 5\n#> [4,] 2 2\n#> [5,] 5 6\n#> [6,] 3 6\n#> [7,] 6 2\n#> [8,] 2 1\n#> [9,] 3 5\n#> [10,] 3 5\n rowSums rowSums(replicate(2, sample(6, 10, TRUE)))\n#> [1] 2 9 6 4 11 9 8 3 8 8\n throws throws <- rowSums(replicate(2, sample(6, 1000, TRUE)))\n throws length(unique(throws))\n#> [1] 11\n length(unique(throws[1:11]))\n#> [1] 10\n length(unique(throws[1:100]))\n#> [1] 11\n for(i in 11:100)\n {\n if(length(unique(throws[1:i])) == 11) break;\n }\n\ni\n#> [1] 23\n i sim <- function() {\n throws <- rowSums(replicate(2, sample(6, 1000, TRUE)))\n for(i in 11:1000)\n {\n if(length(unique(throws[1:i])) == 11) break;\n }\n return(i)\n}\n sim()\n#> [1] 29\nsim()\n#> [1] 94\nsim()\n#> [1] 62\n sim replicate vec <- replicate(1000, sim())\n mean(vec)\n#> [1] 59.821\n median(vec)\n#> [1] 51\n hist(vec)\n plot(density(vec))\n"
},
{
"answer_id": 74553235,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 2,
"selected": false,
"text": "sim() function roll:\n return an int in the range [1, 6] sampled with the uniform distribution\n\nfunction sim:\n let s = an empty set\n let i = 0\n while size(s) < 11, do:\n let n = roll() + roll()\n add n to s\n i += 1\n return i\n s roll <- function() sample(6, 1)\n\nsim <- function() {\n s <- numeric()\n i <- 0\n while(length(s) < 11) {\n n <- roll() + roll()\n if(!n %in% s) s <- c(s, n)\n i <- i + 1\n }\n return(i)\n}\n\nn_sims <- function(n) sapply(seq(n), function(x) sim())\n n_sims(10)\n#> [1] 55 54 31 45 51 118 61 44 63 29\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573120/"
] |
74,533,944
|
<p>There is <a href="https://capitalizemytitle.com/zufallswort-generator/" rel="nofollow noreferrer">the page</a> where a random word generated. That word is in <code>span</code> element which seems to be inserted by JavaScript. I wasn't able to find a link that provides the word from the server.
So I'm questioning what algorithm should I follow (how a front-end professional would do it) to find the link.</p>
<p>I tried to look at the button, the text, to observe click methods etc, but wasn't able to find it.</p>
|
[
{
"answer_id": 74534476,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 2,
"selected": false,
"text": "sample(6, 10, TRUE)\n replicate replicate(2, sample(6, 10, TRUE))\n#> [,1] [,2]\n#> [1,] 1 1\n#> [2,] 4 5\n#> [3,] 1 5\n#> [4,] 2 2\n#> [5,] 5 6\n#> [6,] 3 6\n#> [7,] 6 2\n#> [8,] 2 1\n#> [9,] 3 5\n#> [10,] 3 5\n rowSums rowSums(replicate(2, sample(6, 10, TRUE)))\n#> [1] 2 9 6 4 11 9 8 3 8 8\n throws throws <- rowSums(replicate(2, sample(6, 1000, TRUE)))\n throws length(unique(throws))\n#> [1] 11\n length(unique(throws[1:11]))\n#> [1] 10\n length(unique(throws[1:100]))\n#> [1] 11\n for(i in 11:100)\n {\n if(length(unique(throws[1:i])) == 11) break;\n }\n\ni\n#> [1] 23\n i sim <- function() {\n throws <- rowSums(replicate(2, sample(6, 1000, TRUE)))\n for(i in 11:1000)\n {\n if(length(unique(throws[1:i])) == 11) break;\n }\n return(i)\n}\n sim()\n#> [1] 29\nsim()\n#> [1] 94\nsim()\n#> [1] 62\n sim replicate vec <- replicate(1000, sim())\n mean(vec)\n#> [1] 59.821\n median(vec)\n#> [1] 51\n hist(vec)\n plot(density(vec))\n"
},
{
"answer_id": 74553235,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 2,
"selected": false,
"text": "sim() function roll:\n return an int in the range [1, 6] sampled with the uniform distribution\n\nfunction sim:\n let s = an empty set\n let i = 0\n while size(s) < 11, do:\n let n = roll() + roll()\n add n to s\n i += 1\n return i\n s roll <- function() sample(6, 1)\n\nsim <- function() {\n s <- numeric()\n i <- 0\n while(length(s) < 11) {\n n <- roll() + roll()\n if(!n %in% s) s <- c(s, n)\n i <- i + 1\n }\n return(i)\n}\n\nn_sims <- function(n) sapply(seq(n), function(x) sim())\n n_sims(10)\n#> [1] 55 54 31 45 51 118 61 44 63 29\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19195923/"
] |
74,533,945
|
<p>I'm new to python and trying to make a calculator. The actual calculator part works but I can't figure out how to make it so that when the user puts in something that is not "+, -, *, or /" it prints a sentence then closes.</p>
<p>This is my code and the output</p>
<p>(<a href="https://i.stack.imgur.com/EYzxg.png" rel="nofollow noreferrer">https://i.stack.imgur.com/EYzxg.png</a>)</p>
|
[
{
"answer_id": 74534476,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 2,
"selected": false,
"text": "sample(6, 10, TRUE)\n replicate replicate(2, sample(6, 10, TRUE))\n#> [,1] [,2]\n#> [1,] 1 1\n#> [2,] 4 5\n#> [3,] 1 5\n#> [4,] 2 2\n#> [5,] 5 6\n#> [6,] 3 6\n#> [7,] 6 2\n#> [8,] 2 1\n#> [9,] 3 5\n#> [10,] 3 5\n rowSums rowSums(replicate(2, sample(6, 10, TRUE)))\n#> [1] 2 9 6 4 11 9 8 3 8 8\n throws throws <- rowSums(replicate(2, sample(6, 1000, TRUE)))\n throws length(unique(throws))\n#> [1] 11\n length(unique(throws[1:11]))\n#> [1] 10\n length(unique(throws[1:100]))\n#> [1] 11\n for(i in 11:100)\n {\n if(length(unique(throws[1:i])) == 11) break;\n }\n\ni\n#> [1] 23\n i sim <- function() {\n throws <- rowSums(replicate(2, sample(6, 1000, TRUE)))\n for(i in 11:1000)\n {\n if(length(unique(throws[1:i])) == 11) break;\n }\n return(i)\n}\n sim()\n#> [1] 29\nsim()\n#> [1] 94\nsim()\n#> [1] 62\n sim replicate vec <- replicate(1000, sim())\n mean(vec)\n#> [1] 59.821\n median(vec)\n#> [1] 51\n hist(vec)\n plot(density(vec))\n"
},
{
"answer_id": 74553235,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 2,
"selected": false,
"text": "sim() function roll:\n return an int in the range [1, 6] sampled with the uniform distribution\n\nfunction sim:\n let s = an empty set\n let i = 0\n while size(s) < 11, do:\n let n = roll() + roll()\n add n to s\n i += 1\n return i\n s roll <- function() sample(6, 1)\n\nsim <- function() {\n s <- numeric()\n i <- 0\n while(length(s) < 11) {\n n <- roll() + roll()\n if(!n %in% s) s <- c(s, n)\n i <- i + 1\n }\n return(i)\n}\n\nn_sims <- function(n) sapply(seq(n), function(x) sim())\n n_sims(10)\n#> [1] 55 54 31 45 51 118 61 44 63 29\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470296/"
] |
74,533,977
|
<p>I am trying to give a service principal SELECT access on my Azure Synapse SQL data.</p>
<pre><code>CREATE USER [MY_SERVICE_PRINCIPAL] FROM EXTERNAL PROVIDER WITH DEFAFULT_SCHEMA=[dbo]
GO
GRANT SELECT ON DATABASE :: MyDB TO [MY_SERVICE_PRINCIPAL];
</code></pre>
<p>This works fine, but it requires me logging into the workspace to do this for every single new service principal. Is it possible to automate this? I automate the creation of the service principal via Azure CLI. Is it possible to run this script from a</p>
|
[
{
"answer_id": 74569646,
"author": "tanikellav",
"author_id": 20000817,
"author_profile": "https://Stackoverflow.com/users/20000817",
"pm_score": 1,
"selected": false,
"text": "[CmdletBinding()]\n\nparam (\n\n [Parameter(Mandatory=$true)]\n\n [string]$ResourceGroupName =\"rg_ResourceGroup\",\n\n [Parameter(Mandatory=$true)]\n\n [string]$WorkspaceName = \"wp_WorkSpaceName\",\n\n [Parameter(Mandatory=$true)]\n\n [string]$Operation = \"op_Pause\"\n\n)\n\nBegin {\n\nWrite-Output \"Connecting on $(Get-Date)\"\n\n#Connect to Azure using the Run As Account\n\nTry{\n\n$servicePrincipalConnection=Get-AutomationConnection -Name \"AzureRunAsConnection\"\n\nConnect-AzAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint\n\n}\n\nCatch {\n\nif (!$servicePrincipalConnection){\n\n$ErrorMessage = \"Connection $connectionName not found.\"\n\nthrow $ErrorMessage\n\n} else{\n\nWrite-Output -Message $_.Exception\n\nthrow $_.Exception\n\n}\n\n}\n\n# Validation parameters\n\n$ArrayOperations = \"Pause\",\"Start\",\"Restart\"\n\nIf ($Operation -notin $ArrayOperations)\n\n{\n\nThrow \"Only Pause, Start, Restart Operations are valid\"\n\n}\n\n# Start\n\nWrite-Output \"Starting process on $(Get-Date)\"\n\nTry{\n\n$Status = Get-AzSynapseSqlPool –ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Select-Object Status | Format-Table -HideTableHeaders | Out-String\n\n$Status = $Status -replace \"`t|`n|`r\",\"\"\n\nWrite-Output \"The current status is \"$Status.trim()\" on $(Get-Date)\"\n\n}\n\nCatch {\n\nWrite-Output $_.Exception\n\nthrow $_.Exception\n\n}\n\n# Start block\n\n# Start\n\nWrite-Output \"Starting $Operation on $(Get-Date)\"\n\nif(($Operation -eq \"Start\") -and ($Status.trim() -ne \"Online\")){\n\nWrite-Output \"Starting $Operation Operation\"\n\ntry\n\n{\n\nWrite-Output \"Starting on $(Get-Date)\"\n\nGet-AzSynapseSqlPool –ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Resume-AzSynapseSqlPool\n\n}\n\ncatch\n\n{\n\nWrite-Output \"Error while executing \"$Operation\n\n}\n\n}\n\n# Pause block\n\nif(($Operation -eq \"Pause\") -and ($Status.trim() -ne \"Paused\")){\n\nwrite-Output \"Starting $Operation Operation\"\n\ntry\n\n{\n\nWrite-Output \"Pausing on $(Get-Date)\"\n\nGet-AzSynapseSqlPool –ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Suspend-AzSynapseSqlPool\n\n}\n\ncatch\n\n{\n\nWrite-Output \"Error while executing \"$Operation\n\n}\n\n}\n\n# Restart block\n\nif(($Operation -eq \"Restart\") -and ($Status.trim() -eq \"Online\")){\n\nWrite-Output \"Starting $Operation Operation\"\n\ntry\n\n{\n\nWrite-Output \"Pausing on $(Get-Date)\"\n\nGet-AzSynapseSqlPool –ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Suspend-AzSynapseSqlPool\n\nWrite-Output \"Starting on $(Get-Date)\"\n\nGet-AzSynapseSqlPool –ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Resume-AzSynapseSqlPool\n\n}\n\ncatch\n\n{\n\nWrite-Output \"Error while executing \"$Operation\n\n}\n\n }\n\n}\n\nEnd\n\n{\n\n# Exit\n\nWrite-Output \"Finished process on $(Get-Date)\"\n\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74533977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6241997/"
] |
74,534,000
|
<p>I am trying to figure out how to define a Variable which is a member of a class in C++, Outside of the normal class body. It may be inside of a Function, or outside of the class. Is this possible. What I need is that the variable should be a member of the class such that if I call Nodesecond.birthdate, it returns the birthdate.
I am attempting to understand the language, there is no real-world application involved.</p>
<p>This was my attempt at doing it:</p>
<pre><code>#include <iostream>
using namespace std;
struct Nodesecond {
public:
int Age;
string Name;
// I dont want to define Birthdate here. It should be somewhere else.
Nodesecond() {
this->Age = 5;
this->Name = "baby";
this->birthdate = "01.01.2020";
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
Nodesecond mynode;
cout << mynode.Age << endl << mynode.Name << mynode.Birthdate;
return 0;
}
</code></pre>
|
[
{
"answer_id": 74534176,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 3,
"selected": true,
"text": "#include <iostream>\n#include <unordered_map>\nusing namespace std;\n\nstruct Nodesecond {\npublic:\n int Age;\n string Name;\n unordered_map<string, string> Fields;\n string& operator[](const string& name) {return Fields[name];}\n Nodesecond() {\n this->Age = 5;\n this->Name = \"baby\";\n *(this)[\"Birthdate\"] = \"01.01.2020\";\n }\n};\n\nint main() {\n std::cout << \"Hello, World!\" << std::endl;\n Nodesecond mynode;\n cout << mynode.Age << endl << mynode.Name << mynode[\"Birthdate\"];\n return 0;\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17895488/"
] |
74,534,018
|
<p>I am trying to migrate an existing command-line app to Spring boot and i have a weird problem.</p>
<p>The app works, but it seems to be very slow when started with
<code>mvn spring-boot:run</code></p>
<p>It is not the app startup that is slow. There is a method which should fetch around 1.8 Mio records from the DB and create POJO's from result set.
Normally this takes up to 40 sec.</p>
<p>With app started with maven it takes > 5 minutes.</p>
<p>If i start it with <code>java -jar app.jar</code> it works fine/fast.
App is also fast when started in IntelliJ.</p>
<p>I am guessing it may be something with the classpath, but it is just a guess.</p>
<p>All i did in the app is to migrate some Singelton classes to @Components and add
spring-boot-maven-plugin</p>
<p>Any ideas ?</p>
|
[
{
"answer_id": 74535609,
"author": "Georgi",
"author_id": 219191,
"author_profile": "https://Stackoverflow.com/users/219191",
"pm_score": 1,
"selected": false,
"text": "<plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n <configuration>\n <optimizedLaunch>false</optimizedLaunch>\n </configuration>\n</plugin>\n -XX:TieredStopAtLevel=1 /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/bin/java -XX:TieredStopAtLevel=1 -cp A_LOT_OF_DEPS_HERE com.myapp.SpringApp\n -XX:TieredStopAtLevel=1 /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/bin/java -cp A_LOT_OF_DEPS_HERE com.myapp.SpringApp\n spring-boot:run java(17) -jar my-app.jar"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219191/"
] |
74,534,026
|
<p>This is my keylogger code:</p>
<pre><code>import pynput
from pynput.keyboard import Key, Listener
from datetime import datetime, timedelta, time
import time
start = time.time()
now=datetime.now()
dt=now.strftime('%d%m%Y-%H%M%S')
keys=[]
def on_press(key):
keys.append(key)
write_file(keys)
try:
print(key.char)
except AttributeError:
print(key)
def write_file(keys):
with open ('log-'+str(dt)+'.txt','w') as f:
for key in keys:
# end=time.time()
# tot_time=end-start
k=str(key).replace("'","")
f.write(k.replace("Key.space", ' ').replace("Key.enter", '\n'))
# if tot_time>5.0:
# f.close()
# else:
# continue
with Listener(on_press=on_press) as listener:
listener.join()
</code></pre>
<p>In write_file() function, I've used the close method and also the timer which should automatically save the file after 5 seconds, but that gives me a long 1 paged error whose last line says:</p>
<pre><code>ValueError: I/O operation on closed file.
</code></pre>
<p>How do I make my program save the txt file after every 5 seconds and create a new txt file automatically?</p>
<p>NOTE: I actually want the log file to be generated automatically after every 4 hours so that it is not flooded with uncountable words. I've just taken 5 seconds as an example.</p>
|
[
{
"answer_id": 74537137,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "import pynput\nfrom pynput.keyboard import Key, Listener\nfrom datetime import datetime, timedelta, time\nimport time\n\nstart = time.time()\n\nnow=datetime.now()\ndt=now.strftime('%d%m%Y-%H%M%S')\nkeys=[]\n\ndef on_press(key):\n keys.append(key)\n write_file(keys)\n try:\n print(key.char)\n except AttributeError:\n print(key)\n\ndef write_file(keys, f=None):\n global start\n for key in keys:\n k=str(key).replace(\"'\",\"\").replace(\"Key.space\", ' ').replace(\"Key.enter\", '\\n')\n\n if not f:\n f = open( 'log-'+str(dt)+'.txt', 'w') # open (or reopen)\n f.write( k)\n\n end=time.time()\n tot_time=end-start\n if tot_time>5.0:\n f.close()\n f = None\n start=end\n else:\n continue\n keys = []\n\nwith Listener(on_press=on_press) as listener:\n listener.join()\n"
},
{
"answer_id": 74603706,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "schedule = [ '08:00:00', '12:00:00', '16:00:00', '20:00:00'] # schedule for close/open file (must ascend)\n\nimport pynput\nfrom pynput.keyboard import Listener\n\ndef on_press(key):\n txt = key.char if hasattr( key, 'char') else ( '<'+key._name_+'>')\n \n # do some conversions and concatenate to line\n if txt == '<space>': txt = ' '\n if txt == None: txt = '<?key?>' # some keyboards may generate unknown codes for Multimedia\n glo.line += txt\n\n if (len(glo.line) > 50) or (txt=='<enter>'):\n writeFile( glo.fh, glo.line+'\\n')\n glo.line = ''\n \ndef writeFile( fh, txt):\n fh.write( txt)\n\ndef openFile():\n from datetime import datetime\n dt=datetime.now().strftime('%d%m%Y-%H%M%S')\n fh = open( 'log-'+str(dt)+'.txt', 'w') # open (or reopen)\n return fh\n\ndef closeFile( fh):\n fh.close()\n\ndef closeAndReOpen( fh, line):\n if len( line) > 0:\n writeFile( fh, line+'\\n')\n closeFile( fh)\n fh = openFile()\n return fh\n \nclass Ticker():\n def __init__( self, sched=None, func=None, parm=None):\n # 2 modes: if func is supplied, tick() will not return. Everything will be internal.\n # if func is not supplied, it's non-blocking. The callback and sleep must be external.\n self.target = None\n self.sched = sched\n self.func = func\n self.parm = parm\n \n def selectTarget( self):\n for tim in self.sched: # select next target time (they are in ascending order)\n if tim > self.actual:\n self.target = tim\n break\n else: self.target = self.sched[0]\n self.today = (self.actual < self.target) # True if target is today.\n\n def tick( self):\n from datetime import datetime\n while True:\n self.actual = datetime.now().strftime( \"%H:%M:%S\")\n if not self.target: self.selectTarget()\n if self.actual < self.target: self.today = True\n act = (self.actual >= self.target) and self.today # True if target reached\n if act: self.target = '' # next tick will select a new target\n if not self.func: break # Non-blocking mode: upper level will sleep and call func\n # The following statements are only executed in blocking mode\n if act: self.func( self.parm)\n time.sleep(1)\n \n return act # will return only if func is not defined\n \nclass Glo:\n pass\n\nglo = Glo()\nglo.fh = None\nglo.line = ''\nglo.fini = False\n\nglo.fh = openFile()\nlistener = Listener( on_press=on_press)\nlistener.start()\nticker = Ticker( sched=schedule) # start ticker in non-blocking mode.\n\nwhile not glo.fini:\n import time\n time.sleep(1)\n if ticker.tick():\n # time to close and reopen\n glo.fh = closeAndReOpen( glo.fh, glo.line)\n glo.line = ''\n\nlistener.stop()\nwriteFile( glo.fh, glo.line+'\\n')\ncloseFile( glo.fh)\nexit()\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12978231/"
] |
74,534,076
|
<p>I wanted to find out if it is significantly slower to iterate over the first two dimensions of an array in comparison to doing the operations columnwise. To my surprise if found out that its actually faster to do the operations elementwise. Can someone explain?</p>
<p>Here is the code:</p>
<pre><code>def row_by_row(arr, cop):
for i in range(arr.shape[0]):
for ii in range(arr.shape[1]):
arr[i, ii] = cop[i, ii].copy()
return arr
def all(arr, cop):
for i in range(arr.shape[1]):
arr[:,i] = cop[:, i].copy()
return arr
print(timeit.timeit("row_by_row(arr, cop)", setup="arr=np.ones((26, 15, 5000)); cop = np.random.random((26, 15,5000))",number=50, globals=globals()))
print(timeit.timeit("all(arr, cop)",setup="arr=np.ones((26, 15, 5000)); cop=np.random.random((26, 15,5000))", number=50, globals=globals()))
</code></pre>
<p>this was the time:</p>
<pre><code>0.12496590000000007
0.4989047
</code></pre>
|
[
{
"answer_id": 74537137,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "import pynput\nfrom pynput.keyboard import Key, Listener\nfrom datetime import datetime, timedelta, time\nimport time\n\nstart = time.time()\n\nnow=datetime.now()\ndt=now.strftime('%d%m%Y-%H%M%S')\nkeys=[]\n\ndef on_press(key):\n keys.append(key)\n write_file(keys)\n try:\n print(key.char)\n except AttributeError:\n print(key)\n\ndef write_file(keys, f=None):\n global start\n for key in keys:\n k=str(key).replace(\"'\",\"\").replace(\"Key.space\", ' ').replace(\"Key.enter\", '\\n')\n\n if not f:\n f = open( 'log-'+str(dt)+'.txt', 'w') # open (or reopen)\n f.write( k)\n\n end=time.time()\n tot_time=end-start\n if tot_time>5.0:\n f.close()\n f = None\n start=end\n else:\n continue\n keys = []\n\nwith Listener(on_press=on_press) as listener:\n listener.join()\n"
},
{
"answer_id": 74603706,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "schedule = [ '08:00:00', '12:00:00', '16:00:00', '20:00:00'] # schedule for close/open file (must ascend)\n\nimport pynput\nfrom pynput.keyboard import Listener\n\ndef on_press(key):\n txt = key.char if hasattr( key, 'char') else ( '<'+key._name_+'>')\n \n # do some conversions and concatenate to line\n if txt == '<space>': txt = ' '\n if txt == None: txt = '<?key?>' # some keyboards may generate unknown codes for Multimedia\n glo.line += txt\n\n if (len(glo.line) > 50) or (txt=='<enter>'):\n writeFile( glo.fh, glo.line+'\\n')\n glo.line = ''\n \ndef writeFile( fh, txt):\n fh.write( txt)\n\ndef openFile():\n from datetime import datetime\n dt=datetime.now().strftime('%d%m%Y-%H%M%S')\n fh = open( 'log-'+str(dt)+'.txt', 'w') # open (or reopen)\n return fh\n\ndef closeFile( fh):\n fh.close()\n\ndef closeAndReOpen( fh, line):\n if len( line) > 0:\n writeFile( fh, line+'\\n')\n closeFile( fh)\n fh = openFile()\n return fh\n \nclass Ticker():\n def __init__( self, sched=None, func=None, parm=None):\n # 2 modes: if func is supplied, tick() will not return. Everything will be internal.\n # if func is not supplied, it's non-blocking. The callback and sleep must be external.\n self.target = None\n self.sched = sched\n self.func = func\n self.parm = parm\n \n def selectTarget( self):\n for tim in self.sched: # select next target time (they are in ascending order)\n if tim > self.actual:\n self.target = tim\n break\n else: self.target = self.sched[0]\n self.today = (self.actual < self.target) # True if target is today.\n\n def tick( self):\n from datetime import datetime\n while True:\n self.actual = datetime.now().strftime( \"%H:%M:%S\")\n if not self.target: self.selectTarget()\n if self.actual < self.target: self.today = True\n act = (self.actual >= self.target) and self.today # True if target reached\n if act: self.target = '' # next tick will select a new target\n if not self.func: break # Non-blocking mode: upper level will sleep and call func\n # The following statements are only executed in blocking mode\n if act: self.func( self.parm)\n time.sleep(1)\n \n return act # will return only if func is not defined\n \nclass Glo:\n pass\n\nglo = Glo()\nglo.fh = None\nglo.line = ''\nglo.fini = False\n\nglo.fh = openFile()\nlistener = Listener( on_press=on_press)\nlistener.start()\nticker = Ticker( sched=schedule) # start ticker in non-blocking mode.\n\nwhile not glo.fini:\n import time\n time.sleep(1)\n if ticker.tick():\n # time to close and reopen\n glo.fh = closeAndReOpen( glo.fh, glo.line)\n glo.line = ''\n\nlistener.stop()\nwriteFile( glo.fh, glo.line+'\\n')\ncloseFile( glo.fh)\nexit()\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14327827/"
] |
74,534,091
|
<p>I need to make a call when I click on the button, or open mail in order to send a message, we usually use the a tag with the necessary <code>mail:</code> or <code>tel:</code> attributes for these purposes, but is it possible to do this using <code>Linking.openURL</code> like this?</p>
<pre><code>onPress={() => Linking.openURL('+380775454545455')
</code></pre>
<p>If it possible, what should we add in order to do it?</p>
|
[
{
"answer_id": 74534172,
"author": "P-A",
"author_id": 9720524,
"author_profile": "https://Stackoverflow.com/users/9720524",
"pm_score": 3,
"selected": true,
"text": "const subject = \"Mail Subject\";\nconst message = \"Message Body\";\nLinking.openURL(`mailto:support@domain.com?subject=${subject}&body=${message}`)\n const phone = \"+380775454545455\";\nLinking.openURL(`tel:${phone}`)\n"
},
{
"answer_id": 74535289,
"author": "Luís Mestre",
"author_id": 7850543,
"author_profile": "https://Stackoverflow.com/users/7850543",
"pm_score": 1,
"selected": false,
"text": "const phoneNumber = \"+123456789\";\nLinking.openURL(`tel:${phoneNumber}`);\n const email = \"support@expo.io\";\n\n// if you want to just open the mail app\nLinking.openURL(`mailto:${email}`);\n\n// if you want to open the mail app with subject and body\nconst subject = \"Subject\";\nconst body = \"Body\";\n\nLinking.openURL(`mailto:${email}?subject=${subject}&body=${body}`);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15464003/"
] |
74,534,092
|
<p>I have a myJson.json that look like this:</p>
<pre><code>{
"FirewallGroupsToEnable": [
"Remote Event Log Management",
"Windows Remote Management",
"Performance Logs and Alerts",
"File and Printer Sharing",
"Windows Management Instrumentation (WMI)"
],
"MemoryStartupBytes": "3GB"
}
</code></pre>
<p>I'd like to serialize it as a string and then set it as a variable to be used by other tasks. If there is a better way to use this file inside a pipeline please let me know.</p>
<p>I'm serializing it and setting it like this:</p>
<pre><code> - task: PowerShell@2
inputs:
targetType: 'inline'
script: |
$Configs= Get-Content -Path $(Build.SourcesDirectory)\sources\myJson.json -Raw | ConvertFrom-Json
Write-Host "##vso[task.setvariable variable=Configs]$Configs"
</code></pre>
<p>In the following task, I am running a PowerShell script.</p>
<pre><code> - task: PowerShell@2
displayName: 'myTask'
inputs:
targetType: 'filePath'
filePath: 'sources\myScript.ps1'
pwsh: true
</code></pre>
<p>I'm using the variable in my script like this:</p>
<pre><code>$env:Configs
[Configs]$envConfigs = ConvertFrom-Json -InputObject $env:Configs -ErrorAction Stop
</code></pre>
<p>The Configs is a class that is being imported at the top of the script like so <code>Using module .\Configs.psm1</code>. I know it's being read because if it wasn't the error would be about a missing type.</p>
<p>Configs.psm1</p>
<pre><code>class Configs
{
[string[]]$FirewallGroupsToEnable
[string]$MemoryStartupBytes
}
</code></pre>
<p>This is what I get in the pipeline.</p>
<pre><code>##[debug]Processed: ##vso[task.setvariable variable=Configs]@{FirewallGroupsToEnable=System.Object[]; MemoryStartupBytes=3GB}
@{FirewallGroupsToEnable=System.Object[]; MemoryStartupBytes=3GB}
Cannot convert the "@{FirewallGroupsToEnable=System.Object[]; MemoryStartupBytes=3GB}" value of type "System.String" to type "Configs".
</code></pre>
<p>I've always casted a deserialized JSON into custom types like this and it always worked. But right now there is something wrong!</p>
<p>I tried to remove <code>ConvertFrom-Json</code> while serializing the JSON (before setting it as a variable) but it doesn't serialize it right. It shows like this in the pipeline:</p>
<p><a href="https://i.stack.imgur.com/L1Hn5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L1Hn5.png" alt="enter image description here" /></a></p>
<p>It looks like it's only getting the first curly braces!</p>
<p>So, how do I serialize a JSON regardless of its depth into the pipeline to be used in later tasks <strong>inside a script file</strong>?</p>
|
[
{
"answer_id": 74543675,
"author": "Suki Ji-MSFT",
"author_id": 18349158,
"author_profile": "https://Stackoverflow.com/users/18349158",
"pm_score": 1,
"selected": false,
"text": "- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n $Configs= Get-Content -Path $(Build.SourcesDirectory)\\wit.json\n $Configs | Out-File Test.json\n\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n $Input = Get-Content Test.json\n Write-Host $Input\n"
},
{
"answer_id": 74595891,
"author": "jsnoobie",
"author_id": 17460932,
"author_profile": "https://Stackoverflow.com/users/17460932",
"pm_score": 1,
"selected": true,
"text": "$Configs= Get-Content -Path $(Build.SourcesDirectory)\\sources\\myJson.json -Raw | ConvertFrom-Json | ConvertTo-Json -Compress"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17460932/"
] |
74,534,094
|
<p>Im trying to change a string in a list called <code>lista</code> composed by n times <code>|_|</code>, in a function I'm trying to change one specific place of the list with "X" but nothing is working</p>
<pre><code>lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]
</code></pre>
<p>i want to change only the middle one to <code>|X|</code></p>
<p>I already tried different methods like, the command replace or pop and then insert a new value but nothing as changed and always gives me an error</p>
|
[
{
"answer_id": 74543675,
"author": "Suki Ji-MSFT",
"author_id": 18349158,
"author_profile": "https://Stackoverflow.com/users/18349158",
"pm_score": 1,
"selected": false,
"text": "- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n $Configs= Get-Content -Path $(Build.SourcesDirectory)\\wit.json\n $Configs | Out-File Test.json\n\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n $Input = Get-Content Test.json\n Write-Host $Input\n"
},
{
"answer_id": 74595891,
"author": "jsnoobie",
"author_id": 17460932,
"author_profile": "https://Stackoverflow.com/users/17460932",
"pm_score": 1,
"selected": true,
"text": "$Configs= Get-Content -Path $(Build.SourcesDirectory)\\sources\\myJson.json -Raw | ConvertFrom-Json | ConvertTo-Json -Compress"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20235048/"
] |
74,534,137
|
<p>I just finished creating a NextJs project and i ran <code>npm run dev</code> to start the project; but instead the terminal displays <a href="https://i.stack.imgur.com/VTgSc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VTgSc.png" alt="enter image description here" /></a>
I'm currently not sure what is causing this. Please i need help</p>
|
[
{
"answer_id": 74543675,
"author": "Suki Ji-MSFT",
"author_id": 18349158,
"author_profile": "https://Stackoverflow.com/users/18349158",
"pm_score": 1,
"selected": false,
"text": "- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n $Configs= Get-Content -Path $(Build.SourcesDirectory)\\wit.json\n $Configs | Out-File Test.json\n\n- task: PowerShell@2\n inputs:\n targetType: 'inline'\n script: |\n $Input = Get-Content Test.json\n Write-Host $Input\n"
},
{
"answer_id": 74595891,
"author": "jsnoobie",
"author_id": 17460932,
"author_profile": "https://Stackoverflow.com/users/17460932",
"pm_score": 1,
"selected": true,
"text": "$Configs= Get-Content -Path $(Build.SourcesDirectory)\\sources\\myJson.json -Raw | ConvertFrom-Json | ConvertTo-Json -Compress"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8384358/"
] |
74,534,165
|
<p>I'm really new to Haskell so your help would be much appreciated!</p>
<p>As a small training task I created this function in Haskell and tried to run it:</p>
<pre><code>data S = S NP VP
data N = Linguist | Chemist | Anglist | N ADJ N
data NP = NP DET N
data ADJ = Curious | Smart
data DET = The | Some | Every
data VP = Snores | Dreams | V NP
data V = Cites | Corrects
np :: NP
np = NP Every (N Smart (N Curious Linguist))
</code></pre>
<p>When calling it, I get this error:</p>
<pre><code>*Main> np
<interactive>:58:1: error:
• No instance for (Show NP) arising from a use of ‘print’
• In a stmt of an interactive GHCi command: print it
</code></pre>
<p>I expected this output: NP Every (N Smart (N Curious Linguist))</p>
<p>Has anyone an idea what to do and why? I just copied the code from a powerpoint presentation where it was used as an example and did everything exactly as mentioned on the slide.
Thank you very much for your help!</p>
|
[
{
"answer_id": 74534365,
"author": "Li-yao Xia",
"author_id": 6863749,
"author_profile": "https://Stackoverflow.com/users/6863749",
"pm_score": 2,
"selected": false,
"text": "data S = S NP VP deriving Show\ndata N = Linguist | Chemist | Anglist | N ADJ N deriving Show\ndata NP = NP DET N deriving Show\ndata ADJ = Curious | Smart deriving Show\ndata DET = The | Some | Every deriving Show\ndata VP = Snores | Dreams | V NP deriving Show\ndata V = Cites | Corrects deriving Show\n"
},
{
"answer_id": 74534369,
"author": "leftaroundabout",
"author_id": 745903,
"author_profile": "https://Stackoverflow.com/users/745903",
"pm_score": 3,
"selected": true,
"text": "Map show print Map Map Map Show instance Show NP where\n show (NP d n) = \"NP (\"++show d++\") (\"++show n++\")\" -- not recommended\n show data S = S NP VP deriving (Show)\n...\ndata NP = NP DET N deriving (Show)\n...\n Eq Read data S = S NP VP deriving (Eq, Show, Read)\n...\ndata NP = NP DET N deriving (Eq, Show, Read)\n...\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573133/"
] |
74,534,186
|
<p>I am learning Docker. I have practiced a lot, including testing commands from the official Postgres page on dockerhub.</p>
<p>I ran this command:</p>
<pre><code>docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres
</code></pre>
<p>Could someone give a complete and concrete example to make this command work (i mean with a real existing container). I can't see how it could work.</p>
|
[
{
"answer_id": 74534365,
"author": "Li-yao Xia",
"author_id": 6863749,
"author_profile": "https://Stackoverflow.com/users/6863749",
"pm_score": 2,
"selected": false,
"text": "data S = S NP VP deriving Show\ndata N = Linguist | Chemist | Anglist | N ADJ N deriving Show\ndata NP = NP DET N deriving Show\ndata ADJ = Curious | Smart deriving Show\ndata DET = The | Some | Every deriving Show\ndata VP = Snores | Dreams | V NP deriving Show\ndata V = Cites | Corrects deriving Show\n"
},
{
"answer_id": 74534369,
"author": "leftaroundabout",
"author_id": 745903,
"author_profile": "https://Stackoverflow.com/users/745903",
"pm_score": 3,
"selected": true,
"text": "Map show print Map Map Map Show instance Show NP where\n show (NP d n) = \"NP (\"++show d++\") (\"++show n++\")\" -- not recommended\n show data S = S NP VP deriving (Show)\n...\ndata NP = NP DET N deriving (Show)\n...\n Eq Read data S = S NP VP deriving (Eq, Show, Read)\n...\ndata NP = NP DET N deriving (Eq, Show, Read)\n...\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74534186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18786837/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.