qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,544,192
|
<p>How to get Starting alphabet from the string which contain numbers and other strings ?</p>
<p>Like have to separate the alphabets before the numbers starts.</p>
<pre><code>String value1 = "test123123hj";
String value2 = "demo312342343dfs";
</code></pre>
<p>Output should be :</p>
<pre><code>value1 = "test"
value2 ="demo"
</code></pre>
|
[
{
"answer_id": 74590743,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": -1,
"selected": false,
"text": " Ensure that the service principal has all the permissions. The only thing that worked for me though is adding the service principal 24681998-555f-4570-a559-2fced2d7e841 which shows up as Microsoft.Azure.WebSites. You can add this through the portal, by adding an access policy for Microsoft.Azure.WebSites or through arm with the GUID."
},
{
"answer_id": 74654463,
"author": "Jahnavi",
"author_id": 19785512,
"author_profile": "https://Stackoverflow.com/users/19785512",
"pm_score": 0,
"selected": false,
"text": "keyvault -> secrets key vault Access Policies ssl certificate key,secret & certificate management AzureAD -> App registrations App Service -> Web Application -> Certificates keyvault -> secrets .pfx resource certEncryption 'Microsoft.Web/certificates@2018-02-01' = {\nname: 'xcc-cert-encryption'\nlocation: 'EastUS'\nproperties: {\nkeyVaultId: '/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.KeyVault/vaults/xxxxxkeyvaults'\nkeyVaultSecretName: 'jahnss'\npassword: 'xxxxx' //Certificate protected password\nextensionResourceId: '/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.Web/serverfarms/xxxxxappserviceplan'\n}\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20202063/"
] |
74,544,197
|
<p>Assuming x is a 8bit unsigned integer, what is the most efficient command to set the last two bits to <code>01</code> ?
So regardless of the initial value it should be <code>x = ******01</code> in the final state.</p>
<p>In order to set</p>
<ul>
<li>the last bit to 1, one can use OR like <code>x |= 00000001</code>, and</li>
<li>the forelast bit to 0, one can use AND like <code>x &= 11111101</code> which is <code>~(1<<1)</code>.</li>
</ul>
<p>Is there an arithmetic / logical operation that can be use to apply both operations at the same time?</p>
<p>Can this be answered independently of programm-specific implementation but pure logical operations?</p>
|
[
{
"answer_id": 74590743,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": -1,
"selected": false,
"text": " Ensure that the service principal has all the permissions. The only thing that worked for me though is adding the service principal 24681998-555f-4570-a559-2fced2d7e841 which shows up as Microsoft.Azure.WebSites. You can add this through the portal, by adding an access policy for Microsoft.Azure.WebSites or through arm with the GUID."
},
{
"answer_id": 74654463,
"author": "Jahnavi",
"author_id": 19785512,
"author_profile": "https://Stackoverflow.com/users/19785512",
"pm_score": 0,
"selected": false,
"text": "keyvault -> secrets key vault Access Policies ssl certificate key,secret & certificate management AzureAD -> App registrations App Service -> Web Application -> Certificates keyvault -> secrets .pfx resource certEncryption 'Microsoft.Web/certificates@2018-02-01' = {\nname: 'xcc-cert-encryption'\nlocation: 'EastUS'\nproperties: {\nkeyVaultId: '/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.KeyVault/vaults/xxxxxkeyvaults'\nkeyVaultSecretName: 'jahnss'\npassword: 'xxxxx' //Certificate protected password\nextensionResourceId: '/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.Web/serverfarms/xxxxxappserviceplan'\n}\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14776523/"
] |
74,544,254
|
<p>I'm a beginner with Python.
Say I have a list of lists in python</p>
<pre><code> list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]
</code></pre>
<p>How can I search the list of lists for say 'id2' and print a list with only the integers in its list?</p>
<p>This is what I tried</p>
<pre><code> import numbers
def list_search(lister,index):
for i in lister:
for j in i:
if j == index:
[x for x in i if isinstance(x, numbers.Number)]
print("Not found: ",index)
</code></pre>
<p>Here is the Test for my function</p>
<pre><code> list_search(list1,'id2')
</code></pre>
<p>I was expecting
[90,87,92]
but I got
Not found: id2</p>
|
[
{
"answer_id": 74544346,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "[x for x in i if isinstance(x, numbers.Number)]\n Not found import numbers\n\nlist1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\ndef list_search(lister,index):\n for i in lister:\n for j in i:\n if j == index:\n return [x for x in i if isinstance(x, numbers.Number)]\n print(\"Not found: \",index)\n \nmy_list = list_search(list1,'id2')\n\nprint(my_list)\n# print average\nprint( sum(my_list) / len(my_list))\n [90, 87, 92]\n89.66666666666667\n"
},
{
"answer_id": 74544435,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "index None index Number item[:1] def list_search(lister, index):\n for item in lister:\n if item[0] == index:\n return [x for x in item[1:] if isinstance(x, int)]\n return None\n numbers = list_search(list1, \"id2\")\nprint(sum(numbers)/len(numbers))\n"
},
{
"answer_id": 74544446,
"author": "Yash Mehta",
"author_id": 20172954,
"author_profile": "https://Stackoverflow.com/users/20172954",
"pm_score": 0,
"selected": false,
"text": "list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\ndef list_search(list_of_list,index):\n result=[]\n for lis in list_of_list:\n if lis[0]==index:\n for check in lis:\n try:\n result.append(int(check))\n except ValueError:\n continue\n return sum(result)/len(result) if result else 0\nprint(list_search(list1,\"id2\"))\n 207.6666666\n"
},
{
"answer_id": 74544475,
"author": "Sarper Makas",
"author_id": 19737398,
"author_profile": "https://Stackoverflow.com/users/19737398",
"pm_score": 0,
"selected": false,
"text": " def func(a, activatedString):\n result = []\n for i in a:\n if i[0] == activatedString:\n for j in i:\n if isinstance(i, int):\n result.append(j)\n\n return result\n def func(list1, activatedString):\n return [i for i in [a for a in list1 if a[0] == activatedString][0] if isinstance(i, int)]\n\nprint(func(list1, \"id2\"))\n"
},
{
"answer_id": 74544661,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "integers list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\n\ntemp_integers = [list(filter(lambda x: isinstance(x, int), list1[i])) for i in range(len(list1))]\n >>> temp_integers\n... [[100, 75, 100], [90, 87, 92], [79, 81, 83]]\n means temp_means=[np.mean(x) for x in temp_integers]\n >>> temp_means\n... [91.66666666666667, 89.66666666666667, 81.0]\n id2 mean for i in range(len(list1)):\n if 'id2' in list1[i]:\n print(temp_integers[i])\n print(temp_means[i])\n def list_search(lister,index):\n temp_integers = [list(filter(lambda x: isinstance(x, int), lister[i])) for i in range(len(lister))]\n temp_means=[np.mean(x) for x in temp_integers]\n \n if all(index not in y for y in lister):\n print(\"Not found: \",index)\n else:\n for i in range(len(lister)):\n if index in lister[i]:\n print(temp_integers[i])\n print(temp_means[i])\n >>> list_search(list1,'id2')\n... [90, 87, 92]\n... 89.66666666666667\n"
},
{
"answer_id": 74545560,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\n\ndef list_search(lister, index):\n return [j for i in lister for j in i if isinstance(j, int) and i[0] == index]\n\nresults = list_search(list1,'id2')\nprint(results)\n\naverage = sum(results)/len(results)\nprint(average)\n\n# Output:\n# [90, 87, 92]\n# 89.66666666666667\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580104/"
] |
74,544,275
|
<p>I'm trying to add an active class on the map element with hover. Everything is perfect but I need to add an active class on the first div when I do not hover over any.</p>
<p>Here is my code...</p>
<pre><code>{WhatWeOfferData.map(({ img, title, para}, index) => {
return (
<div
className={`${style.card} ${addActive.index === index && addActive.show ? `${style.active}` : ""}`}
onMouseEnter={hoverOn}
onMouseLeave={hoverOff}
key={index}
data-id={index}
>
<Image src={img} alt="offer_images" width={37} height={41} />
<h2>{title}</h2>
<p>{para}</p>
</div>
);
})}
</code></pre>
<p>and</p>
<pre><code> let [addActive, setAddActive] = useState(false);
const hoverOn = (e) => {
setAddActive({
index: parseInt(e.currentTarget.dataset.id),
show: true
});
};
const hoverOff = (e) => {
setAddActive({
index: parseInt(e.currentTarget.dataset.id),
show: false
});
};
</code></pre>
|
[
{
"answer_id": 74544346,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "[x for x in i if isinstance(x, numbers.Number)]\n Not found import numbers\n\nlist1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\ndef list_search(lister,index):\n for i in lister:\n for j in i:\n if j == index:\n return [x for x in i if isinstance(x, numbers.Number)]\n print(\"Not found: \",index)\n \nmy_list = list_search(list1,'id2')\n\nprint(my_list)\n# print average\nprint( sum(my_list) / len(my_list))\n [90, 87, 92]\n89.66666666666667\n"
},
{
"answer_id": 74544435,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "index None index Number item[:1] def list_search(lister, index):\n for item in lister:\n if item[0] == index:\n return [x for x in item[1:] if isinstance(x, int)]\n return None\n numbers = list_search(list1, \"id2\")\nprint(sum(numbers)/len(numbers))\n"
},
{
"answer_id": 74544446,
"author": "Yash Mehta",
"author_id": 20172954,
"author_profile": "https://Stackoverflow.com/users/20172954",
"pm_score": 0,
"selected": false,
"text": "list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\ndef list_search(list_of_list,index):\n result=[]\n for lis in list_of_list:\n if lis[0]==index:\n for check in lis:\n try:\n result.append(int(check))\n except ValueError:\n continue\n return sum(result)/len(result) if result else 0\nprint(list_search(list1,\"id2\"))\n 207.6666666\n"
},
{
"answer_id": 74544475,
"author": "Sarper Makas",
"author_id": 19737398,
"author_profile": "https://Stackoverflow.com/users/19737398",
"pm_score": 0,
"selected": false,
"text": " def func(a, activatedString):\n result = []\n for i in a:\n if i[0] == activatedString:\n for j in i:\n if isinstance(i, int):\n result.append(j)\n\n return result\n def func(list1, activatedString):\n return [i for i in [a for a in list1 if a[0] == activatedString][0] if isinstance(i, int)]\n\nprint(func(list1, \"id2\"))\n"
},
{
"answer_id": 74544661,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "integers list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\n\ntemp_integers = [list(filter(lambda x: isinstance(x, int), list1[i])) for i in range(len(list1))]\n >>> temp_integers\n... [[100, 75, 100], [90, 87, 92], [79, 81, 83]]\n means temp_means=[np.mean(x) for x in temp_integers]\n >>> temp_means\n... [91.66666666666667, 89.66666666666667, 81.0]\n id2 mean for i in range(len(list1)):\n if 'id2' in list1[i]:\n print(temp_integers[i])\n print(temp_means[i])\n def list_search(lister,index):\n temp_integers = [list(filter(lambda x: isinstance(x, int), lister[i])) for i in range(len(lister))]\n temp_means=[np.mean(x) for x in temp_integers]\n \n if all(index not in y for y in lister):\n print(\"Not found: \",index)\n else:\n for i in range(len(lister)):\n if index in lister[i]:\n print(temp_integers[i])\n print(temp_means[i])\n >>> list_search(list1,'id2')\n... [90, 87, 92]\n... 89.66666666666667\n"
},
{
"answer_id": 74545560,
"author": "Arifa Chan",
"author_id": 19574157,
"author_profile": "https://Stackoverflow.com/users/19574157",
"pm_score": 0,
"selected": false,
"text": "list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]\n\ndef list_search(lister, index):\n return [j for i in lister for j in i if isinstance(j, int) and i[0] == index]\n\nresults = list_search(list1,'id2')\nprint(results)\n\naverage = sum(results)/len(results)\nprint(average)\n\n# Output:\n# [90, 87, 92]\n# 89.66666666666667\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10011289/"
] |
74,544,276
|
<p>I want a list of <code>user_id</code> which shouldn't have zero status.</p>
<p>Lets say, I have task table with user id, status. I'm trying to write a query to fetch user ids which have status = 1 only but not 2. As for below table, it should get me users id of tables with only status =1;</p>
<p>User table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>etc</th>
</tr>
</thead>
<tbody>
<tr>
<td>100</td>
<td>anything</td>
</tr>
<tr>
<td>200</td>
<td>anything</td>
</tr>
<tr>
<td>300</td>
<td>anything</td>
</tr>
</tbody>
</table>
</div>
<p>Tasks table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>user_id</th>
<th>status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>100</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>100</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>200</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>300</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>200</td>
<td>2</td>
</tr>
<tr>
<td>6</td>
<td>300</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried this query</p>
<pre class="lang-sql prettyprint-override"><code>SELECT user_id FROM tasks where status =2 and status != 1;
</code></pre>
<p>The above user id 100 has two tasks one with status 1 and other with status 2, I don't want that user.
The above user id 200 has two tasks but none of them has status 1, that is what i want.
The above user id 300 has both tasks with status 1, I don't want it too.</p>
<p>Status 1 means open. So I want a query which should get me users with zero open tasks only. If it has status 1 and 2 both, I don't want that.</p>
<p>I have tried multiple queries, but unable to find it.</p>
|
[
{
"answer_id": 74544334,
"author": "Akina",
"author_id": 10138734,
"author_profile": "https://Stackoverflow.com/users/10138734",
"pm_score": 0,
"selected": false,
"text": "SELECT *\nFROM users\nWHERE EXISTS ( SELECT NULL\n FROM tasks\n WHERE users.id = tasks.user_id\n AND statis IN (1) -- must have 1\n )\n AND NOT EXISTS ( SElECT NULL\n FROM tasks\n WHERE users.id = tasks.user_id\n AND statis IN (2) -- must not have 2\n )\n WHERE .. AND statis IN (..)"
},
{
"answer_id": 74544484,
"author": "AymDev",
"author_id": 6349751,
"author_profile": "https://Stackoverflow.com/users/6349751",
"pm_score": 1,
"selected": false,
"text": "IN() NOT IN() SELECT *\nFROM users\nWHERE\n -- ensure the user has at least 1 task in status 1\n id IN(\n SELECT user_id\n FROM tasks\n WHERE status = 1\n )\n -- ensure the user has no task in status 2\n AND id NOT IN(\n SELECT user_id\n FROM tasks\n WHERE status = 2\n )\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19306161/"
] |
74,544,298
|
<p>I have a list look like:</p>
<pre><code>const initArray = [
{
id: 0,
},
{
id: 1,
},
{
id: 2,
},
{
id: 3,
},
];
</code></pre>
<p>A selected list look like:</p>
<pre><code>const selectedList = [
{
id: 2,
},
];
</code></pre>
<p>And the desired data has been sorted:</p>
<pre><code>const outPut= [
{
id: 2,
},
{
id: 0,
},
{
id: 1,
},
{
id: 3,
},
];
</code></pre>
<p>I'm in trouble right now, so I can't figure it out yet.</p>
<p>Can you share some solutions?</p>
|
[
{
"answer_id": 74544464,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 1,
"selected": false,
"text": "Set Array#map Array#sort const _sort = (arr = [], selected = []) => {\n const priority = new Set( selected.map(({ id }) => id) );\n return [...arr].sort(({ id: a }, { id: b }) => priority.has(b) - priority.has(a));\n}\n\nconst \n initArray = [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ],\n selectedList = [ { id: 2 } ];\nconsole.log( _sort(initArray, selectedList) );"
},
{
"answer_id": 74544547,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 3,
"selected": true,
"text": "const\n data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }],\n selectedList = [{ id: 2 }],\n order = Object.fromEntries(selectedList.map(({ id }, i) => [id, i + 1]));\n\ndata.sort((a, b) => (order[a.id] || Number.MAX_VALUE) - (order[b.id] || Number.MAX_VALUE));\n\nconsole.log(data);"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745811/"
] |
74,544,300
|
<p>type script:</p>
<p><code>Buffer.from('Мегафон').toString('base64') //0JzQtdCz0LDRhNC+0L0=</code></p>
<p>go:</p>
<p><code>decode, err := base64.URLEncoding.DecodeString("0JzQtdCz0LDRhNC+0L0=") //err : illegal base64 data at input byte 15</code></p>
<p>if i try:</p>
<p><code>base64.URLEncoding.EncodeToString([]byte("Мегафон")) //0JzQtdCz0LDRhNC-0L0=</code></p>
<p>That is, the difference is only in + and -.</p>
<p>I made it work with
<code>v = strings.ReplaceAll(v, "+", "-")</code>
but this is clearly not a solution.</p>
|
[
{
"answer_id": 74544378,
"author": "Steffen Ullrich",
"author_id": 3081018,
"author_profile": "https://Stackoverflow.com/users/3081018",
"pm_score": 2,
"selected": false,
"text": "base64.URLEncoding.DecodeString base64.StdEncoding.DecodeString"
},
{
"answer_id": 74544465,
"author": "wirekang",
"author_id": 15062892,
"author_profile": "https://Stackoverflow.com/users/15062892",
"pm_score": 0,
"selected": false,
"text": "base64.go // StdEncoding is the standard base64 encoding, as defined in\n// RFC 4648.\nvar StdEncoding = NewEncoding(encodeStd)\n\n// URLEncoding is the alternate base64 encoding defined in RFC 4648.\n// It is typically used in URLs and file names.\nvar URLEncoding = NewEncoding(encodeURL)\n base64.StdEncoding.DecodeString(\"0JzQtdCz0LDRhNC+0L0=\")\n base64url base64 base64.URLEncoding Buffer.from('Мегафон').toString('base64url'); //'0JzQtdCz0LDRhNC-0L0'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580229/"
] |
74,544,306
|
<p>I can not serialize a nested set of classes to json:</p>
<pre><code>import { readFileSync } from 'fs'
class Address {
constructor(
public readonly street: string,
public readonly city: string){}
}
class Person {
constructor(
public readonly address: Address,
public readonly name: string){}
}
class School {
private students = new Map<string, Person>();
public add(student: Person): School {
this.students.set(student.name, student);
return this;
}
public toJson(filename: string) {
}
}
const p1 = new Person(new Address("5th Ave.", "NYC"), "moish");
const p2 = new Person(new Address("remi", "Boston"), "dave");
const p3 = new Person(new Address("Dart", "Boston"), "uzi");
let school = new School();
school.add(p1).add(p2).add(p3)
console.log(school); // <--- good ! but wrong format
console.log(JSON.stringify(school)); // doesn't work: {"students":{}}
</code></pre>
<p>And here is how I compile and run it:</p>
<pre><code>% npx tsc --target es2022 --moduleResolution node main.ts
% node main.js
School {
students: Map(3) {
'moish' => Person { address: [Address], name: 'moish' },
'dave' => Person { address: [Address], name: 'dave' },
'uzi' => Person { address: [Address], name: 'uzi' }
}
}
{"students":{}}
</code></pre>
|
[
{
"answer_id": 74544378,
"author": "Steffen Ullrich",
"author_id": 3081018,
"author_profile": "https://Stackoverflow.com/users/3081018",
"pm_score": 2,
"selected": false,
"text": "base64.URLEncoding.DecodeString base64.StdEncoding.DecodeString"
},
{
"answer_id": 74544465,
"author": "wirekang",
"author_id": 15062892,
"author_profile": "https://Stackoverflow.com/users/15062892",
"pm_score": 0,
"selected": false,
"text": "base64.go // StdEncoding is the standard base64 encoding, as defined in\n// RFC 4648.\nvar StdEncoding = NewEncoding(encodeStd)\n\n// URLEncoding is the alternate base64 encoding defined in RFC 4648.\n// It is typically used in URLs and file names.\nvar URLEncoding = NewEncoding(encodeURL)\n base64.StdEncoding.DecodeString(\"0JzQtdCz0LDRhNC+0L0=\")\n base64url base64 base64.URLEncoding Buffer.from('Мегафон').toString('base64url'); //'0JzQtdCz0LDRhNC-0L0'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3357352/"
] |
74,544,314
|
<p>I have a service. This contains the following function (simplified):</p>
<pre><code>private _eventListener$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
</code></pre>
<pre><code>push(field?: FormField): void {
this.isAlive = true;
this._eventListener$.pipe(
debounceTime(3500),
takeWhile(() => this.isAlive)
).subscribe(() => {
this.isAlive = false;
console.log(field?.control.value)
});
}
</code></pre>
<p>This function does the following: if a field changes (input, dropdown,...) then the backend should be called and data should be queried. This should not happen directly with every change of a field but only after a certain time nothing has changed. Therefore I have thought, I use debounceTime. But unfortunately this does not work.</p>
<p>If I enter a lot of numbers and I am above the debounce time, all the numbers I enter are logged:</p>
<p><a href="https://i.stack.imgur.com/RCGI2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RCGI2.png" alt="enter image description here" /></a></p>
<p>I thought debounceTime always only outputs the last value after nothing has happened for a certain time. Why does this not work?</p>
|
[
{
"answer_id": 74544378,
"author": "Steffen Ullrich",
"author_id": 3081018,
"author_profile": "https://Stackoverflow.com/users/3081018",
"pm_score": 2,
"selected": false,
"text": "base64.URLEncoding.DecodeString base64.StdEncoding.DecodeString"
},
{
"answer_id": 74544465,
"author": "wirekang",
"author_id": 15062892,
"author_profile": "https://Stackoverflow.com/users/15062892",
"pm_score": 0,
"selected": false,
"text": "base64.go // StdEncoding is the standard base64 encoding, as defined in\n// RFC 4648.\nvar StdEncoding = NewEncoding(encodeStd)\n\n// URLEncoding is the alternate base64 encoding defined in RFC 4648.\n// It is typically used in URLs and file names.\nvar URLEncoding = NewEncoding(encodeURL)\n base64.StdEncoding.DecodeString(\"0JzQtdCz0LDRhNC+0L0=\")\n base64url base64 base64.URLEncoding Buffer.from('Мегафон').toString('base64url'); //'0JzQtdCz0LDRhNC-0L0'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917537/"
] |
74,544,321
|
<p>I'm getting values in the below format</p>
<pre><code>/a/b/c/d="value1"
/a/b/e/f="value2"
</code></pre>
<p>I want these values in the below format.</p>
<pre><code>{
"a": {
"b": {
{
"c": {
"d": "value1"
}
},
{
"e" {
"f": "value2"
}
}
}
}
</code></pre>
<p>}</p>
<p>Are there any built-in functions in python that can do this job as I could <code>a["b"]["c"]["d"]</code> kind of structure is not possible in the python dictionary?</p>
|
[
{
"answer_id": 74544378,
"author": "Steffen Ullrich",
"author_id": 3081018,
"author_profile": "https://Stackoverflow.com/users/3081018",
"pm_score": 2,
"selected": false,
"text": "base64.URLEncoding.DecodeString base64.StdEncoding.DecodeString"
},
{
"answer_id": 74544465,
"author": "wirekang",
"author_id": 15062892,
"author_profile": "https://Stackoverflow.com/users/15062892",
"pm_score": 0,
"selected": false,
"text": "base64.go // StdEncoding is the standard base64 encoding, as defined in\n// RFC 4648.\nvar StdEncoding = NewEncoding(encodeStd)\n\n// URLEncoding is the alternate base64 encoding defined in RFC 4648.\n// It is typically used in URLs and file names.\nvar URLEncoding = NewEncoding(encodeURL)\n base64.StdEncoding.DecodeString(\"0JzQtdCz0LDRhNC+0L0=\")\n base64url base64 base64.URLEncoding Buffer.from('Мегафон').toString('base64url'); //'0JzQtdCz0LDRhNC-0L0'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11430828/"
] |
74,544,379
|
<p>Let's say I have 5 of these</p>
<pre><code><input type="button" class="button" value="A">
<input type="button" class="button" value="B">
<input type="button" class="button" value="C">
<input type="button" class="button" value="D">
<input type="button" class="button" value="E">
</code></pre>
<p>So basically I want all the buttons with a class of <strong>button</strong> to change its value from uppercase (A) to lowercase (a) when I click on a specific button like this
<code><input type="button" id="ChangeBtn"></code></p>
<p>I tried using JavaScript (which im new to) to do this.</p>
<pre><code><script>
//The button I want to click to perform the function
Var button = document.gelementById("ChangeBtn");
//The buttons with a class button I want to change its value to lowercase
Var value = document.querySelector(".button").value;
button.onclick = function (){
Value.classList.toggle("change");
}
</script>
</code></pre>
<p>Using the class list</p>
<pre><code>.change{
text-transform : lowercase
}
</code></pre>
|
[
{
"answer_id": 74544378,
"author": "Steffen Ullrich",
"author_id": 3081018,
"author_profile": "https://Stackoverflow.com/users/3081018",
"pm_score": 2,
"selected": false,
"text": "base64.URLEncoding.DecodeString base64.StdEncoding.DecodeString"
},
{
"answer_id": 74544465,
"author": "wirekang",
"author_id": 15062892,
"author_profile": "https://Stackoverflow.com/users/15062892",
"pm_score": 0,
"selected": false,
"text": "base64.go // StdEncoding is the standard base64 encoding, as defined in\n// RFC 4648.\nvar StdEncoding = NewEncoding(encodeStd)\n\n// URLEncoding is the alternate base64 encoding defined in RFC 4648.\n// It is typically used in URLs and file names.\nvar URLEncoding = NewEncoding(encodeURL)\n base64.StdEncoding.DecodeString(\"0JzQtdCz0LDRhNC+0L0=\")\n base64url base64 base64.URLEncoding Buffer.from('Мегафон').toString('base64url'); //'0JzQtdCz0LDRhNC-0L0'\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20515018/"
] |
74,544,386
|
<p>Lets say I have the following route to display a specific user in an API point, that is protected via some authentication middle:</p>
<pre><code>Route::get('/v1/user/{user}', 'Api\V1\UserController@show')->middleware('can:show,user');
</code></pre>
<p>Assume my database is filled with just a handfull records. Then, going to the route <strong>without</strong> a credential:</p>
<ul>
<li><code>/api/v1/user/1</code> will give me <code>403 UNAUTHORIZED</code></li>
<li><code>/api/v1/user/999999</code> will give me <code>404 NOT FOUND</code></li>
</ul>
<p>In this setup, any visitor can find out how many users I have, by just poking around and trying some routes. Moreover, they can also find out the primary identifier (the id) of these users. This is something I would like to hide from a business perspective, but also from a security perspective.</p>
<p>An appoach that partially addresses this issue, is using UUID's. UUIDs are universally unique alpha-numeric identifiers that are 36 characters long, and <a href="https://laravel.com/docs/9.x/eloquent#uuid-and-ulid-keys" rel="nofollow noreferrer">Laravel supports the use of these on your models</a>. This will hide the amount of records our have, and make it hard to find existing records. However, since it is still statistically possible to find records by just brute forcing, I feel this is not the correct answer to this problem.</p>
<p>So, how can I prevent a Laravel security leak where API returns not found when you are not authenticated?</p>
|
[
{
"answer_id": 74544978,
"author": "ericmp",
"author_id": 14569750,
"author_profile": "https://Stackoverflow.com/users/14569750",
"pm_score": 2,
"selected": true,
"text": "404 403 app/Exceptions/Handler.php render() 403 404 public function render($request, Throwable $e)\n{\n if ($e->getStatusCode() === 403) {\n abort(404);\n }\n\n return parent::render($request, $e);\n}\n routes/web.php Route::get('/test', function () {\n return abort(403); // should return a 404\n});\n"
},
{
"answer_id": 74545973,
"author": "Erhan URGUN",
"author_id": 9476192,
"author_profile": "https://Stackoverflow.com/users/9476192",
"pm_score": 2,
"selected": false,
"text": "// Path: app/Http/Controllers/Api/V1/UserController.php\n<?php\n\nnamespace App\\Http\\Controllers\\Api\\V1;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\User;\nuse Illuminate\\Http\\Request;\n\nclass UserController extends Controller\n{\n public function show(User $user)\n {\n return $user;\n }\n}\n // Path: app/User.php\n<?php\n\nnamespace App;\n\nuse Illuminate\\Notifications\\Notifiable;\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\n\nclass User extends Authenticatable\n{\n use Notifiable;\n\n /**\n * The attributes that are mass assignable.\n *\n * @var array\n */\n protected $fillable = [\n 'name', 'email', 'password',\n ];\n\n /**\n * The attributes that should be hidden for arrays.\n *\n * @var array\n */\n protected $hidden = [\n 'password', 'remember_token',\n ];\n}\n // Path: routes/api.php\n<?php\n\nRoute::get('/v1/user/{user}', 'Api\\V1\\UserController@show')->middleware('can:show,user');\n // Path: app/Providers/AuthServiceProvider.php\n<?php\n\nnamespace App\\Providers;\n\nuse Illuminate\\Foundation\\Support\\Providers\\AuthServiceProvider as ServiceProvider;\nuse Illuminate\\Support\\Facades\\Gate;\n\nclass AuthServiceProvider extends ServiceProvider\n{\n /**\n * The policy mappings for the application.\n *\n * @var array\n */\n protected $policies = [\n 'App\\Model' => 'App\\Policies\\ModelPolicy',\n ];\n\n /**\n * Register any authentication / authorization services.\n *\n * @return void\n */\n public function boot()\n {\n $this->registerPolicies();\n\n //\n }\n}\n // Path: app/Http/Middleware/Can.php\n<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Auth\\Access\\AuthorizationException;\nuse Illuminate\\Auth\\Access\\Response;\nuse Illuminate\\Support\\Facades\\Gate;\n\nclass Can\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @param string $ability\n * @param array|string $arguments\n * @return mixed\n *\n * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n */\n public function handle($request, Closure $next, $ability, ...$arguments)\n {\n if (Gate::denies($ability, $arguments)) {\n throw new AuthorizationException(\n 'This action is unauthorized.', null, Response::deny()\n );\n }\n\n return $next($request);\n }\n}\n // Path: app/Http/Kernel.php\n<?php\n\nnamespace App\\Http;\n\nuse App\\Http\\Middleware\\Can;\nuse Illuminate\\Foundation\\Http\\Kernel as HttpKernel;\n\nclass Kernel extends HttpKernel\n{\n /**\n * The application's global HTTP middleware stack.\n *\n * These middleware are run during every request to your application.\n *\n * @var array\n */\n protected $middleware = [\n \\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode::class,\n ];\n\n /**\n * The application's route middleware groups.\n *\n * @var array\n */\n protected $middlewareGroups = [\n 'web' => [\n \\App\\Http\\Middleware\\EncryptCookies::class,\n \\Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse::class,\n \\Illuminate\\Session\\Middleware\\StartSession::class,\n // \\Illuminate\\Session\\Middleware\\AuthenticateSession::class,\n \\Illuminate\\View\\Middleware\\ShareErrorsFromSession::class,\n \\App\\Http\\Middleware\\VerifyCsrfToken::class,\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n ],\n\n 'api' => [\n 'throttle:60,1',\n 'bindings',\n ],\n ];\n\n /**\n * The application's route middleware.\n *\n * These middleware may be assigned to groups or used individually.\n *\n * @var array\n */\n protected $routeMiddleware = [\n 'auth' => \\Illuminate\\Auth\\Middleware\\Authenticate::class,\n 'auth.basic' => \\Illuminate\\Auth\\Middleware\\AuthenticateWithBasicAuth::class,\n 'bindings' => \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n 'cache.headers' => \\Illuminate\\Http\\Middleware\\SetCacheHeaders::class,\n 'can' => Can::class,\n 'guest' => \\App\\Http\\Middleware\\RedirectIfAuthenticated::class,\n 'signed' => \\Illuminate\\Routing\\Middleware\\ValidateSignature::class,\n 'throttle' => \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class,\n 'verified' => \\Illuminate\\Auth\\Middleware\\EnsureEmailIsVerified::class,\n ];\n}\n // Path: app/Http/Controllers/Api/V1/UserControllerTest.php\n<?php\n\nnamespace Tests\\Feature\\Api\\V1;\n\nuse App\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Illuminate\\Foundation\\Testing\\WithFaker;\nuse Tests\\TestCase;\n\nclass UserControllerTest extends TestCase\n{\n use RefreshDatabase;\n\n public function testShow()\n {\n $user = factory(User::class)->create();\n\n $response = $this->getJson(\"/api/v1/user/{$user->id}\");\n\n $response->assertStatus(200);\n }\n\n public function testShowUnauthorized()\n {\n $user = factory(User::class)->create();\n\n $response = $this->getJson(\"/api/v1/user/{$user->id}\");\n\n $response->assertStatus(403);\n }\n\n public function testShowUnauthorizedWithPolicy()\n {\n $user = factory(User::class)->create();\n\n $response = $this->getJson(\"/api/v1/user/{$user->id}\");\n\n $response->assertStatus(403);\n }\n}\n // Path: app/Policies/UserPolicy.php\n<?php\n\nnamespace App\\Policies;\n\nuse App\\User;\nuse Illuminate\\Auth\\Access\\HandlesAuthorization;\n\nclass UserPolicy\n{\n use HandlesAuthorization;\n\n /**\n * Determine whether the user can view the model.\n *\n * @param \\App\\User $user\n * @param \\App\\User $model\n * @return mixed\n */\n public function show(User $user, User $model)\n {\n return $user->id === $model->id;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12355272/"
] |
74,544,412
|
<p>I'm trying to create a simple script to update a file within a zip, but running into some issues.
MyZip.zip contains some subdirectories, and the file I want to update (myFile.txt) is inside dir1/dir2/dir3:</p>
<p><a href="https://i.stack.imgur.com/dF9vB.png" rel="nofollow noreferrer">initialZip</a></p>
<p>I'm then running the following command to try and update this file with a new version of myFile.txt (which is nested inside dir1/dir2/dir3 on my file system so that it gets updated into the right directory in the zip):</p>
<pre><code>Compress-Archive -Path .\dir1 -Update -DestinationPath .\myZip.zip
</code></pre>
<p>But this is resulting in the new version of the file being added to the directory, but not replacing the old version:</p>
<p><a href="https://i.stack.imgur.com/YXj0U.png" rel="nofollow noreferrer">DuplicatedFile</a></p>
<p>What doesn't make sense after this, is that when I then go and update the source file, and rerun the same command, the new version of the file is updated correctly, and it doesn't make a third one?</p>
<p><a href="https://i.stack.imgur.com/omN3r.png" rel="nofollow noreferrer">UpdatedDuplicate</a></p>
<p>Why wouldn't this work for the original file in the zip?
Am I doing something wrong, or do I need to change how I'm doing this?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74544978,
"author": "ericmp",
"author_id": 14569750,
"author_profile": "https://Stackoverflow.com/users/14569750",
"pm_score": 2,
"selected": true,
"text": "404 403 app/Exceptions/Handler.php render() 403 404 public function render($request, Throwable $e)\n{\n if ($e->getStatusCode() === 403) {\n abort(404);\n }\n\n return parent::render($request, $e);\n}\n routes/web.php Route::get('/test', function () {\n return abort(403); // should return a 404\n});\n"
},
{
"answer_id": 74545973,
"author": "Erhan URGUN",
"author_id": 9476192,
"author_profile": "https://Stackoverflow.com/users/9476192",
"pm_score": 2,
"selected": false,
"text": "// Path: app/Http/Controllers/Api/V1/UserController.php\n<?php\n\nnamespace App\\Http\\Controllers\\Api\\V1;\n\nuse App\\Http\\Controllers\\Controller;\nuse App\\User;\nuse Illuminate\\Http\\Request;\n\nclass UserController extends Controller\n{\n public function show(User $user)\n {\n return $user;\n }\n}\n // Path: app/User.php\n<?php\n\nnamespace App;\n\nuse Illuminate\\Notifications\\Notifiable;\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\n\nclass User extends Authenticatable\n{\n use Notifiable;\n\n /**\n * The attributes that are mass assignable.\n *\n * @var array\n */\n protected $fillable = [\n 'name', 'email', 'password',\n ];\n\n /**\n * The attributes that should be hidden for arrays.\n *\n * @var array\n */\n protected $hidden = [\n 'password', 'remember_token',\n ];\n}\n // Path: routes/api.php\n<?php\n\nRoute::get('/v1/user/{user}', 'Api\\V1\\UserController@show')->middleware('can:show,user');\n // Path: app/Providers/AuthServiceProvider.php\n<?php\n\nnamespace App\\Providers;\n\nuse Illuminate\\Foundation\\Support\\Providers\\AuthServiceProvider as ServiceProvider;\nuse Illuminate\\Support\\Facades\\Gate;\n\nclass AuthServiceProvider extends ServiceProvider\n{\n /**\n * The policy mappings for the application.\n *\n * @var array\n */\n protected $policies = [\n 'App\\Model' => 'App\\Policies\\ModelPolicy',\n ];\n\n /**\n * Register any authentication / authorization services.\n *\n * @return void\n */\n public function boot()\n {\n $this->registerPolicies();\n\n //\n }\n}\n // Path: app/Http/Middleware/Can.php\n<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Auth\\Access\\AuthorizationException;\nuse Illuminate\\Auth\\Access\\Response;\nuse Illuminate\\Support\\Facades\\Gate;\n\nclass Can\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @param string $ability\n * @param array|string $arguments\n * @return mixed\n *\n * @throws \\Illuminate\\Auth\\Access\\AuthorizationException\n */\n public function handle($request, Closure $next, $ability, ...$arguments)\n {\n if (Gate::denies($ability, $arguments)) {\n throw new AuthorizationException(\n 'This action is unauthorized.', null, Response::deny()\n );\n }\n\n return $next($request);\n }\n}\n // Path: app/Http/Kernel.php\n<?php\n\nnamespace App\\Http;\n\nuse App\\Http\\Middleware\\Can;\nuse Illuminate\\Foundation\\Http\\Kernel as HttpKernel;\n\nclass Kernel extends HttpKernel\n{\n /**\n * The application's global HTTP middleware stack.\n *\n * These middleware are run during every request to your application.\n *\n * @var array\n */\n protected $middleware = [\n \\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode::class,\n ];\n\n /**\n * The application's route middleware groups.\n *\n * @var array\n */\n protected $middlewareGroups = [\n 'web' => [\n \\App\\Http\\Middleware\\EncryptCookies::class,\n \\Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse::class,\n \\Illuminate\\Session\\Middleware\\StartSession::class,\n // \\Illuminate\\Session\\Middleware\\AuthenticateSession::class,\n \\Illuminate\\View\\Middleware\\ShareErrorsFromSession::class,\n \\App\\Http\\Middleware\\VerifyCsrfToken::class,\n \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n ],\n\n 'api' => [\n 'throttle:60,1',\n 'bindings',\n ],\n ];\n\n /**\n * The application's route middleware.\n *\n * These middleware may be assigned to groups or used individually.\n *\n * @var array\n */\n protected $routeMiddleware = [\n 'auth' => \\Illuminate\\Auth\\Middleware\\Authenticate::class,\n 'auth.basic' => \\Illuminate\\Auth\\Middleware\\AuthenticateWithBasicAuth::class,\n 'bindings' => \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class,\n 'cache.headers' => \\Illuminate\\Http\\Middleware\\SetCacheHeaders::class,\n 'can' => Can::class,\n 'guest' => \\App\\Http\\Middleware\\RedirectIfAuthenticated::class,\n 'signed' => \\Illuminate\\Routing\\Middleware\\ValidateSignature::class,\n 'throttle' => \\Illuminate\\Routing\\Middleware\\ThrottleRequests::class,\n 'verified' => \\Illuminate\\Auth\\Middleware\\EnsureEmailIsVerified::class,\n ];\n}\n // Path: app/Http/Controllers/Api/V1/UserControllerTest.php\n<?php\n\nnamespace Tests\\Feature\\Api\\V1;\n\nuse App\\User;\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Illuminate\\Foundation\\Testing\\WithFaker;\nuse Tests\\TestCase;\n\nclass UserControllerTest extends TestCase\n{\n use RefreshDatabase;\n\n public function testShow()\n {\n $user = factory(User::class)->create();\n\n $response = $this->getJson(\"/api/v1/user/{$user->id}\");\n\n $response->assertStatus(200);\n }\n\n public function testShowUnauthorized()\n {\n $user = factory(User::class)->create();\n\n $response = $this->getJson(\"/api/v1/user/{$user->id}\");\n\n $response->assertStatus(403);\n }\n\n public function testShowUnauthorizedWithPolicy()\n {\n $user = factory(User::class)->create();\n\n $response = $this->getJson(\"/api/v1/user/{$user->id}\");\n\n $response->assertStatus(403);\n }\n}\n // Path: app/Policies/UserPolicy.php\n<?php\n\nnamespace App\\Policies;\n\nuse App\\User;\nuse Illuminate\\Auth\\Access\\HandlesAuthorization;\n\nclass UserPolicy\n{\n use HandlesAuthorization;\n\n /**\n * Determine whether the user can view the model.\n *\n * @param \\App\\User $user\n * @param \\App\\User $model\n * @return mixed\n */\n public function show(User $user, User $model)\n {\n return $user->id === $model->id;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20574212/"
] |
74,544,431
|
<p>I have grey row that should contain text and icons, my code:
<code>{{ trans.dashboard.settings.car.Name| translate }} <i class="fas fa-caret-up"></i></code></p>
<p>this works, but i wanna to text be on the left side as it is now and icon on the right side, so text on the left corner of the container and icon on the right corner, inside corner i write this code:</p>
<p><code> i { margin-left: 95px; }</code></p>
<p>but when margin left has higher pixels icon goes bellow text, they are not in the same line, how to create bigger space but still make those 2 elements into one line?</p>
|
[
{
"answer_id": 74544503,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": 1,
"selected": true,
"text": "display: flex; \njustify-content: space-between;\n"
},
{
"answer_id": 74544528,
"author": "Abdul Samad",
"author_id": 3143678,
"author_profile": "https://Stackoverflow.com/users/3143678",
"pm_score": 0,
"selected": false,
"text": ".container{\n display: flex;\n justify-content: space-between;\n width: 100%;\n\n}\n"
},
{
"answer_id": 74544530,
"author": "Azhar Parvaiz",
"author_id": 9540058,
"author_profile": "https://Stackoverflow.com/users/9540058",
"pm_score": 1,
"selected": false,
"text": "display: flex; justify-content: space-between;"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19576858/"
] |
74,544,433
|
<p>I have created a model Agent that is in a OneToOne relation with the User model.
I managed to create a form where I can edit the Agent(user) details, but I would like to populate the form with the existing details of the model(Agent/user).
Found something similar <a href="https://stackoverflow.com/questions/35287445/accessing-field-from-onetoone-field-in-modelform">here</a> but it is not using Class based views.</p>
<p>models.py -></p>
<pre><code>from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_organisor = models.BooleanField(default=True)
is_agent = models.BooleanField(default=False)
class Agent(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
def __str__(self):
return self.user.email
</code></pre>
<p>forms.py -></p>
<pre><code>from django import forms
from django.contrib.auth import get_user_model
User = get_user_model()
class AgentModelForm(forms.ModelForm):
class Meta:
model = User
fields = (
'email',
'username',
'first_name',
'last_name'
)
</code></pre>
<p>views.py -></p>
<pre><code>class AgentUpdateView(OrganisorAndLoginRequiredMixin,generic.UpdateView):
template_name = "agents/agent_update.html"
form_class = AgentModelForm
queryset = Agent.objects.all()
def get_success_url(self):
return reverse("agents:agent_list")
</code></pre>
|
[
{
"answer_id": 74544503,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": 1,
"selected": true,
"text": "display: flex; \njustify-content: space-between;\n"
},
{
"answer_id": 74544528,
"author": "Abdul Samad",
"author_id": 3143678,
"author_profile": "https://Stackoverflow.com/users/3143678",
"pm_score": 0,
"selected": false,
"text": ".container{\n display: flex;\n justify-content: space-between;\n width: 100%;\n\n}\n"
},
{
"answer_id": 74544530,
"author": "Azhar Parvaiz",
"author_id": 9540058,
"author_profile": "https://Stackoverflow.com/users/9540058",
"pm_score": 1,
"selected": false,
"text": "display: flex; justify-content: space-between;"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12036940/"
] |
74,544,437
|
<p>I want to add strings to all of my logs to achieve this, I am planing to use aop but I coldnt declare point cut for all of my loggger objects. I am using slf4j logger here is an example log in a class</p>
<pre class="lang-java prettyprint-override"><code>Logger logger = LoggerFactory.getLogger(InterviewService.class);
logger.error(ex.getMessage(),ex);
</code></pre>
<p><a href="https://i.stack.imgur.com/bnNUb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bnNUb.png" alt="enter image description here" /></a></p>
<p>I am trying to intercept logger in the ss so before printing that log I can alter arguments in message and add my text
I change my code little bit currently I can catch thrown exceptions but still cant intercept logger.error("some error log") messages in aspect method.</p>
<pre class="lang-java prettyprint-override"><code>@Pointcut("within(org.apache.logging.log4j.*)")
public void logPointcut() {}
@Pointcut("within(*..Log4jLogger.*)")
public void logPointcuts() {}
@Pointcut("execution(* *.error(*))")
public void logPointcutsMethod() {}
@Pointcut("within(*.error)")
public void logPointcutsMethodw() {}
@Around("logPointcutsMethod() || logPointcuts() || logPointcut() || logPointcutsMethodw()")
public Object logError(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = joinPoint.proceed();
String user = "";
if (state)
user = getUser();
logger.error(
"Exception in {} User :{}.{}() with cause = {}",
joinPoint.getSignature().getDeclaringTypeName(),
user,
joinPoint.getSignature().getName()
);
return result;
}
</code></pre>
<p>To summarise, I want to create pointcut for every logger.error call so I can add my string to every message</p>
|
[
{
"answer_id": 74571372,
"author": "kriegaex",
"author_id": 1082681,
"author_profile": "https://Stackoverflow.com/users/1082681",
"pm_score": 1,
"selected": false,
"text": "package de.scrum_master.app;\n\nimport org.apache.log4j.BasicConfigurator;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Application {\n private static final Logger logger = LoggerFactory.getLogger(Application.class);\n\n public static void main(String[] args) {\n BasicConfigurator.configure();\n logger.info(\"Hello Slf4j\");\n logger.error(\"uh-oh\", new Exception(\"oops!\"));\n logger.error(\"WTF dude?!?\");\n }\n}\n package de.scrum_master.aspect;\n\nimport org.aspectj.lang.ProceedingJoinPoint;\nimport org.aspectj.lang.annotation.Around;\nimport org.aspectj.lang.annotation.Aspect;\n\n@Aspect\npublic class LogEnhancerAspect {\n @Around(\"execution(void org.slf4j.Logger.error(String, ..)) && args(msg, ..)\")\n public void formatMessageLog(String msg, ProceedingJoinPoint joinPoint) throws Throwable {\n Object[] args = joinPoint.getArgs();\n args[0] = \"[MY PREFIX] \" + msg;\n joinPoint.proceed(args);\n }\n}\n 0 [main] INFO de.scrum_master.app.Application - Hello Slf4j\n7 [main] ERROR de.scrum_master.app.Application - [MY PREFIX] uh-oh\njava.lang.Exception: oops!\n at de.scrum_master.app.Application.main(Application.java:13)\n8 [main] ERROR de.scrum_master.app.Application - [MY PREFIX] WTF dude?!?\n Logger.error(..) String error(String) error(String, Throwable) call() execution() within(my.base.pkg..*) && call(void org.slf4j.Logger.error(String, ..)) && args(msg, ..)"
},
{
"answer_id": 74573008,
"author": "cihad",
"author_id": 1969611,
"author_profile": "https://Stackoverflow.com/users/1969611",
"pm_score": 0,
"selected": false,
"text": " @Pointcut(\"within(com.saas.contoller.*)\")\n public void applicationPackagePointcut() {\n // Method is empty as this is just a Pointcut, the implementations are in the advices.\n }\n /**\n * Pointcut that matches all Spring beans in the application's main packages.\n */\n @Pointcut(\"within(com.saas.service.*)\")\n public void servicePackagePointcut() {\n // Method is empty as this is just a Pointcut, the implementations are in the advices.\n }\n\n @Around(\"applicationPackagePointcut() && springBeanPointcut()\")\n public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {\n String user = \"\";\n if (state) {\n user = getUser();\n }\n ThreadContext.put(\"user\",user);\n Object result = joinPoint.proceed();\n ThreadContext.remove(\"user\");\n <Property name=\"LOG_PATTERN_CONSOLE\" >\n %d{yyyy-MM-dd HH:mm:ss.SSS} - user:%X{user} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue, TRACE=cyan} %style{[%15.15t]}{magenta} : %style{%-40.40c{1.}}{cyan} : %m%n%ex\n </Property>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1969611/"
] |
74,544,443
|
<p>Passkeys in the Google Password Manager are always end-to-end encrypted: When a passkey is backed up, its private key is uploaded only in its encrypted form using an encryption key that is only accessible on the user's own devices</p>
<p>Question: are this passkey protection keys unique to end user devices or to user accounts?</p>
<p>just a question for further understanding the concept of protection user's passkeys from unauthorized access while these passkeys are backed up to Google systems</p>
|
[
{
"answer_id": 74571372,
"author": "kriegaex",
"author_id": 1082681,
"author_profile": "https://Stackoverflow.com/users/1082681",
"pm_score": 1,
"selected": false,
"text": "package de.scrum_master.app;\n\nimport org.apache.log4j.BasicConfigurator;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class Application {\n private static final Logger logger = LoggerFactory.getLogger(Application.class);\n\n public static void main(String[] args) {\n BasicConfigurator.configure();\n logger.info(\"Hello Slf4j\");\n logger.error(\"uh-oh\", new Exception(\"oops!\"));\n logger.error(\"WTF dude?!?\");\n }\n}\n package de.scrum_master.aspect;\n\nimport org.aspectj.lang.ProceedingJoinPoint;\nimport org.aspectj.lang.annotation.Around;\nimport org.aspectj.lang.annotation.Aspect;\n\n@Aspect\npublic class LogEnhancerAspect {\n @Around(\"execution(void org.slf4j.Logger.error(String, ..)) && args(msg, ..)\")\n public void formatMessageLog(String msg, ProceedingJoinPoint joinPoint) throws Throwable {\n Object[] args = joinPoint.getArgs();\n args[0] = \"[MY PREFIX] \" + msg;\n joinPoint.proceed(args);\n }\n}\n 0 [main] INFO de.scrum_master.app.Application - Hello Slf4j\n7 [main] ERROR de.scrum_master.app.Application - [MY PREFIX] uh-oh\njava.lang.Exception: oops!\n at de.scrum_master.app.Application.main(Application.java:13)\n8 [main] ERROR de.scrum_master.app.Application - [MY PREFIX] WTF dude?!?\n Logger.error(..) String error(String) error(String, Throwable) call() execution() within(my.base.pkg..*) && call(void org.slf4j.Logger.error(String, ..)) && args(msg, ..)"
},
{
"answer_id": 74573008,
"author": "cihad",
"author_id": 1969611,
"author_profile": "https://Stackoverflow.com/users/1969611",
"pm_score": 0,
"selected": false,
"text": " @Pointcut(\"within(com.saas.contoller.*)\")\n public void applicationPackagePointcut() {\n // Method is empty as this is just a Pointcut, the implementations are in the advices.\n }\n /**\n * Pointcut that matches all Spring beans in the application's main packages.\n */\n @Pointcut(\"within(com.saas.service.*)\")\n public void servicePackagePointcut() {\n // Method is empty as this is just a Pointcut, the implementations are in the advices.\n }\n\n @Around(\"applicationPackagePointcut() && springBeanPointcut()\")\n public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {\n String user = \"\";\n if (state) {\n user = getUser();\n }\n ThreadContext.put(\"user\",user);\n Object result = joinPoint.proceed();\n ThreadContext.remove(\"user\");\n <Property name=\"LOG_PATTERN_CONSOLE\" >\n %d{yyyy-MM-dd HH:mm:ss.SSS} - user:%X{user} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue, TRACE=cyan} %style{[%15.15t]}{magenta} : %style{%-40.40c{1.}}{cyan} : %m%n%ex\n </Property>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580416/"
] |
74,544,485
|
<p>I want to implement a function <code>get_bit(value,pos)</code> so that it returns the value of the bit (0 or 1) from the unsigned integer value at index pos. <code>value</code> is an integer.</p>
<p>for example, if value = 5 (0101 in binary) then get_bit(5,0) = 1 and then if get_bit(5,1) = 0 and then get_bit(5,2)=1 and so on.</p>
<p>So far what I tried to do is:</p>
<pre><code>#include <stdio.h>
#include <math.h>
long decimalToBinary(int decimalnum)
{
long binarynum = 0;
int rem, temp = 1;
while (decimalnum!=0)
{
rem = decimalnum%2;
decimalnum = decimalnum / 2;
binarynum = binarynum + rem*temp;
temp = temp * 10;
}
return binarynum;
}
const char * get_bit(int value, int pos) {
char result[99];
long bin_val = decimalToBinary(value);
sprintf(result, "%f", bin_val);
return result[pos];
}
int main() {
printf( get_bit(5,0) );
return 0;
}
</code></pre>
<p>but it is showing segmentation error. Can anybody help to make it work?</p>
|
[
{
"answer_id": 74544622,
"author": "carce-bo",
"author_id": 18101070,
"author_profile": "https://Stackoverflow.com/users/18101070",
"pm_score": 2,
"selected": true,
"text": "get_bit result[pos] char char * printf #include <stdio.h>\n#include <math.h>\n\nlong decimalToBinary(int decimalnum)\n{\n long binarynum = 0;\n int rem, temp = 1;\n\n while (decimalnum!=0)\n {\n rem = decimalnum%2;\n decimalnum = decimalnum / 2;\n binarynum = binarynum + rem*temp;\n temp = temp * 10;\n }\n return binarynum;\n}\n\nconst char get_bit(int value, int pos) {\n char result[99];\n long bin_val = decimalToBinary(value);\n sprintf(result, \"%ld\", bin_val);\n return result[pos];\n}\n\nint main() {\n int val = 5;\n printf(\"val(%d) is : 0b%c%c%c\\n\", val, get_bit(val,0), get_bit(val,1), get_bit(val,2));\n return 0;\n}\n val(5) is : 0b101\n"
},
{
"answer_id": 74544751,
"author": "Stoica Mircea",
"author_id": 5583881,
"author_profile": "https://Stackoverflow.com/users/5583881",
"pm_score": 0,
"selected": false,
"text": "char get_bit(int value, int pos) {\n long bin_val = decimalToBinary(value);\n cout << \"binary value = \" << bin_val << endl;\n \n for(int i=0; i<pos; i++)\n bin_val /= 10;\n return bin_val%10;\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9550867/"
] |
74,544,491
|
<p>So, I am making a small text based game and this is part of a lootbox after beating a dungeon. It's for one of the 5 items you can possibly get out of the lootbox. It checks if inventoryslot 1 is free. If not, it checks if inventoryslot 2 is free... etc etc. This results in giant if elseif statements and makes the code really messy. Are there any alternatives I can use instead of this?</p>
<pre><code>if (whatitem == 1)
{
Console.WriteLine("You got " + item5 + "(10%)");
if (invitem1 == "")
{
invitem1 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 1");
}
else if (invitem2 == "")
{
invitem2 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 2");
}
else if (invitem3 == "")
{
invitem3 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 3");
}
else if (invitem4 == "")
{
invitem4 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 4");
}
else if (invitem5 == "")
{
invitem5 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 5");
}
else if (invitem6 == "")
{
invitem6 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 6");
}
else if (invitem7 == "")
{
invitem7 = item5;
Console.Write("The item has been added to your inventory");
Console.WriteLine(" Added to slot 7");
}
else
{
Console.WriteLine("No space, Reward deleted");
}
Console.WriteLine("Press ENTER to proceed");
}
</code></pre>
<p>I tried searching for solutions on google and so on, but I feel that this problem is very specific and I couldn't find a solid answer.</p>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580393/"
] |
74,544,520
|
<p><code>ServiceCategory</code> has many <code>Service</code></p>
<pre><code>public function services(): HasMany {
return $this->hasMany(Service::class, 'category_id');
}
</code></pre>
<p><code>Service</code> has many <code>Price</code></p>
<pre><code>public function prices(): HasMany {
return $this->hasMany(ServicePrice::class, 'service_id');
}
</code></pre>
<p>Let's say <code>prices</code> table has a <code>price_value</code> column, how do I get the lowest and highest price?</p>
<p>I used <a href="https://stackoverflow.com/a/25628830">this method</a> but every time the query returns a list of <code>ServiceCategory</code> instead of a list of <code>Price</code>.</p>
<p>What I tried:</p>
<pre><code>ServiceCategory::with('services.prices')->get();
// Or Even
ServiceCategory::first()->with('services.prices')->get();
</code></pre>
<p>And:</p>
<pre><code>ServiceCategory::has('services')->with('services:category_id')->with(['services.prices' => function ($q) {
$q->select('price');
}])->get();
</code></pre>
<p>Still no chance to only return a collection of <code>Price</code></p>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6679820/"
] |
74,544,532
|
<p>I am trying to setup a picker, simple. I am successfully fetching an array of projects from firebase and populating the picker with the names of the projects. The problem that I am having is that I need to get the project id when I click the list but it's not doing anything after I click the option that I want. I tried to run it in a simulator and also on my iPhone and nothing happens after I make the selection. I am pretty sure I am not updating the picker and thus I am not updating the variable with the selected project id. I tried using the .onChange on the picker but nothing happens.</p>
<pre><code>import SwiftUI
struct NewProjectView: View {
@ObservedObject var viewModel = ProjectViewModel()
@ObservedObject var clientViewModel = ClientFeedViewModel()
@Environment (\.dismiss) var dismiss
@State var projectName: String = "s"
var clientNameIsEmpty: Bool {
if projectName.count < 3 {
return true
} else {
return false
}
}
var clients: [Client] {
return clientViewModel.clients
}
@State var selectedClient: String = ""
var body: some View {
NavigationView {
VStack {
Picker("", selection: $selectedClient) {
ForEach(clients, id:\.self) {
Text($0.clientName)
//I need to exctract the project id so I can pass it on
}
}
.pickerStyle(.menu)
CustomTextField(text: $projectName, placeholder: Text("Client Name"), imageName: "person.text.rectangle")
.padding()
.background(Color("JUMP_COLOR")
.opacity(0.75)
)
.cornerRadius(10)
.padding(.horizontal, 40)
Text("Name must contain more than 3 characters")
.font(.system(.subheadline))
.foregroundColor(.gray.opacity(0.3))
.padding(.top, 30)
.toolbar {
ToolbarItem(placement: .navigationBarLeading, content: {
Button(action: {
dismiss()
}, label: {
Text("Cancel")
})
})
ToolbarItem(placement: .navigationBarTrailing , content: {
Button(action: {
viewModel.newProject(name: projectName)
dismiss()
}, label: {
Text("Save")
})
.disabled(clientNameIsEmpty)
})
}
}
}
.presentationDetents([.height(400)])
//.presentationDetents([.medium])
.presentationDragIndicator(.visible)
}
}
struct NewProjectView_Previews: PreviewProvider {
static var previews: some View {
NewProjectView()
}
}
</code></pre>
<p>Here is the picker populated with the foo data: <a href="https://i.stack.imgur.com/26MUD.png" rel="nofollow noreferrer">picker</a></p>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14534481/"
] |
74,544,557
|
<p>i dont kow ehy my programs dont run.
i am trying to reverse my array through user defined function.
i can give an input but cannot find out the answer.</p>
<pre><code>import java.util.*;
public class reverseanarray{
public static int reversea(int array[]){
int swap;
int j=array.length;
for(int i=0;i<array.length/2;i++){
swap=array[i];
array[i]=array[j];
array[j]=swap;
j--;
}
return j;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//System.out.println();
//int a = sc.nextInt();
System.out.println("please input the length");
int y=sc.nextInt();//INPUT OF LENGTH OF ARRAY
int arr[]=new int[y];
//INPUT ARRAY
for(int r=0;r<arr.length;r++){
System.out.println("please input the "+r+" index value");
arr[r]=sc.nextInt();
}
System.out.println(reversea(arr));
for(int i=0;i<y;i++){
System.out.println(arr[i]);
}
}
}
</code></pre>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20458153/"
] |
74,544,582
|
<p>I have the following component where I want to change the color depending on user type , issue is when I use gradient ... the color get stops from transitioning , if I use simple colors like bule , red , green .... then it works but at the current state in code the colors changes but whiteout the slowed transition ... how to solve this ?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Home: React.FC = () => {
const _authContext = useContext(authContext);
const hexUserArr = ['linear-gradient(360deg, #fe6b8b 30%, #7DF9FF 70%)'];
const hexAdminArr = ['linear-gradient(360deg, #dfe566 30%, #7DF334 70%)'];
return (
<div
style={{
minHeight: '100vh',
marginTop: 0,
marginBottom: -50,
justifyContent: 'center',
background: _authContext.starterUserType === 'admin' ? hexAdminArr[0] : hexUserArr[0],
transition: 'background 10s ease',
}}
>
</div>
);
};
export default Home;</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15357136/"
] |
74,544,599
|
<p>I want to display on a page if the logged in user has ordered a specific product.</p>
<p>I can't find a function in WC_Order that would allow me to get this information.</p>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20571736/"
] |
74,544,609
|
<p>I want to detect when a string is a quote of some kind. For my use case a string can be classed as a quote if it starts with a quotation mark, which will enable me to mark the string as a quote whilst it is being typed out.</p>
<h3>Test cases</h3>
<p>✅ <code>"I am a quote</code><br />
✅ <code>'I am a quote</code><br />
✅ <code>“I am a quote</code><br />
✅ <code> “I am a quote </code><br />
❌ <code>I am not a quote</code><br />
❌ <code>This isn't a quote</code></p>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827129/"
] |
74,544,643
|
<p>I am creating a do-while-loop that prints start to end. The program checks different types of numbers to get, and whenever it's small to big number it checks out but not when it's big to small. Anyone interested to help a stupid student?</p>
<p>This is what my program looks like, my teacher told me " The fact that a do-always gonna do an iteration should mean that the task isn't possible to do with only a do-while, try adding something to your loop" but I can't seem to figure it out.</p>
<pre><code>public static void runLoop(int start, int end) {
do {
System.out.print( start );
start++;
}
} while (start <= end );
}
</code></pre>
|
[
{
"answer_id": 74545404,
"author": "CthenB",
"author_id": 1885199,
"author_profile": "https://Stackoverflow.com/users/1885199",
"pm_score": 1,
"selected": false,
"text": "public class Program\n{\n public static void Main(string[] args)\n {\n var inventory = new Inventory();\n var items = new List<Item>();\n\n foreach (var item in items)\n {\n inventory.AddItemToInventory(item).\n }\n }\n}\n\npublic class Item\n{\n public string Name { get; set: }\n}\n\npublic class Inventory\n{\n public int Slots => 4\n\n public List<Item> SlotsInUse { get; set; } = new List<Item>();\n\n public bool AddItemToInventory(Item item)\n {\n if (SlotsInUse.Count() < Slots)\n {\n Console.WriteLine($\"{item.Name} added to inventory.\";\n SlotsInUse.Add(item);\n }\n else\n {\n Console.WriteLine(\"Your inventory is full!\"\n }\n }\n}\n"
},
{
"answer_id": 74546034,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 0,
"selected": false,
"text": "internal class Inventory\n{\n private readonly List<string> _inventory;\n private readonly uint _maximumInventorySize;\n\n public Inventory(uint maximumSize)\n {\n if (maximumSize < 1)\n throw new ArgumentOutOfRangeException(nameof(maximumSize), \"Inventory must hold at least one item\");\n\n _maximumInventorySize = maximumSize;\n _inventory = new List<string>();\n }\n\n public bool AddItem(string itemName)\n {\n if (_inventory.Count == _maximumInventorySize)\n return false;\n\n _inventory.Add(itemName);\n return true;\n }\n\n public bool RemoveItem(string itemName)\n {\n if (!_inventory.Contains(itemName))\n return false;\n\n _inventory.Remove(itemName);\n return true;\n }\n\n public override string ToString()\n {\n return _inventory.Count == 0\n ? \"Nothing\"\n : string.Join(\", \", _inventory);\n }\n}\n internal static class Program\n{\n public static void Main()\n {\n const int inventorySize = 7;\n var inventory = new Inventory(inventorySize);\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Attempt to overfill the inventory to get the 'No space' message.\n for (var item = 0; item < inventorySize + 1; item++)\n {\n var itemName = $\"Item{item + 1}\";\n if (inventory.AddItem(itemName))\n Console.Write($\"{itemName} has been added to your inventory\\n\");\n else\n Console.WriteLine($\"No space for {itemName}, reward deleted\");\n }\n\n // Display the inventory.\n Console.WriteLine($\"Your inventory contains: {inventory}.\");\n\n // Remove odd numbered inventory items.\n for (var item = 0; item < inventorySize; item += 2)\n {\n var itemName = $\"Item{item + 1}\";\n inventory.RemoveItem(itemName);\n }\n\n // Display the inventory.\n Console.WriteLine($\"After removing odd numbered items, your inventory contains: {inventory}.\");\n\n Console.WriteLine(\"Press ENTER to proceed\");\n Console.ReadLine();\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580483/"
] |
74,544,646
|
<p>I have 5 criteria in cell B2 to B6:</p>
<p>I want to return the criteria that is the highest risk (i.e. the lowest score), but this also needs to be based on rank. Meaning, criteria 1 is prioritized over criteria 2 if their scores are the same, but if criteria 2 has a lower score than 1, it is selected. This trend remains true throughout.</p>
<p>So overall, the criteria with the lowest score is selected, but if multiple criteria have the same score then the one with the highest rank is selected. See example below - criteria 3 is selected:</p>
<p><a href="https://i.stack.imgur.com/1BCQU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1BCQU.png" alt="enter image description here" /></a></p>
<p>I want to automate this selection process as the scores will be constantly changing. Can I use formulas for this?</p>
|
[
{
"answer_id": 74545395,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=LET(d,A2:C6,\nrank,INDEX(d,,1), score,INDEX(d,,3),\nsortByRankScore,SORTBY(d,score,1,rank,1),\nINDEX(sortByRankScore,1,2))\n"
},
{
"answer_id": 74545451,
"author": "Nick",
"author_id": 11995192,
"author_profile": "https://Stackoverflow.com/users/11995192",
"pm_score": 0,
"selected": false,
"text": "=index(B2:B6;match(small(C2:C6;1);C2:C6;0))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17843146/"
] |
74,544,653
|
<p>I am trying place an HTML element next to the end of the first line of a heading.
For a better understanding, I took screenshots of what it looks like for now and what it should look like.</p>
<p>What it looks like:
<img src="https://i.stack.imgur.com/uyLy1.png" alt="What it looks like" /></p>
<p>What it should look like:
<img src="https://i.stack.imgur.com/S7xZu.png" alt="What it should look like" /></p>
<p>As you can see, I used the <code>::first-line</code> pseudo-selector to change the background of the first line of the title in red.</p>
<p>So far I have tried to add a <code>::after</code> to the <code>::first-line</code> but there are two issues. First, I did not manage to display a text content in the <code>::after</code>. Second, you can't add html content to both <code>::before</code> and <code>::after</code> so it was pointless.</p>
<p>You should know that the "sunshines" are not an image but an actual html element :</p>
<pre><code>
<div className={css.container}>
<div className={css.shine1}></div>
<div className={css.shine2}></div>
<div className={css.shine3}></div>
</div>
</code></pre>
<pre><code>.container {
position: absolute;
display: inline;
top: 20px;
right: 5px;
div {
position: absolute;
height: 5px;
border-radius: 5px;
background-color: $mainColor;
transform-origin: bottom left;
}
.shine1 {
width: 26px;
transform: rotate(-95deg) translate(20px, 5px);
}
.shine2 {
width: 32px;
transform: rotate(-45deg) translate(20px);
}
.shine3 {
width: 26px;
transform: rotate(0deg) translate(15px);
}
}
</code></pre>
<p>This is JSX with scss modules. But basically the same syntax as HTML/CSS.</p>
<p>Do you have any idea on how to do it, I guess it is possible since the css is capable to know where the end of the line is since I can change the background.</p>
|
[
{
"answer_id": 74545395,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=LET(d,A2:C6,\nrank,INDEX(d,,1), score,INDEX(d,,3),\nsortByRankScore,SORTBY(d,score,1,rank,1),\nINDEX(sortByRankScore,1,2))\n"
},
{
"answer_id": 74545451,
"author": "Nick",
"author_id": 11995192,
"author_profile": "https://Stackoverflow.com/users/11995192",
"pm_score": 0,
"selected": false,
"text": "=index(B2:B6;match(small(C2:C6;1);C2:C6;0))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19555540/"
] |
74,544,668
|
<p>I've got an error</p>
<p><code>Caused by: org.h2.jdbc.JdbcSQLDataException: Hexadecimal string contains non-hex character: "SWEDISH_MARKET"; SQL statement:</code></p>
<p>when I pass an enum as parameter to query</p>
<p>Entity has this enum as field.</p>
<p>Field has bellow annotations</p>
<pre><code>@Column(name = "market", nullable = false)
@Enumerated(EnumType.STRING)
private Market type;
</code></pre>
<p>query:</p>
<pre><code> @Query(value = "SELECT count(*) " +
"FROM Statements statements WHERE " +
"market = :market",
nativeQuery = true)
long countStatements(@Param("licenseMarket") Market market);
</code></pre>
<p>Previously everything was parsed to String and casted in postgres <code>market = (cast :market as text)</code></p>
<p>Invoking countStatements(Market.SWEDISH_MARKET) throws the exception</p>
|
[
{
"answer_id": 74545395,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=LET(d,A2:C6,\nrank,INDEX(d,,1), score,INDEX(d,,3),\nsortByRankScore,SORTBY(d,score,1,rank,1),\nINDEX(sortByRankScore,1,2))\n"
},
{
"answer_id": 74545451,
"author": "Nick",
"author_id": 11995192,
"author_profile": "https://Stackoverflow.com/users/11995192",
"pm_score": 0,
"selected": false,
"text": "=index(B2:B6;match(small(C2:C6;1);C2:C6;0))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9304291/"
] |
74,544,713
|
<p>I have a list with the following values:</p>
<pre><code>const myList = [True, False, False]
</code></pre>
<p>With <strong>myList.length</strong> I get the value <strong>3</strong>.</p>
<p>Now I want the length of the list with all <strong>False</strong> values.</p>
<p>How can I return the length with a condition?</p>
|
[
{
"answer_id": 74544738,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "Array.filter() let len = myList.filter(i => !i).length\n const myList1 = [true, false, false]\nlet len1 = myList1.filter(i => !i).length\nconsole.log(len1)\n\nconst myList2 = ['True', 'False', 'False']\nlet len2 = myList2.map(i => i.toLowerCase() === 'true').filter(i => !i).length\nconsole.log(len2)"
},
{
"answer_id": 74544746,
"author": "voidbrain",
"author_id": 1000137,
"author_profile": "https://Stackoverflow.com/users/1000137",
"pm_score": 3,
"selected": true,
"text": "const myList = [True, False, False].filter(el => el === false)\nconsole.log(myList.length)\n"
},
{
"answer_id": 74544752,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n True = true,\n False = false,\n getCount = (array, value) => array.reduce((t, v) => t + (v === value), 0),\n myList = [True, False, False];\n\nconsole.log(getCount(myList, False));"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346503/"
] |
74,544,720
|
<p>Please help me to fix this issue. Thank you!</p>
<p>I am working on a <strong>Grails-5.2.4</strong> project with <strong>Java 1.8</strong>. Class Loader is not working as expected.</p>
<p><strong>I am getting class cast exception for the following piece of code.</strong></p>
<pre><code>def index() {
Profile profile = getClass().classLoader.loadClass("centaur.demo.Profile") as Profile
}
</code></pre>
<p><strong>Below is the exception details:</strong></p>
<pre><code>Caused by: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class centaur.demo.Profile' with class 'java.lang.Class' to class 'centaur.demo.Profile'
at org.grails.web.converters.ConverterUtil.invokeOriginalAsTypeMethod(ConverterUtil.java:147)
at org.grails.web.converters.ConvertersExtension.asType(ConvertersExtension.groovy:56)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at centaur.demo.IndexController.index(IndexController.groovy:10)
... 13 common frames omitted
</code></pre>
<p><a href="https://i.stack.imgur.com/epdsa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/epdsa.png" alt="enter image description here" /></a></p>
<p>Expected behavior:</p>
<p>The line below should return an object of class Profile.</p>
<pre><code>getClass().classLoader.loadClass("centaur.demo.Profile")
</code></pre>
<p>This is working fine with Grails 3.3.9.</p>
|
[
{
"answer_id": 74544738,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "Array.filter() let len = myList.filter(i => !i).length\n const myList1 = [true, false, false]\nlet len1 = myList1.filter(i => !i).length\nconsole.log(len1)\n\nconst myList2 = ['True', 'False', 'False']\nlet len2 = myList2.map(i => i.toLowerCase() === 'true').filter(i => !i).length\nconsole.log(len2)"
},
{
"answer_id": 74544746,
"author": "voidbrain",
"author_id": 1000137,
"author_profile": "https://Stackoverflow.com/users/1000137",
"pm_score": 3,
"selected": true,
"text": "const myList = [True, False, False].filter(el => el === false)\nconsole.log(myList.length)\n"
},
{
"answer_id": 74544752,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 1,
"selected": false,
"text": "const\n True = true,\n False = false,\n getCount = (array, value) => array.reduce((t, v) => t + (v === value), 0),\n myList = [True, False, False];\n\nconsole.log(getCount(myList, False));"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005336/"
] |
74,544,727
|
<p>How can I get the column types of a Julia <code>DataFrame</code>?</p>
<pre><code>using DataFrames
df = DataFrame(a = 1:4, b = ["a", "b", "c", "d"])
4×2 DataFrame
Row │ a b
│ Int64 String
─────┼───────────────
1 │ 1 a
2 │ 2 b
3 │ 3 c
4 │ 4 d
</code></pre>
|
[
{
"answer_id": 74544728,
"author": "Georgery",
"author_id": 7210250,
"author_profile": "https://Stackoverflow.com/users/7210250",
"pm_score": 2,
"selected": false,
"text": "eltype.(eachcol(df))\n df |> eachcol .|> eltype\n\n2-element Vector{DataType}:\n Int64\n String\n df |> eachcol .|> typeof\n\n2-element Vector{DataType}:\n Vector{Int64} (alias for Array{Int64, 1})\n Vector{String} (alias for Array{String, 1})\n"
},
{
"answer_id": 74544819,
"author": "Bogumił Kamiński",
"author_id": 1269567,
"author_profile": "https://Stackoverflow.com/users/1269567",
"pm_score": 3,
"selected": false,
"text": "julia> mapcols(eltype, df)\n1×2 DataFrame\n Row │ a b\n │ DataType DataType\n─────┼────────────────────\n 1 │ Int64 String\n\njulia> mapcols(typeof, df)\n1×2 DataFrame\n Row │ a b\n │ DataType DataType\n─────┼───────────────────────────────\n 1 │ Vector{Int64} Vector{String}\n\njulia> describe(df, :eltype)\n2×2 DataFrame\n Row │ variable eltype\n │ Symbol DataType\n─────┼────────────────────\n 1 │ a Int64\n 2 │ b String\n describe Missing"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7210250/"
] |
74,544,742
|
<p>I want to display names of cities according to state/region selected on Checkout page. I have inserted cities and regions in table via impex. Now I want to fetch the cityname according to regionisocode.</p>
<p>I have created custom facade and defined method getCity(final String city) and getCity(final String regionIso, final String cityIso). Declared bean in spring.xml. I have also created interface GrocerymateCheckoutService Please help me with writing its logic for implementation. Attaching class file for reference please help with logic in methods.What will be the code in below picture?</p>
<p><a href="https://i.stack.imgur.com/2KZ7K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2KZ7K.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74544728,
"author": "Georgery",
"author_id": 7210250,
"author_profile": "https://Stackoverflow.com/users/7210250",
"pm_score": 2,
"selected": false,
"text": "eltype.(eachcol(df))\n df |> eachcol .|> eltype\n\n2-element Vector{DataType}:\n Int64\n String\n df |> eachcol .|> typeof\n\n2-element Vector{DataType}:\n Vector{Int64} (alias for Array{Int64, 1})\n Vector{String} (alias for Array{String, 1})\n"
},
{
"answer_id": 74544819,
"author": "Bogumił Kamiński",
"author_id": 1269567,
"author_profile": "https://Stackoverflow.com/users/1269567",
"pm_score": 3,
"selected": false,
"text": "julia> mapcols(eltype, df)\n1×2 DataFrame\n Row │ a b\n │ DataType DataType\n─────┼────────────────────\n 1 │ Int64 String\n\njulia> mapcols(typeof, df)\n1×2 DataFrame\n Row │ a b\n │ DataType DataType\n─────┼───────────────────────────────\n 1 │ Vector{Int64} Vector{String}\n\njulia> describe(df, :eltype)\n2×2 DataFrame\n Row │ variable eltype\n │ Symbol DataType\n─────┼────────────────────\n 1 │ a Int64\n 2 │ b String\n describe Missing"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301790/"
] |
74,544,759
|
<p>I have a dataframe:</p>
<pre><code>df = C1 A1. A2. A3. Type
A 1. 5. 2. AG
A 7. 3. 8. SC
</code></pre>
<p>And I want to create:</p>
<pre><code>df = C1 A1_AG A1_SC A2_AG A2_SC
A 1. 7. 5. 3
</code></pre>
<p>How can it be done?</p>
|
[
{
"answer_id": 74544793,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 4,
"selected": true,
"text": "melt transpose (df.melt('Type')\n .assign(col=lambda d: d['Type']+'_'+d['variable'])\n .set_index('col')[['value']].T\n)\n col AG_A1 SC_A1 AG_A2 SC_A2 AG_A3 SC_A3\nvalue 1 7 5 3 2 8\n (df.melt(['C1', 'Type'])\n .assign(col=lambda d: d['Type']+'_'+d['variable'])\n .pivot(index=['C1'], columns='col', values='value')\n .reset_index()\n)\n col C1 AG_A1 AG_A2 AG_A3 SC_A1 SC_A2 SC_A3\n0 A 1 5 2 7 3 8\n"
},
{
"answer_id": 74544877,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "DataFrame.set_index DataFrame.unstack df = df.set_index(['C1','Type']).unstack()\ndf.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')\ndf = df.reset_index()\nprint (df)\n C1 A1_AG A1_SC A2_AG A2_SC A3_AG A3_SC\n0 A 1.0 7.0 5.0 3.0 2.0 8.0\n"
},
{
"answer_id": 74545154,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\ndf.pivot_wider(index = 'C1', names_from = 'Type')\n\n C1 A1_AG A1_SC A2_AG A2_SC A3_AG A3_SC\n0 A 1.0 7.0 5.0 3.0 2.0 8.0\n pivot result = df.pivot(index='C1', columns='Type')\nresult.columns = result.columns.map('_'.join)\nresult.reset_index()\n\n C1 A1_AG A1_SC A2_AG A2_SC A3_AG A3_SC\n0 A 1.0 7.0 5.0 3.0 2.0 8.0\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6057371/"
] |
74,544,760
|
<pre class="lang-py prettyprint-override"><code>keys = ['a', 'a' ,'a' ,'b' ,'b' ,'c']
values = [2, 4, 6, 6, 4 ,3]
</code></pre>
<p>Here it is guaranteed that <code>len(keys)==len(values)</code>. You can also assume that the keys are sorted. I would like to create a dictionary where the new values will be the average of the old values. If I do</p>
<pre class="lang-py prettyprint-override"><code>x = dict(zip(keys, values)) # {'a': 3, 'b': 4, 'c': 3}
</code></pre>
<p>Here the new values are not the average of the old values. I am expecting something like</p>
<pre class="lang-py prettyprint-override"><code>{'a': 4, 'b': 5, 'c': 3}
</code></pre>
<p>I can do this by summing over each of the old values, dividing those by the number of corresponding key occurrences, but I think there might be a more elegant solution to this. Any ideas would be appreciated!</p>
<p>Edit: By average values, I meant this: <code>b</code> occurred twice in <code>keys</code>, and the values were <code>6</code> and <code>4</code>. In the new dictionary, it will have the value <code>5</code>.</p>
|
[
{
"answer_id": 74544793,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 4,
"selected": true,
"text": "melt transpose (df.melt('Type')\n .assign(col=lambda d: d['Type']+'_'+d['variable'])\n .set_index('col')[['value']].T\n)\n col AG_A1 SC_A1 AG_A2 SC_A2 AG_A3 SC_A3\nvalue 1 7 5 3 2 8\n (df.melt(['C1', 'Type'])\n .assign(col=lambda d: d['Type']+'_'+d['variable'])\n .pivot(index=['C1'], columns='col', values='value')\n .reset_index()\n)\n col C1 AG_A1 AG_A2 AG_A3 SC_A1 SC_A2 SC_A3\n0 A 1 5 2 7 3 8\n"
},
{
"answer_id": 74544877,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "DataFrame.set_index DataFrame.unstack df = df.set_index(['C1','Type']).unstack()\ndf.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')\ndf = df.reset_index()\nprint (df)\n C1 A1_AG A1_SC A2_AG A2_SC A3_AG A3_SC\n0 A 1.0 7.0 5.0 3.0 2.0 8.0\n"
},
{
"answer_id": 74545154,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\ndf.pivot_wider(index = 'C1', names_from = 'Type')\n\n C1 A1_AG A1_SC A2_AG A2_SC A3_AG A3_SC\n0 A 1.0 7.0 5.0 3.0 2.0 8.0\n pivot result = df.pivot(index='C1', columns='Type')\nresult.columns = result.columns.map('_'.join)\nresult.reset_index()\n\n C1 A1_AG A1_SC A2_AG A2_SC A3_AG A3_SC\n0 A 1.0 7.0 5.0 3.0 2.0 8.0\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978724/"
] |
74,544,767
|
<p>I am trying to get the current day then getting the day before it, how can I get that date then convert it into a String?</p>
<pre><code>DateTime now = new DateTime.now();
</code></pre>
|
[
{
"answer_id": 74544817,
"author": "Risheek Mittal",
"author_id": 16973338,
"author_profile": "https://Stackoverflow.com/users/16973338",
"pm_score": 2,
"selected": true,
"text": " DateTime.now().subtract(Duration(days:1))\n"
},
{
"answer_id": 74544830,
"author": "VincentDR",
"author_id": 19540575,
"author_profile": "https://Stackoverflow.com/users/19540575",
"pm_score": 0,
"selected": false,
"text": "DateTime now = DateTime.now();\nDateTime nowMinus1Day = now. subtract(const Duration(days: 1));\nprint(nowMinus1Day.toIso8601String());\n"
},
{
"answer_id": 74544844,
"author": "Rahul Pandey",
"author_id": 17615801,
"author_profile": "https://Stackoverflow.com/users/17615801",
"pm_score": 0,
"selected": false,
"text": "var now = DateTime.now();\nvar startDate= now.subtract(Duration(days: 1));\nprint(startDate);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580264/"
] |
74,544,768
|
<p>I have 3 DF:</p>
<ol>
<li>"CAR" with 100 rows and 2 columns</li>
<li>"BIKE" with 60 rows and 3 columns</li>
<li>"ELENCO_DF" with 2 rows and 1 column</li>
</ol>
<p>ELENCO_DF is like that</p>
<p><strong>Nome</strong>
CAR
BIKE</p>
<p>Each element rappresent the "name" of the other DF</p>
<pre><code>#for each element of ELENCO_DF I would like to print the following
for (i in 1:nrow(ELENCO_DF)){
print(nrow(ELENCO_DF[i]))
}
#Thanks a lot in advance
</code></pre>
|
[
{
"answer_id": 74544817,
"author": "Risheek Mittal",
"author_id": 16973338,
"author_profile": "https://Stackoverflow.com/users/16973338",
"pm_score": 2,
"selected": true,
"text": " DateTime.now().subtract(Duration(days:1))\n"
},
{
"answer_id": 74544830,
"author": "VincentDR",
"author_id": 19540575,
"author_profile": "https://Stackoverflow.com/users/19540575",
"pm_score": 0,
"selected": false,
"text": "DateTime now = DateTime.now();\nDateTime nowMinus1Day = now. subtract(const Duration(days: 1));\nprint(nowMinus1Day.toIso8601String());\n"
},
{
"answer_id": 74544844,
"author": "Rahul Pandey",
"author_id": 17615801,
"author_profile": "https://Stackoverflow.com/users/17615801",
"pm_score": 0,
"selected": false,
"text": "var now = DateTime.now();\nvar startDate= now.subtract(Duration(days: 1));\nprint(startDate);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19511376/"
] |
74,544,778
|
<p>Question 1: I have a non useful window that appears when using tkinter in spyder.
Any solution for this issue ?</p>
<p><a href="https://i.stack.imgur.com/Rw5Gf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rw5Gf.png" alt="enter image description here" /></a></p>
<p>Question 2: Why there is a warning message on 'from tkinter import *' ?</p>
<p>Code:</p>
<pre><code>from tkinter import *
from tkinter.simpledialog import askstring
from tkinter import messagebox
box = Tk()
name = askstring('Name','What is your name?')
messagebox.showinfo('Hello!','Hi, {}'.format(name))
box.mainloop()
</code></pre>
|
[
{
"answer_id": 74544953,
"author": "Tranbi",
"author_id": 13525512,
"author_profile": "https://Stackoverflow.com/users/13525512",
"pm_score": 1,
"selected": false,
"text": "box messagebox box import tkinter as tk\nfrom tkinter.simpledialog import askstring\n\nname = askstring('Name','What is your name?')\ntk.messagebox.showinfo('Hello!','Hi, {}'.format(name))\n"
},
{
"answer_id": 74544975,
"author": "Andreja Milosavljevic",
"author_id": 18187699,
"author_profile": "https://Stackoverflow.com/users/18187699",
"pm_score": -1,
"selected": false,
"text": "box askstring from tkinter import *\nfrom tkinter.simpledialog import askstring\nfrom tkinter import messagebox\n\nname = askstring('Name','What is your name?')\nmessagebox.showinfo('Hello!','Hi, {}'.format(name))\n"
},
{
"answer_id": 74545105,
"author": "Thingamabobs",
"author_id": 13629335,
"author_profile": "https://Stackoverflow.com/users/13629335",
"pm_score": 1,
"selected": false,
"text": "Tk messagebox overrideredirect withdraw wm_attributes('-alpha', 0) PhotoImage pillow import tkinter as tk\nfrom tkinter.simpledialog import askstring\nfrom tkinter import messagebox\n\nbox = tk.Tk()\nbox.overrideredirect(True)\nbox.withdraw()\n\nname = askstring('Name','What is your name?') #blocks the code block\nmessagebox.showinfo('Hello!','Hi, {}'.format(name)) #shows message\nbox.after(5000, box.destroy) #destroy root window after 5 seconds\nbox.mainloop()#blocks until root is destroyed\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580476/"
] |
74,544,818
|
<p>I am trying to write a program that will count the number of words in each line. But the loop is not interrupted by a newline.</p>
<p>`</p>
<pre><code>program StringSymbols;
var
c : char;
i : integer;
begin
i := 1;
c := ' ';
writeln('Enter your string');
while c <> '#13' do
begin
read(c);
if c = ' ' then i := i + 1;
end;
writeln('count words: ', i)
end.
</code></pre>
<p>`</p>
<p>Please tell me how to write correctly. It is important that it was character-by-character reading.</p>
|
[
{
"answer_id": 74545008,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 1,
"selected": true,
"text": "read(c);\nwhile (c <> #13) and (c <> #10) do\nbegin\n if c = ' ' then inc(i);\n read(c);\nend; \n"
},
{
"answer_id": 74556916,
"author": "Stuart",
"author_id": 2655905,
"author_profile": "https://Stackoverflow.com/users/2655905",
"pm_score": 2,
"selected": false,
"text": "while not eoln do\n begin\n read(c);\n if c = ' ' then i := i + 1;\n end;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19876668/"
] |
74,544,821
|
<p>I'm trying to create a custom notification counter, which shows the number of notifications that are unread.
I receive the notification content from the backend as an array.
My idea is to get the first value, check if the previous length is different from the current length, and add to this counter +1(or more).</p>
<pre><code> useEffect(() => {
axios
.get(USER_API)
.then((response) => {
setNotificationList(response.data.data);
})
.catch((error) => console.log('error from getNotifications', error));
});
</code></pre>
<p>How can I make it work?</p>
|
[
{
"answer_id": 74544864,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": " setNotificationList((prev) => {\n if(prev?.length === response.data.data.length) return prev \n return response.data.data\n } );\n"
},
{
"answer_id": 74545247,
"author": "Ragnar",
"author_id": 9608873,
"author_profile": "https://Stackoverflow.com/users/9608873",
"pm_score": 2,
"selected": false,
"text": "useEffect(() => {\naxios\n .get(USER_API)\n .then((response) => {\n const data = response.data?.data;\n const unReadItems = data.filter((item)=> !item.isRead)\n setUnReadCount(unReadItems.length)\n setNotificationList(data);\n })\n .catch((error) => console.log('error from getNotifications', error));\n});\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20051604/"
] |
74,544,826
|
<p>I want a Boolean for a button stat but i cant what's wrong in my code?
`</p>
<pre><code><button id="read-more" class="read-more" onclick="Openreadmore()"> Read More </button>
</code></pre>
<p>``</p>
<p>`</p>
<pre><code> <script>
var status = false;
var myopacity = 0;
function Openreadmore() {
if (status == false) {
document.getElementById("text-more").style.display = "none";
document.getElementById("text-more").classList.remove("is-active");
document.getElementById("small-text").style.display = "block";
document.getElementById("read-more").textContent = 'Read More';
status == true;
}
if (status == true) {
document.getElementById("text-more").style.display = "block";
MycomeFadeFunction();
document.getElementById("text-more").classList.toggle("is-active");
document.getElementById("small-text").style.display = "none";
status == false;
document.getElementById("read-more").textContent = 'Close Paragraph';
}
}
function MycomeFadeFunction() {
if (myopacity < 1) {
myopacity += .075;
setTimeout(function() {
MycomeFadeFunction()
}, 100);
}
document.getElementById('text-more').style.opacity = myopacity;
}
</script>
</code></pre>
<p>`
I wanted to hide some divs when the boolean is true or false, there is a var status = false; I set it as default value then checked with if but things didn't work out</p>
|
[
{
"answer_id": 74544864,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": " setNotificationList((prev) => {\n if(prev?.length === response.data.data.length) return prev \n return response.data.data\n } );\n"
},
{
"answer_id": 74545247,
"author": "Ragnar",
"author_id": 9608873,
"author_profile": "https://Stackoverflow.com/users/9608873",
"pm_score": 2,
"selected": false,
"text": "useEffect(() => {\naxios\n .get(USER_API)\n .then((response) => {\n const data = response.data?.data;\n const unReadItems = data.filter((item)=> !item.isRead)\n setUnReadCount(unReadItems.length)\n setNotificationList(data);\n })\n .catch((error) => console.log('error from getNotifications', error));\n});\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13031871/"
] |
74,544,835
|
<p>I have below string which contains some functions names, so I need to call those function & whaterver values/result came from function need to replace in existing string (instead of function name)</p>
<p>My String</p>
<pre><code>my_computer/project_folder/customer=getCustomer()/getCsvFileName()/controller=getControllerName()
</code></pre>
<p>Need output like:</p>
<pre><code>my_computer/project_folder/customer=Customer1/userData.csv/controller=myController
</code></pre>
<p>I am getting function names from string using below:</p>
<pre><code>let functions = parquetUploadPath.split("/")
.filter(element => element.endsWith("()"))
.map(element => element.split("=")[1] ?? element.split("=")[0]);
</code></pre>
|
[
{
"answer_id": 74544999,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 1,
"selected": false,
"text": " `my_computer/project_folder/customer=${getCustomer()}/${getCsvFileName()}/controller=${getControllerName()}`\n"
},
{
"answer_id": 74545022,
"author": "voidbrain",
"author_id": 1000137,
"author_profile": "https://Stackoverflow.com/users/1000137",
"pm_score": 0,
"selected": false,
"text": "const customer = getCustomer(); const csvFileName = getCsvFileName();\nconst controllerName getControllerName();\nconst myString = `my_computer/project_folder/customer=${customer}/${csvFileName}/controller=${controller}`;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16915156/"
] |
74,544,837
|
<p>Say I have</p>
<pre><code>Method1(); // might return error
Method2(); // should only be executed if previous line successful
</code></pre>
<p>I could use <code>try</code> and <code>catch</code>, however I still want errors to <strong>happen</strong>, I just don't want <code>Method2()</code> to be run if any errors occurred.</p>
|
[
{
"answer_id": 74544943,
"author": "Fildor",
"author_id": 982149,
"author_profile": "https://Stackoverflow.com/users/982149",
"pm_score": 3,
"selected": true,
"text": "bool TrySomething( out int returnValue )\n returnValue if( TrySomething(out int someValue) )\n{\n Method2( someValue );\n}\n TryParse Method1 Method1();\n// If Method1 throws an exception, Method2 will not be executed.\n// The control flow will be redirected to the \"next\" catch block\n// that handles the exception type or if none of those exist crash \n// the app.\nMethod2();\n Method1 Method2 Method2 try\n{\n Method1(); // throws \n Method2(); // won't execute\n}\ncatch(SomeException ex)\n{\n // Control flow will continue here.\n // Handle that exception\n}\nfinally // optional\n{\n // This will be executed regardless of whether there was an exception or not.\n}\n"
},
{
"answer_id": 74545004,
"author": "The Overrider",
"author_id": 9289710,
"author_profile": "https://Stackoverflow.com/users/9289710",
"pm_score": 1,
"selected": false,
"text": " try {\n MethodWithErrorOrException();\n MethodAfter();\n }\n catch (Exception) {\n // Handling\n }\n finally {\n MethodAlwaysCalled();\n }\n"
},
{
"answer_id": 74545291,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "if(Method1()){Method2();}"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16234971/"
] |
74,544,839
|
<p>I try to run following "trying.py" but get above error. How to fix it?</p>
<p><strong>trying.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import cv2, os
import numpy as np
from PIL import Image
# Create Local Binary Patterns Histograms for face recognization
recognizer = cv2.face.LBPHFaceRecognizer_create()
# Using prebuilt frontal face training model, for face detection
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
# Create method to get the images and label data
def getImagesAndLabels(path):
# Get all file path
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
# Initialize empty face sample
faceSamples = []
# Initialize empty id
ids = []
# Loop all the file path
for imagePath in imagePaths:
# Get the image and convert it to grayscale
PIL_img = Image.open(imagePath).convert('L')
# PIL image to numpy array
img_numpy = np.array(PIL_img, 'uint8')
# Get the image id
id = int(os.path.split(imagePath)[-1].split(".")[1])
print(id)
# Get the face from the training images
faces = detector.detectMultiScale(img_numpy)
# Loop for each face, append to their respective ID
for (x, y, w, h) in faces:
# Add the image to face samples
faceSamples.append(img_numpy[y:y + h, x:x + w])
# Add the ID to IDs
ids.append(id)
# Pass the face array and IDs array
return faceSamples, ids
# Get the faces and IDs
faces, ids = getImagesAndLabels('dataset')
# Train the model using the faces and IDs
recognizer.train(faces, np.array(ids))
# Save the model into trainer.yml
recognizer.save('trainer/trainer.yml')
</code></pre>
<p><strong>Error:</strong></p>
<blockquote>
<p>Traceback (most recent call last):
File "C:\Users\HP\PycharmProjects\face_identificiation\trying.py", line 12, in
recognizer = cv2.face.LBPHFaceRecognizer_create()
AttributeError: module 'cv2' has no attribute 'face'</p>
</blockquote>
|
[
{
"answer_id": 74544943,
"author": "Fildor",
"author_id": 982149,
"author_profile": "https://Stackoverflow.com/users/982149",
"pm_score": 3,
"selected": true,
"text": "bool TrySomething( out int returnValue )\n returnValue if( TrySomething(out int someValue) )\n{\n Method2( someValue );\n}\n TryParse Method1 Method1();\n// If Method1 throws an exception, Method2 will not be executed.\n// The control flow will be redirected to the \"next\" catch block\n// that handles the exception type or if none of those exist crash \n// the app.\nMethod2();\n Method1 Method2 Method2 try\n{\n Method1(); // throws \n Method2(); // won't execute\n}\ncatch(SomeException ex)\n{\n // Control flow will continue here.\n // Handle that exception\n}\nfinally // optional\n{\n // This will be executed regardless of whether there was an exception or not.\n}\n"
},
{
"answer_id": 74545004,
"author": "The Overrider",
"author_id": 9289710,
"author_profile": "https://Stackoverflow.com/users/9289710",
"pm_score": 1,
"selected": false,
"text": " try {\n MethodWithErrorOrException();\n MethodAfter();\n }\n catch (Exception) {\n // Handling\n }\n finally {\n MethodAlwaysCalled();\n }\n"
},
{
"answer_id": 74545291,
"author": "Mykhailo Svyrydovych",
"author_id": 13251244,
"author_profile": "https://Stackoverflow.com/users/13251244",
"pm_score": 0,
"selected": false,
"text": "if(Method1()){Method2();}"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580599/"
] |
74,544,924
|
<p>I want to create a file that shows the execution progress and what is being done when I run tasks. Now I want to generate a JSON format when I have done it through <code>local_action</code> and <code>lineinfile</code>.</p>
<p>This is my playbook</p>
<pre class="lang-yaml prettyprint-override"><code>- name: The module that Set the progress and details
block:
- name: Set the progress and details
shell: echo "10"
register: progress_result
delegate_to: localhost
- name: Set the progress and details
shell: echo "update docker script"
register: message_result
delegate_to: localhost
- name: Save progress
delegate_to: localhost
local_action:
module: lineinfile
path: "{{playbook_dir}}/scheduler/plan.yaml"
regexp: "progress:"
line: "progress:{{progress_result.stdout}},step:{{message_result.stdout}}"
create: yes
</code></pre>
<p>The current results of operation is</p>
<pre><code># cat scheduler/plan.yaml
progress:10,step:update docker script
</code></pre>
<p>But I would like to have the results in JSON format</p>
<pre class="lang-json prettyprint-override"><code>{"progress":"10","step":"update docker script"}
</code></pre>
<p>Who can help me?</p>
|
[
{
"answer_id": 74546236,
"author": "Markus",
"author_id": 2779972,
"author_profile": "https://Stackoverflow.com/users/2779972",
"pm_score": 1,
"selected": false,
"text": "lineinfile from_json to_json"
},
{
"answer_id": 74557700,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 0,
"selected": false,
"text": "---\n- hosts: localhost\n become: false\n gather_facts: false\n\n vars:\n\n progress_result:\n stdout: 10\n\n message_result:\n stdout: update\n\n tasks:\n\n - name: Save progress\n lineinfile:\n path: test.txt\n regexp: \"progress:\"\n line: '\"progress\":\"{{ progress_result.stdout }}\",\"step\":\"{{ message_result.stdout }}\"'\n create: yes\n \"progress\":\"10\",\"step\":\"update\"\n { } !unsafe {% raw %} {% endraw %} line: '{% raw %}{{% endraw %}\"progress\":\"{{ progress_result.stdout }}\",\"step\":\"{{ message_result.stdout }}{% raw %}\"}{% endraw %}'\n {'progress': '10', 'step': 'update'}\n lineinfile lineinfile"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14150358/"
] |
74,544,926
|
<p>Facing issue while downloading the app in iPhone 16.1.1 version.</p>
<p><strong>Developer mode required</strong> - <em><Your_App> requires Developer Mode to run. Until Developer Mode has been enabled, this app will not be available for use.</em></p>
<p><a href="https://i.stack.imgur.com/iXSTO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iXSTO.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74546236,
"author": "Markus",
"author_id": 2779972,
"author_profile": "https://Stackoverflow.com/users/2779972",
"pm_score": 1,
"selected": false,
"text": "lineinfile from_json to_json"
},
{
"answer_id": 74557700,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 0,
"selected": false,
"text": "---\n- hosts: localhost\n become: false\n gather_facts: false\n\n vars:\n\n progress_result:\n stdout: 10\n\n message_result:\n stdout: update\n\n tasks:\n\n - name: Save progress\n lineinfile:\n path: test.txt\n regexp: \"progress:\"\n line: '\"progress\":\"{{ progress_result.stdout }}\",\"step\":\"{{ message_result.stdout }}\"'\n create: yes\n \"progress\":\"10\",\"step\":\"update\"\n { } !unsafe {% raw %} {% endraw %} line: '{% raw %}{{% endraw %}\"progress\":\"{{ progress_result.stdout }}\",\"step\":\"{{ message_result.stdout }}{% raw %}\"}{% endraw %}'\n {'progress': '10', 'step': 'update'}\n lineinfile lineinfile"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12681178/"
] |
74,544,945
|
<p>I need add 40 to a <code>string | number</code> type, and return a <code>string | number</code>. How is it possible in Typescript?</p>
<p>I thought parse it to number, then increase it and return it. But how can I parse a variable which is not sure is string, but it can be number? :)</p>
<p>tried this:</p>
<blockquote>
<p>parseInt(x) - 44</p>
</blockquote>
<p>but raised an</p>
<pre><code>Argument of type 'string | number' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'.ts(2345)
</code></pre>
|
[
{
"answer_id": 74546236,
"author": "Markus",
"author_id": 2779972,
"author_profile": "https://Stackoverflow.com/users/2779972",
"pm_score": 1,
"selected": false,
"text": "lineinfile from_json to_json"
},
{
"answer_id": 74557700,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 0,
"selected": false,
"text": "---\n- hosts: localhost\n become: false\n gather_facts: false\n\n vars:\n\n progress_result:\n stdout: 10\n\n message_result:\n stdout: update\n\n tasks:\n\n - name: Save progress\n lineinfile:\n path: test.txt\n regexp: \"progress:\"\n line: '\"progress\":\"{{ progress_result.stdout }}\",\"step\":\"{{ message_result.stdout }}\"'\n create: yes\n \"progress\":\"10\",\"step\":\"update\"\n { } !unsafe {% raw %} {% endraw %} line: '{% raw %}{{% endraw %}\"progress\":\"{{ progress_result.stdout }}\",\"step\":\"{{ message_result.stdout }}{% raw %}\"}{% endraw %}'\n {'progress': '10', 'step': 'update'}\n lineinfile lineinfile"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557555/"
] |
74,544,958
|
<p>I've created an ACF Checkbox field that I assigned to the User Profile area.</p>
<p>I'm using a form in order to bring up a popup with the checkboxes where users choose from the available options, the form then saves and updates the choices in user's profile. That all seems to be working perfectly fine.</p>
<p>But now I need to show the selected choices in User Profile template using a shortcode.</p>
<p>My ACF return value is set to value and I'm using the snippet exactly as per <a href="https://www.advancedcustomfields.com/resources/checkbox/" rel="nofollow noreferrer">ACF's docs</a> in order to display a list of labels.</p>
<p>This is my shortcode:</p>
<pre><code>function get_user_profile_choices() {
$field = get_field_object('color_choices');
$colors = $field['value'];
// Display labels.
if( $colors ): ?>
<ul>
<?php foreach( $colors as $color ): ?>
<li><?php echo $field['choices'][ $color ]; ?></li>
<?php endforeach; ?>
</ul>
<?php endif;
}
add_shortcode( 'user-profile', 'get_user_profile_choices' );
</code></pre>
<p>I am currently just testing this with my own admin account, so I'm trying to show my choices in my profile.</p>
<p>I'm not getting anything. Could it be because the checkbox is in User Profile? Do I need to declare any user variable? Any ideas?</p>
|
[
{
"answer_id": 74546984,
"author": "Rizwan Ahmad",
"author_id": 20133382,
"author_profile": "https://Stackoverflow.com/users/20133382",
"pm_score": -1,
"selected": false,
"text": "$user_id = 1;\n$field = get_field_object('color_choices', 'user_' . $user_id);\n"
},
{
"answer_id": 74556940,
"author": "Harit Panchal",
"author_id": 16112853,
"author_profile": "https://Stackoverflow.com/users/16112853",
"pm_score": 0,
"selected": false,
"text": "function get_user_profile_choices() {\n $user_id = get_current_user_id();\n $field = get_field_object('color_choices', 'user_'.$user_id);\n}\nadd_shortcode( 'user-profile', 'get_user_profile_choices' );\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4339640/"
] |
74,544,977
|
<p>When using database projects, compare, and then Generate Script then the generated scripts is default for SqlCmd. E.g. it generates a row like:</p>
<pre><code>/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
</code></pre>
<p>Is it possible to generate scripts in the Database Project that just generates the stuff that can be executed via SQL Server Management Studio?</p>
<p>(I use Visual Studio 2022)</p>
|
[
{
"answer_id": 74546984,
"author": "Rizwan Ahmad",
"author_id": 20133382,
"author_profile": "https://Stackoverflow.com/users/20133382",
"pm_score": -1,
"selected": false,
"text": "$user_id = 1;\n$field = get_field_object('color_choices', 'user_' . $user_id);\n"
},
{
"answer_id": 74556940,
"author": "Harit Panchal",
"author_id": 16112853,
"author_profile": "https://Stackoverflow.com/users/16112853",
"pm_score": 0,
"selected": false,
"text": "function get_user_profile_choices() {\n $user_id = get_current_user_id();\n $field = get_field_object('color_choices', 'user_'.$user_id);\n}\nadd_shortcode( 'user-profile', 'get_user_profile_choices' );\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2854001/"
] |
74,545,035
|
<p>How can I calculate total hours between two dates. here I have to select the start date and end date. and every day an employee works 8 hours per day. I calculate the total hours between these two dates. For example if I select two dates from: 11/21/2022 and date to:11/22/2022. These two dates total hours are 16 hours. and date need to count without holiday how can I do that. Please help me. Here I want to exclude holidays between the total days.please help me</p>
<pre><code>@api.depends("start_date", "date_deadline")
def _compute_hours(self):
if self.start_date and self.date_deadline:
t1 = datetime.strptime(str(self.start_date), '%Y-%m-%d')
print(t1)
t2 = datetime.strptime(str(self.date_deadline), '%Y-%m-%d')
print('=================================T2')
print(t2)
t3 = t2 - t1
# count = sum(1 for day in t3 if day.weekday() < 5)
# print(count)
print('=================================T3')
print(t3)
print('=================================')
seconds = t3.total_seconds() / 3
diff_in_hours = seconds / 3600
print('Difference between two datetimes in hours:')
print(diff_in_hours)
self.total_hours = diff_in_hours
</code></pre>
<p>I am trying to exclude holidays from total days</p>
|
[
{
"answer_id": 74546984,
"author": "Rizwan Ahmad",
"author_id": 20133382,
"author_profile": "https://Stackoverflow.com/users/20133382",
"pm_score": -1,
"selected": false,
"text": "$user_id = 1;\n$field = get_field_object('color_choices', 'user_' . $user_id);\n"
},
{
"answer_id": 74556940,
"author": "Harit Panchal",
"author_id": 16112853,
"author_profile": "https://Stackoverflow.com/users/16112853",
"pm_score": 0,
"selected": false,
"text": "function get_user_profile_choices() {\n $user_id = get_current_user_id();\n $field = get_field_object('color_choices', 'user_'.$user_id);\n}\nadd_shortcode( 'user-profile', 'get_user_profile_choices' );\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20466282/"
] |
74,545,050
|
<pre><code><?php
echo "<a href='".$client->createAuthUrl()."'><button>Login with Google</button></a>";
?>
</code></pre>
<p>Im trying to add class for <code><a href></code> inside php echo , but i cant do any style what i want to do</p>
<pre><code><?php
echo "<a href='".$client->createAuthUrl()."'><button>Login with Google</button></a>";
?>
</code></pre>
|
[
{
"answer_id": 74546984,
"author": "Rizwan Ahmad",
"author_id": 20133382,
"author_profile": "https://Stackoverflow.com/users/20133382",
"pm_score": -1,
"selected": false,
"text": "$user_id = 1;\n$field = get_field_object('color_choices', 'user_' . $user_id);\n"
},
{
"answer_id": 74556940,
"author": "Harit Panchal",
"author_id": 16112853,
"author_profile": "https://Stackoverflow.com/users/16112853",
"pm_score": 0,
"selected": false,
"text": "function get_user_profile_choices() {\n $user_id = get_current_user_id();\n $field = get_field_object('color_choices', 'user_'.$user_id);\n}\nadd_shortcode( 'user-profile', 'get_user_profile_choices' );\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580749/"
] |
74,545,054
|
<p>i have been trying to get my ternery operator to work on a nested fashion on the link component of the router. appearently the ternery operator is flipped where its supposed to be like
Condition?true:false
mine is like Condition?false:true which is really confusing since i want to nest the ternery ot have mulitple cases like a switch statemnt to make the button react to what every component its put on</p>
<p>i have attached some code in order to make it more clearer</p>
<pre><code>function BottomNav({product}) {
return (
<div className="bottomNav">
<Link to={product !== 'model 3'? '/design/model3':'/design/model'}>
<button className="leftbutton">Custom design</button>
</Link>
</code></pre>
<p>the above takes a props called product and checks the product name to give a certain route for the specific product</p>
|
[
{
"answer_id": 74546984,
"author": "Rizwan Ahmad",
"author_id": 20133382,
"author_profile": "https://Stackoverflow.com/users/20133382",
"pm_score": -1,
"selected": false,
"text": "$user_id = 1;\n$field = get_field_object('color_choices', 'user_' . $user_id);\n"
},
{
"answer_id": 74556940,
"author": "Harit Panchal",
"author_id": 16112853,
"author_profile": "https://Stackoverflow.com/users/16112853",
"pm_score": 0,
"selected": false,
"text": "function get_user_profile_choices() {\n $user_id = get_current_user_id();\n $field = get_field_object('color_choices', 'user_'.$user_id);\n}\nadd_shortcode( 'user-profile', 'get_user_profile_choices' );\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20181776/"
] |
74,545,075
|
<p>I'm looking for a solution from the STL, for dealing with "time of day". I am working on a simple unit test exercise, with behavior depending on whether current time is in the morning, evening or night.</p>
<p>For a first iteration I used a humble integer as a stand-in for some "time object":</p>
<pre><code>using TimeOfDay = int;
constexpr bool isBetween(TimeOfDay in, TimeOfDay min, TimeOfDay max) noexcept {
return in >= min && in <= max;
}
constexpr bool isMorning(TimeOfDay in) noexcept {
return isBetween(in, 6, 12); }
constexpr bool isEvening(TimeOfDay in) noexcept {
return isBetween(in, 18, 22);
}
constexpr bool isNight(TimeOfDay in) noexcept {
return isBetween(in, 22, 24) || isBetween(in, 0, 6);
}
constexpr string_view getGreetingFor(TimeOfDay time) noexcept {
if (isMorning(time)) {
return "Good morning "sv;
}
if (isEvening(time)) {
return "Good evening "sv;
}
if (isNight(time)) {
return "Good night "sv;
}
return "Hello "sv;
}
</code></pre>
<p>This works but has a couple of smells:</p>
<ul>
<li>the <code>int</code> simply isn't the right type to represent a 24 hour clock</li>
<li><code>isNight()</code> requires an unnecessarily complicated comparison, due to wrapping (22-06)</li>
<li>ideally I would like to be able actually use the system clock for some of my tests.</li>
<li><code>std::chrono::system_clock::now()</code> returns a <code>std::chrono::time_point</code>, so my ideal type should probably be something that can be compared to a <code>time_point</code>, or easily constructed from a <code>time_point</code>.</li>
</ul>
<p>Any pointers would be very appreciated!</p>
<p>(I am working in Visual Studio with C++Latest (preview of the C++ working draft, so roughly C++23))</p>
|
[
{
"answer_id": 74545246,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 1,
"selected": false,
"text": "std::chrono::duration std::chrono::hours std::chrono::hh_mm_ss #include <iostream>\n#include <chrono>\n\nusing namespace std::chrono;\n\nint main()\n{\n auto now = system_clock::now().time_since_epoch();\n auto today = duration_cast<days>(now);\n hh_mm_ss time { now - today };\n std::cout << time.hours() << time.minutes() << time.seconds();\n}\n"
},
{
"answer_id": 74546724,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 0,
"selected": false,
"text": "std::chrono::duration duration auto time_info = my_duration - std::chrono::round<std::chrono::days>(my_duration);\n time_point auto now = std::chrono::system_clock::now();\nauto time_info = now - std::chrono::round<std::chrono::days>(now);\n hh_mm_ss auto hms = std::chrono::hh_mm_ss{ time_info };\nstd::cout << hms.hours() << hms.minutes() << hms.seconds();\n duration using TimeOfDay = std::chrono::seconds;\n\nconstexpr bool isBetween(TimeOfDay in, TimeOfDay min, TimeOfDay max) noexcept {\n return in >= min && in <= max; \n}\n\nconstexpr bool isMorning(TimeOfDay in) noexcept { \n return isBetween(in, std::chrono::hours{6}, std::chrono::hours{12}); \n}\n using namespace std::chrono_literals using namespace std::literals constexpr bool isMorning(TimeOfDay in) noexcept { \n return isBetween(in, 6h, 12h); \n}\n isEvening isBetween(in + 12h - days{1}, 10h, 18h) time_point auto today = std::chrono::round<std::chrono::days>(std::chrono::system_clock::now());\nauto now = today + time_info;\n"
},
{
"answer_id": 74549840,
"author": "Howard Hinnant",
"author_id": 576911,
"author_profile": "https://Stackoverflow.com/users/576911",
"pm_score": 3,
"selected": true,
"text": "chrono::system_clock std::chrono::system_clock::time_point std::chrono::system_clock::duration using TimeOfDay = std::chrono::system_clock::duration;\n\nTimeOfDay\nget_local_time_of_day(std::chrono::system_clock::time_point tp) noexcept\n{\n using namespace std::chrono;\n auto time = current_zone()->to_local(tp);\n return time - floor<days>(time);\n}\n chrono::current_zone() chrono::time_zone system_clock::time_point time_point time_point chrono::time_point floor<days>(time) time_point days time chrono::duration duration tp constexpr isMorning bool isMorning(std::chrono::system_clock::time_point in) noexcept { \n using namespace std::literals;\n return isBetween(get_local_time_of_day(in), 6h, 12h); }\n if (isMorning(system_clock::now())) ...\n isNight isBetween TimeOfDay"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/347764/"
] |
74,545,085
|
<p>Hi am working terraform code where am creating eks cluster and rds with security group for rds ad cluster also in rds security group am using dynamic method create ingress in that some using cidr some of security group am able to create cidr am stuck at security groupa</p>
<pre><code>variable.tf
variable "ingress_rules" {
default = {
"indian vpn ingress rule" = {
"description" = "India CIDR"
"from_port" = "1521"
"to_port" = "1521"
"protocol" = "tcp"
"cidr_blocks" = ["192.34.890.0/24"]
},
"eks node ingress rule" = {
"description" = "EKS Nodes SG"
"from_port" = "1521"
"to_port" = "1521"
"protocol" = "tcp"
"security_groups" = ["module.eks.worker_security_group_id"]
}
</code></pre>
<p>mani.tf</p>
<pre><code>esource "aws_security_group" "rds_sg" {
name = "${var.cluster_name}-rds-sg"
vpc_id = var.vpc_id
dynamic "ingress" {
for_each = var.ingress_rules
content {
description = lookup(ingress.value, "description", null)
from_port = lookup(ingress.value, "from_port", null)
to_port = lookup(ingress.value, "to_port", null)
protocol = lookup(ingress.value, "protocol", null)
cidr_blocks = lookup(ingress.value, "cidr_blocks", null)
security_groups = lookup(ingress.value, "security_groups", null)
}
}
</code></pre>
<p>How to define ["module.eks.worker_security_group_id"] in varibale tf my eks module define in main.tf</p>
|
[
{
"answer_id": 74545246,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 1,
"selected": false,
"text": "std::chrono::duration std::chrono::hours std::chrono::hh_mm_ss #include <iostream>\n#include <chrono>\n\nusing namespace std::chrono;\n\nint main()\n{\n auto now = system_clock::now().time_since_epoch();\n auto today = duration_cast<days>(now);\n hh_mm_ss time { now - today };\n std::cout << time.hours() << time.minutes() << time.seconds();\n}\n"
},
{
"answer_id": 74546724,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 0,
"selected": false,
"text": "std::chrono::duration duration auto time_info = my_duration - std::chrono::round<std::chrono::days>(my_duration);\n time_point auto now = std::chrono::system_clock::now();\nauto time_info = now - std::chrono::round<std::chrono::days>(now);\n hh_mm_ss auto hms = std::chrono::hh_mm_ss{ time_info };\nstd::cout << hms.hours() << hms.minutes() << hms.seconds();\n duration using TimeOfDay = std::chrono::seconds;\n\nconstexpr bool isBetween(TimeOfDay in, TimeOfDay min, TimeOfDay max) noexcept {\n return in >= min && in <= max; \n}\n\nconstexpr bool isMorning(TimeOfDay in) noexcept { \n return isBetween(in, std::chrono::hours{6}, std::chrono::hours{12}); \n}\n using namespace std::chrono_literals using namespace std::literals constexpr bool isMorning(TimeOfDay in) noexcept { \n return isBetween(in, 6h, 12h); \n}\n isEvening isBetween(in + 12h - days{1}, 10h, 18h) time_point auto today = std::chrono::round<std::chrono::days>(std::chrono::system_clock::now());\nauto now = today + time_info;\n"
},
{
"answer_id": 74549840,
"author": "Howard Hinnant",
"author_id": 576911,
"author_profile": "https://Stackoverflow.com/users/576911",
"pm_score": 3,
"selected": true,
"text": "chrono::system_clock std::chrono::system_clock::time_point std::chrono::system_clock::duration using TimeOfDay = std::chrono::system_clock::duration;\n\nTimeOfDay\nget_local_time_of_day(std::chrono::system_clock::time_point tp) noexcept\n{\n using namespace std::chrono;\n auto time = current_zone()->to_local(tp);\n return time - floor<days>(time);\n}\n chrono::current_zone() chrono::time_zone system_clock::time_point time_point time_point chrono::time_point floor<days>(time) time_point days time chrono::duration duration tp constexpr isMorning bool isMorning(std::chrono::system_clock::time_point in) noexcept { \n using namespace std::literals;\n return isBetween(get_local_time_of_day(in), 6h, 12h); }\n if (isMorning(system_clock::now())) ...\n isNight isBetween TimeOfDay"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20527029/"
] |
74,545,125
|
<p>I am trying to validate a form using the reactive approach. I am using the file input to take a file from the user. I have defined a custom validator that allows the user to upload a file on certain conditions. While trying to do so, I am getting an error. The validator does not receive the event as a whole but rather only the path of the file something like <code>C:\fakepath\abc.xlsx</code>. I want to pass the DOM event so that I can handle all the properties of files like type, size etc.</p>
<p>Here's my code:</p>
<blockquote>
<p>file.validator.ts</p>
</blockquote>
<pre><code>import { AbstractControl } from '@angular/forms';
export function ValidateFile(control: AbstractControl) :
{ [key: string]: boolean } | null {
const value = control.value;
if (!value) {
return null;
}
return value.length < 0 && value.files[0].type !== '.xlsx' && value.files[0].size > 5000000
? { invalidFile: true } : null;
}
</code></pre>
<blockquote>
<p>sheet.component.ts</p>
</blockquote>
<pre><code>constructor(
private formBuilder: FormBuilder,
private alertService: AlertService
) {
this.sheetForm = this.formBuilder.group({
sheetType: ['Select Sheet Type', [Validators.required]],
sheetUpload: [null, [Validators.required, ValidateFile]],
sheetDescription: [
null,
[
Validators.required,
Validators.minLength(10),
Validators.maxLength(100),
],
],
});
}
</code></pre>
<blockquote>
<p>sheet.component.html</p>
</blockquote>
<pre><code><div class="input-group">
<label for="sheet-upload">Upload Sheet: </label> &nbsp; &nbsp;
<input
id="sheet-upload"
type="file"
(change)="handleFileInput($event)"
formControlName="sheetUpload"
accept=".xlsx"
/>
<small
id="custom-error-message"
*ngIf="
(sheetForm.get('sheetUpload').dirty ||
sheetForm.get('sheetUpload').touched) &&
sheetForm.get('sheetUpload').invalid
"
>
The file size exceeds 5 MB or isn't a valid excel type. Please
upload again.
</small>
</div>
</code></pre>
<p>Any help would be appreciated. Thanks!</p>
|
[
{
"answer_id": 74546295,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 2,
"selected": true,
"text": "@Directive({\n selector: '[formControlName]',\n})\nexport class NativeElementInjectorDirective implements OnInit {\n constructor(private el: ElementRef, private control: NgControl) {}\n\n ngOnInit() {\n (this.control.control as any).nativeElement = this.el.nativeElement;\n }\n}\n export function ValidateFile(control: any): { [key: string]: boolean } | null {\n const value = control.value;\n const file = control?.nativeElement?.files[0];\n\n if (!value) {\n return null;\n }\n\n return value.length < 0 || file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.size > 5000000\n ? { invalidFile: true }\n : null;\n}\n\n <div class=\"input-group\" [formGroup]=\"sheetForm\">\n <label for=\"sheet-upload\">Upload Sheet: </label> \n <input\n id=\"sheet-upload\"\n type=\"file\"\n formControlName=\"sheetUpload\"\n accept=\".xlsx\"\n />\n <small\n id=\"custom-error-message\"\n *ngIf=\"\n (sheetForm.get('sheetUpload').dirty ||\n sheetForm.get('sheetUpload').touched) &&\n sheetForm.get('sheetUpload').invalid\n \"\n >\n The file size exceeds 5 MB or isn't a valid excel type. Please upload again.\n </small>\n</div>\n"
},
{
"answer_id": 74546425,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 0,
"selected": false,
"text": "<input #sheetUpload ...>\n\n@ViewChild('sheetUpload') fileInput: HTMLInputElement;\n\nprivate ValidateFile(): ValidatorFn {\nreturn (control) => {\n const value = control.value;\n\n if (!value || !this.fileInput) {\n return null;\n }\n\n const file = this.fileInput.files[0];\n\n return value.length < 0 && file.type !== '.xlsx' && file.size > 5000000\n ? { invalidFile: file.name }\n : null;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7735258/"
] |
74,545,126
|
<p>Is there a way to save last N seconds of a video stream to a file with openCV? E.g. The camera recording starts at 0s and ends at 20s leading to a recorded file which contains the video from 10s -> 20s.</p>
<p>One way I can think of is to save last N seconds in a memory buffer and write them to file once the process finishes, but this is not a desireable solution because of the latency involved at the end as well as memory limitations when multiple HD streams are involved.</p>
|
[
{
"answer_id": 74546295,
"author": "Mr. Stash",
"author_id": 13625800,
"author_profile": "https://Stackoverflow.com/users/13625800",
"pm_score": 2,
"selected": true,
"text": "@Directive({\n selector: '[formControlName]',\n})\nexport class NativeElementInjectorDirective implements OnInit {\n constructor(private el: ElementRef, private control: NgControl) {}\n\n ngOnInit() {\n (this.control.control as any).nativeElement = this.el.nativeElement;\n }\n}\n export function ValidateFile(control: any): { [key: string]: boolean } | null {\n const value = control.value;\n const file = control?.nativeElement?.files[0];\n\n if (!value) {\n return null;\n }\n\n return value.length < 0 || file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.size > 5000000\n ? { invalidFile: true }\n : null;\n}\n\n <div class=\"input-group\" [formGroup]=\"sheetForm\">\n <label for=\"sheet-upload\">Upload Sheet: </label> \n <input\n id=\"sheet-upload\"\n type=\"file\"\n formControlName=\"sheetUpload\"\n accept=\".xlsx\"\n />\n <small\n id=\"custom-error-message\"\n *ngIf=\"\n (sheetForm.get('sheetUpload').dirty ||\n sheetForm.get('sheetUpload').touched) &&\n sheetForm.get('sheetUpload').invalid\n \"\n >\n The file size exceeds 5 MB or isn't a valid excel type. Please upload again.\n </small>\n</div>\n"
},
{
"answer_id": 74546425,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 0,
"selected": false,
"text": "<input #sheetUpload ...>\n\n@ViewChild('sheetUpload') fileInput: HTMLInputElement;\n\nprivate ValidateFile(): ValidatorFn {\nreturn (control) => {\n const value = control.value;\n\n if (!value || !this.fileInput) {\n return null;\n }\n\n const file = this.fileInput.files[0];\n\n return value.length < 0 && file.type !== '.xlsx' && file.size > 5000000\n ? { invalidFile: file.name }\n : null;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19721091/"
] |
74,545,173
|
<p>I need to perform a number of imputations for missing values for modes of transport. There are 12 different modes of transport. As a preliminary step I calculate the number of people using each mode of transport and the corresponding quota:</p>
<p>My code looks like this:</p>
<pre><code>PROC SQL;
CREATE TABLE hjälptabell_transport_SE as
SELECT R_fard_h,antal,antal/sum(antal) as kvot
FROM
(SELECT R_fard_h,count(R_fard_h) as antal
FROM data_resor14_2
WHERE R_fard_h is not missing and R_res_land_grp="Sverige"
GROUP BY R_fard_h);
quit;
</code></pre>
<p>And my output ideally looks something like this:</p>
<p><a href="https://i.stack.imgur.com/tbaFK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tbaFK.png" alt="enter image description here" /></a></p>
<p>However, in some case zero observations uses a certain mode of transport, making the output look like this instead:</p>
<p><a href="https://i.stack.imgur.com/MucxQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MucxQ.png" alt="enter image description here" /></a></p>
<p>Note that the number of people using the eleventh mode of transport is omitted. It's actually very important that every table is precisely 12 rows long, and if precisely zero people uses a certain mode of transport I still want that row to be included, but with a count of zero.</p>
<p>How can I make this happen?</p>
|
[
{
"answer_id": 74549702,
"author": "Stu Sztukowski",
"author_id": 5342700,
"author_profile": "https://Stackoverflow.com/users/5342700",
"pm_score": 1,
"selected": false,
"text": "data template;\n do r_fard_h = 1 to 12;\n output;\n end;\nrun;\n coalesce PROC SQL;\n CREATE TABLE hjälptabell_transport_SE as\n SELECT t2.R_fard_h\n , antal\n , coalesce(antal/sum(antal), 0) as kvot \n FROM (SELECT R_fard_h, count(R_fard_h) as antal\n FROM data_resor14_2\n WHERE R_fard_h is not missing AND R_res_land_grp=\"Sverige\"\n GROUP BY R_fard_h\n ) as t1\n RIGHT JOIN\n template as t2\n ON t1.r_fard_h = t2.r_fard_h\n ;\nquit;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5428469/"
] |
74,545,209
|
<p>Hope someone can help me here.
Been trying different things but always end up just extending my routes.
What i want is to be able to navigate through products (its some kinda eshop)</p>
<p>So, when i am in 1st product with prod_G6kVw7pV6Oo2eD as product id</p>
<pre><code>http://localhost:3000/combo/prod_G6kVw7pV6Oo2eD
</code></pre>
<p>I need to be able to go to the next product (go back and forth as I have 3 buttons called "Prev" and "Next"). 6 products in total.
That's the array of product ids =</p>
<pre><code>['prod_G6kVw7pV6Oo2eD', 'prod_RyWOwmPkL9lnEa', 'prod_ypbroE9QBno8n4', 'prod_Kvg9l61rEm51bB', 'prod_NqKE50NEPBwdgB', 'prod_kpnNwA1P8awmXB']
</code></pre>
<p>Once i reach the last product (prod_kpnNwA1P8awmXB) i need to go the first product.</p>
<p>In other words - just need to change product_id - last element of the route.</p>
<p>I think there is a good solution for this cos its a very common case. But I am unable to find.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74545321,
"author": "Paul-Marie",
"author_id": 9603417,
"author_profile": "https://Stackoverflow.com/users/9603417",
"pm_score": 2,
"selected": true,
"text": "const comboproductsids = [\n 'prod_G6kVw7pV6Oo2eD',\n 'prod_RyWOwmPkL9lnEa',\n 'prod_ypbroE9QBno8n4',\n 'prod_Kvg9l61rEm51bB',\n 'prod_NqKE50NEPBwdgB',\n 'prod_kpnNwA1P8awmXB'\n];\n\n<Box onClick={() => navigate(`/${id[1]}/${comboproductsids[(index + 1) % comboproductsids.length]}`)} \n 0"
},
{
"answer_id": 74546711,
"author": "Simon Buryat",
"author_id": 12396859,
"author_profile": "https://Stackoverflow.com/users/12396859",
"pm_score": 0,
"selected": false,
"text": "<Box onClick={()=>navigate(`/${id[1]}/${comboproductsids[index+1]}`)} \n const id = window.location.pathname.split(\"/\"); const indexid = window.location.pathname.split(\"/\")[2]; const index = comboproductsids.indexOf(indexid)"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12396859/"
] |
74,545,219
|
<p>I'm trying to filter my data by keeping the row that respects a condition AND the row that follows it if it exists:</p>
<p>In the example below, I need to keep the row with "NOK" in "X3" and the next one but if the next one doesnt exist, just keep the row with "NOK".</p>
<p>My data looks like this (Original data have far more rows) :</p>
<p><a href="https://i.stack.imgur.com/zvCGM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zvCGM.png" alt="enter image description here" /></a></p>
<p>My final result should look like this :</p>
<p><a href="https://i.stack.imgur.com/6JpoV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6JpoV.png" alt="enter image description here" /></a></p>
<p>Here's the structure of my data:</p>
<pre><code>
structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28
), X1 = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
"A", "A", "A", "A"), X2 = c(0.41216973831289, 0.135689706939447,
0.209457162385174, 0.309543570254728, 0.137749096959088, 0.573368605784345,
0.428017532791265, 0.549909139998716, 0.409122667142699, 0.124117306710226,
0.992993602943196, 0.613134107410448, 0.641394855265801, 0.622613385385378,
0.828952257344686, 0.336949690008312, 0.858400408475689, 0.927912763348051,
0.602819926298281, 0.309487756908737, 0.429053378531082, 0.515696657675126,
0.792817566017885, 0.71207432761577, 0.829152651324837, 0.741688856317136,
0.150579318070398, 0.585073373582262), X3 = c("OK", "NOK", "OK",
"OK", "OK", "OK", "OK", "OK", "OK", "OK", "OK", "OK", "NOK",
"NOK", "OK", "OK", "OK", "OK", "OK", "OK", "OK", "OK", "NOK",
"OK", "NOK", "OK", "OK", "NOK")), row.names = c(NA, -28L), class = "data.frame")
</code></pre>
<p>Thanks in advance !</p>
|
[
{
"answer_id": 74545296,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "dplyr::lag() \"NOK\" library(dplyr)\n\ntest.data %>%\n filter(X3 == \"NOK\" | lag(X3) == \"NOK\")\n ID X1 X2 X3\n1 2 A 0.1356897 NOK\n2 3 A 0.2094572 OK\n3 13 A 0.6413949 NOK\n4 14 A 0.6226134 NOK\n5 15 A 0.8289523 OK\n6 23 A 0.7928176 NOK\n7 24 A 0.7120743 OK\n8 25 A 0.8291527 NOK\n9 26 A 0.7416889 OK\n10 28 A 0.5850734 NOK\n"
},
{
"answer_id": 74545350,
"author": "user2974951",
"author_id": 2974951,
"author_profile": "https://Stackoverflow.com/users/2974951",
"pm_score": 1,
"selected": false,
"text": "df[df$X3==\"NOK\" | c(\"\",head(df$X3,-1))==\"NOK\",]\n\n ID X1 X2 X3\n2 2 A 0.1356897 NOK\n3 3 A 0.2094572 OK\n13 13 A 0.6413949 NOK\n14 14 A 0.6226134 NOK\n15 15 A 0.8289523 OK\n23 23 A 0.7928176 NOK\n24 24 A 0.7120743 OK\n25 25 A 0.8291527 NOK\n26 26 A 0.7416889 OK\n28 28 A 0.5850734 NOK\n"
},
{
"answer_id": 74545589,
"author": "MF_",
"author_id": 20570319,
"author_profile": "https://Stackoverflow.com/users/20570319",
"pm_score": 0,
"selected": false,
"text": "index= which(data$X3 == \"NOK\")\nprint(index)\nlibrary(dplyr)\n\nindex_all = append(index, index+1) %>%\n sort(decreasing = F) %>%\n unique()\n\nindex_all = if(index_all[length(index_all)]>nrow(data)) index_all[- length(index_all)]\n\ndata_filter = data[index_all,]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12322285/"
] |
74,545,235
|
<p>I'm new to Flutter and Dart and I need to know how to switch pages by pressing a button. The application detects when I press the button but it does not change the page. I want to know what i did wrong. There is my code. It's basic but i want to understand my error. Thanks</p>
<pre><code>import 'package:flutter/material.dart';
void main() {
runApp(const MyHomePage());
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
Widget titleSection = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
child: Column(
children: [
Container(
padding: const EdgeInsets.only(bottom: 8),
child: const Text(
'blabla',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Text(
'Sous texte',
style: TextStyle(
color: Colors.green[500],
),
),
],
),
),
/*3*/
Icon(
Icons.square_foot,
color: Colors.yellow[500],
size: 10,
),
const Text('30°C'),
],
),
);
Column _buildButtonColumn(Color color, IconData icon, String label) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: Colors.blue),
Container(
margin: const EdgeInsets.only(top: 8),
child: Text(label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
)),
)
],
);
}
Color color = Theme.of(context).primaryColor;
Widget buttonSection = Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(color, Icons.dialpad_sharp, 'dialpad sharp'),
_buildButtonColumn(color, Icons.airplanemode_on_rounded, 'airplane'),
_buildButtonColumn(color, Icons.assistant_photo_rounded, 'assistant'),
],
);
Widget textSection = const Padding(
padding: EdgeInsets.all(32),
child: Text(
'Lake Oeschinen lies at the foot of the Blüemlisalp in the Bernese '
'Alps. Situated 1,578 meters above sea level, it is one of the '
'larger Alpine Lakes. A gondola ride from Kandersteg, followed by a '
'half-hour walk through pastures and pine forest, leads you to the '
'l = Conake, which warms to 20 degrees Celsius in the summer. Activities '
'enjoyed here include rowing, and riding the summer toboggan run.',
softWrap: true,
),
);
Widget secondSection = Container(
padding: const EdgeInsets.all(32),
child: Column(
children: [
Container(
padding: EdgeInsets.all(38),
child: const Text(
'texte ea inséré la',
style: TextStyle(
color: Colors.lightBlueAccent,
fontSize: 10,
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline,
),
),
),
Text(
'hehehehehehe',
style: TextStyle(
color: Colors.yellowAccent,
),
),
],
),
);
Widget button = Container(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/secondPage');
},
child: const Text('Launch screen'),
),
);
return MaterialApp(
title: 'Flutter layout demo',
theme: ThemeData(
primarySwatch: Colors.grey,
scaffoldBackgroundColor: Colors.white24,
),
home: Scaffold(
body: ListView(
children: [
titleSection,
Image.asset(
'images/lake.jpg',
width: 600,
height: 230,
fit: BoxFit.cover,
),
buttonSection,
textSection,
Image.asset(
'images/lala.jpg',
width: 200,
height: 200,
fit: BoxFit.cover,
),
secondSection,
button
],
),
),
initialRoute: '/',
routes: {
'/first': (context) => MyHomePage(),
'/secondPage': (context) => SecondPage(),
},
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('secondPage'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Go back!'),
),
),
);
}
}
</code></pre>
<p>I have a first page that works with some pictures, and a second, more basic page.</p>
|
[
{
"answer_id": 74545478,
"author": "Risheek Mittal",
"author_id": 16973338,
"author_profile": "https://Stackoverflow.com/users/16973338",
"pm_score": 1,
"selected": false,
"text": "class MyApp extends StatelessWidget {\n String email = '';\n String name = '';\n\n MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n initialRoute: '/',\n routes: {\n '/first': (context) => MyHomePage2(),\n '/secondPage': (context) => SecondPage(),\n },\n debugShowCheckedModeBanner: false,\n title: 'Flutter Demo',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n home: MyHomePage());\n }\n}\n"
},
{
"answer_id": 74548935,
"author": "Muhammad Waqas",
"author_id": 16322368,
"author_profile": "https://Stackoverflow.com/users/16322368",
"pm_score": 0,
"selected": false,
"text": "Navigator.of(context).push(MaterialPageRoute(\n builder: (context) => SecondPage()));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580811/"
] |
74,545,265
|
<p>We are working on a Spring Boot application. Any unknown errors at controllers layers are handled by the global exception handler classes and response is constructed there.</p>
<p>However, I see that in case of authentication at Spring authentication filter, I see that Spring sometimes return without logging or throwing any errors.</p>
<p>And the error message is provided by Spring in WWW-Authenticate header.</p>
<p>Now, in this case, if any application is not handling this scenario, I want to modify only the response body, I want to pass a JSON message explaining the error message to user in response body so that user does not have to look in header.</p>
<p>Is there any way to modify only the response body in Spring's OncePerRequestHeader? I don't see any method which allows me to simply modify the body.</p>
|
[
{
"answer_id": 74546019,
"author": "Times",
"author_id": 5151202,
"author_profile": "https://Stackoverflow.com/users/5151202",
"pm_score": 1,
"selected": false,
"text": "AuthenticationEntryPoint HttpServletResponse import lombok.RequiredArgsConstructor;\nimport org.springframework.context.support.MessageSourceAccessor;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.stereotype.Component;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\n@Component\n@RequiredArgsConstructor\npublic class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {\n\n private final MessageSourceAccessor messages;\n\n /**\n * This is invoked when a user tries to access a secured REST resource without supplying valid credentials.\n * A 401 Unauthorized HTTP Status code will be returned as there is no login page to redirect to.\n */\n @Override\n public void commence(final HttpServletRequest request, \n final HttpServletResponse response,\n final AuthenticationException authException) throws IOException {\n response.sendError(HttpServletResponse.SC_UNAUTHORIZED, messages.getMessage(\"error.unauthorized\"));\n }\n}\n AuthenticationEntryPoint @Configuration\n@EnableWebSecurity\n@RequiredArgsConstructor\npublic class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {\n\n private final CustomAuthenticationEntryPoint authenticationEntryPoint;\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n // all your other security config\n .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);\n }\n @Configuration\n@EnableWebSecurity\n@RequiredArgsConstructor\npublic class WebSecurityConfiguration {\n\n private final CustomAuthenticationEntryPoint authenticationEntryPoint;\n\n @Bean\n SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception {\n return http\n // all your other security config\n .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);\n }\n}\n AuthenticationEntryPoint BearerTokenAuthenticationEntryPoint AuthenticationEntryPoint"
},
{
"answer_id": 74547059,
"author": "xerx593",
"author_id": 592355,
"author_profile": "https://Stackoverflow.com/users/592355",
"pm_score": 1,
"selected": false,
"text": "BasicAuthenticationEntryPoint private static AuthenticationEntryPoint authenticationEntryPoint() {\n BasicAuthenticationEntryPoint result = new BasicAuthenticationEntryPoint() {\n // inline:\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {\n response.addHeader( // identic/similar to super method\n \"WWW-Authenticate\", String.format(\"Basic realm=\\\"%s\\\"\", getRealmName())\n );\n // subtle difference:\n response.setStatus(HttpStatus.UNAUTHORIZED.value() /*, no message! */);\n // \"print\" custom to \"response\":\n response.getWriter().format(\n \"{\\\"error\\\":{\\\"message\\\":\\\"%s\\\"}}\", authException.getMessage()\n );\n }\n };\n // basic specific/default:\n result.setRealmName(\"Realm\");\n return result;\n}\n package com.example.security.custom.entrypoint;\n\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.web.servlet.MockMvc;\nimport static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;\nimport static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;\nimport static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;\n\n@AutoConfigureMockMvc\n@SpringBootTest(properties = {\"spring.security.user.password=!test2me\"})\nclass SecurityCustomEntrypointApplicationTests {\n\n @Autowired\n private MockMvc mvc;\n\n @Test\n public void testWrongCredentials() throws Exception {\n mvc\n .perform(get(\"/secured\").with(httpBasic(\"unknown\", \"wrong\")))\n .andDo(print())\n .andExpectAll(\n unauthenticated(),\n status().isUnauthorized(),\n header().exists(\"WWW-Authenticate\"),\n content().bytes(new byte[0]) // !! no content\n );\n }\n\n @Test\n void testCorrectCredentials() throws Exception {\n mvc\n .perform(get(\"/secured\").with(httpBasic(\"user\", \"!test2me\")))\n .andDo(print())\n .andExpectAll(\n status().isOk(),\n content().string(\"Hello\")\n );\n }\n\n @Test\n void testNoCredentials() throws Exception {\n mvc\n .perform(get(\"/secured\"))\n .andDo(print())\n .andExpectAll(\n status().isUnauthorized(),\n header().exists(\"WWW-Authenticate\"),\n jsonPath(\"$.error.message\").exists()\n );\n }\n}\n package com.example.security.custom.entrypoint;\n\nimport java.io.IOException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.HttpStatus;\nimport static org.springframework.security.config.Customizer.withDefaults;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.web.AuthenticationEntryPoint;\nimport org.springframework.security.web.SecurityFilterChain;\nimport org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@SpringBootApplication\npublic class SecurityCustomEntrypointApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SecurityCustomEntrypointApplication.class, args);\n }\n\n @Controller\n static class SecuredController {\n\n @GetMapping(\"secured\")\n @ResponseBody\n public String secured() {\n return \"Hello\";\n }\n }\n\n @Configuration\n static class SecurityConfig {\n\n @Bean\n public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n return http\n .authorizeRequests()\n .anyRequest().authenticated()\n .and()\n .httpBasic(withDefaults())\n .exceptionHandling()\n .authenticationEntryPoint(authenticationEntryPoint()) \n // ...\n .and().build();\n }\n // @Bean (and/) or static...: you decide!;)\n private static AuthenticationEntryPoint authenticationEntryPoint() {\n BasicAuthenticationEntryPoint result = new BasicAuthenticationEntryPoint() {\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {\n response.addHeader(\n \"WWW-Authenticate\", String.format(\"Basic realm=\\\"%s\\\"\", getRealmName())\n );\n response.setStatus(HttpStatus.UNAUTHORIZED.value());\n response.getWriter().format(\n \"{\\\"error\\\":{\\\"message\\\":\\\"%s\\\"}}\", authException.getMessage()\n );\n }\n };\n result.setRealmName(\"Realm\");\n return result;\n }\n }\n}\n response testWrongCredentials() http.formLogin().failureHandler((req, resp, exc)->{/*your code here*/})... BasicAuthenticationFilter.on[Uns|S]uccessfulAuthentication(req,resp,exc) //@Bean possible resp. needed, when autowire.., for simplicity, just:\nprivate static BasicAuthenticationFilter customBasicAuthFilter(AuthenticationManager authenticationManager) {\n return new BasicAuthenticationFilter(authenticationManager\n /*, entryPoint */) {\n @Override\n protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {\n System.err.println(\"Aha!\");\n writeToResponse(response, failed); \n }\n\n // @Override ...\n };\n}\n// with:\nprivate static void writeToResponse(HttpServletResponse response, Exception failed) throws IOException {\n response.getWriter().format(\n \"{\\\"error\\\":{\\\"message\\\":\\\"%s\\\"}}\", failed.getMessage()\n );\n}\n filterChain http.addFilter(customBasicAuthFilter(authenticationManager));\n .httpBasic(...) BasicAuthenticationFilter AuthenticationEntryPoint .exceptionHandling().authenticationEntryPoint(...) XXXFilter#anyVisibleMethod authenticationManager==null static class CustomDsl extends AbstractHttpConfigurer<CustomDsl, HttpSecurity> {\n\n @Override\n public void configure(HttpSecurity http) throws Exception {\n AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);\n http.addFilter(customBasicAuthFilter(authenticationManager));\n }\n\n public static CustomDsl customDsl() {\n return new CustomDsl();\n }\n}\n @Bean\npublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {\n return http\n .authorizeRequests()\n .anyRequest().authenticated()\n .and()\n .apply(CustomDsl.customDsl()) // before httpBasic()!\n .and()\n .httpBasic(withDefaults())\n .exceptionHandling() // this is still needed ...\n .authenticationEntryPoint(authenticationEntryPoint()) // ... for the \"anonymous\" (test) case!\n .and()\n .build();\n}\n @Test\npublic void testWrongCredentials() throws Exception {\n mvc\n .perform(get(\"/secured\").with(httpBasic(\"unknown\", \"wrong\")))\n .andDo(print())\n .andExpectAll(\n unauthenticated(),\n status().isUnauthorized(),\n header().exists(\"WWW-Authenticate\"),\n jsonPath(\"$.error.message\").exists() // !#\n );\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3610891/"
] |
74,545,334
|
<p>I am trying to add search and page to my url for searching and pagination on a page.</p>
<pre><code> const urlParams = new URLSearchParams(window.location.search);
if(!urlParams.has('search'){
urlParams.append('search', question);
}
if(!urlParams.has('page'){
urlParams.append('page', pageIndex);
}
</code></pre>
<p>This appears to do nothing to the actual url.
But when I call urlParams.toString()
then I can see that they have been added, but they are not in the actual url in the browser.</p>
<p>I'm using Chrome 107, so it should support it.
Am I missing something?</p>
<p>The documentation has not helped me so far.</p>
|
[
{
"answer_id": 74545496,
"author": "ericmp",
"author_id": 14569750,
"author_profile": "https://Stackoverflow.com/users/14569750",
"pm_score": 0,
"selected": false,
"text": "path urlParams history.pushState() const question = \"the question\";\nconst pageIndex = 3;\n\nconst urlParams = new URLSearchParams(window.location.search);\n\nif (! urlParams.has('search')) {\n urlParams.append('search', question);\n}\n\nif (! urlParams.has('page')) {\n urlParams.append('page', pageIndex);\n}\n\nconst path = window.location.href.split('?')[0];\nconst newURL = `${path}?${urlParams}`;\n\nhistory.pushState({}, '', newURL);\n"
},
{
"answer_id": 74545593,
"author": "mohammad ali",
"author_id": 9545762,
"author_profile": "https://Stackoverflow.com/users/9545762",
"pm_score": 2,
"selected": true,
"text": "window.loacation.search = urlParams.toString()\n history let url = new URL(window.location.href);\nif(!(url.searchParams.has('search'))){\n url.searchParams.append('search', question);\n}\nif(!(url.searchParams.has('page'))){\n url.searchParams.append('page', pageIndex);\n}\nhistory.pushState({},'',url.href);\n page search url.searchParams.set() url.searchParams.set('page', pageIndex);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6848931/"
] |
74,545,340
|
<p>I try to get action after pressing back button in top toolbar</p>
<pre><code>class TagsFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as AppCompatActivity?)?.supportActionBar?.title = "$selectedItemText Tags"
(activity as AppCompatActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
// This callback will only be called when MyFragment is at least Started.
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
Log.d(InTorry.TAG, "TagsFragment: back BTN Pressed")
}
}
}
</code></pre>
<p>Unfortunately, it doest log anything</p>
<p>I found I should add OnBackPressedCallback but it doesnt work as well :</p>
<pre><code>class TagsFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val selectedItemText = arguments?.getString("selectedItemText")//get arguments
(activity as AppCompatActivity?)?.supportActionBar?.title = "$selectedItemText Tags"
(activity as AppCompatActivity?)?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity as AppCompatActivity?)?.onBackPressedDispatcher?.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d(InTorry.TAG, "Fragment back pressed invoked")
// Do custom work here
// if you want onBackPressed() to be called as normal afterwards
if (isEnabled) {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
)
}
</code></pre>
<p>Kind regards
Jack</p>
|
[
{
"answer_id": 74545496,
"author": "ericmp",
"author_id": 14569750,
"author_profile": "https://Stackoverflow.com/users/14569750",
"pm_score": 0,
"selected": false,
"text": "path urlParams history.pushState() const question = \"the question\";\nconst pageIndex = 3;\n\nconst urlParams = new URLSearchParams(window.location.search);\n\nif (! urlParams.has('search')) {\n urlParams.append('search', question);\n}\n\nif (! urlParams.has('page')) {\n urlParams.append('page', pageIndex);\n}\n\nconst path = window.location.href.split('?')[0];\nconst newURL = `${path}?${urlParams}`;\n\nhistory.pushState({}, '', newURL);\n"
},
{
"answer_id": 74545593,
"author": "mohammad ali",
"author_id": 9545762,
"author_profile": "https://Stackoverflow.com/users/9545762",
"pm_score": 2,
"selected": true,
"text": "window.loacation.search = urlParams.toString()\n history let url = new URL(window.location.href);\nif(!(url.searchParams.has('search'))){\n url.searchParams.append('search', question);\n}\nif(!(url.searchParams.has('page'))){\n url.searchParams.append('page', pageIndex);\n}\nhistory.pushState({},'',url.href);\n page search url.searchParams.set() url.searchParams.set('page', pageIndex);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086818/"
] |
74,545,343
|
<p>How can we use custom code to generate a password for the forgot password user endpoint API?</p>
|
[
{
"answer_id": 74545496,
"author": "ericmp",
"author_id": 14569750,
"author_profile": "https://Stackoverflow.com/users/14569750",
"pm_score": 0,
"selected": false,
"text": "path urlParams history.pushState() const question = \"the question\";\nconst pageIndex = 3;\n\nconst urlParams = new URLSearchParams(window.location.search);\n\nif (! urlParams.has('search')) {\n urlParams.append('search', question);\n}\n\nif (! urlParams.has('page')) {\n urlParams.append('page', pageIndex);\n}\n\nconst path = window.location.href.split('?')[0];\nconst newURL = `${path}?${urlParams}`;\n\nhistory.pushState({}, '', newURL);\n"
},
{
"answer_id": 74545593,
"author": "mohammad ali",
"author_id": 9545762,
"author_profile": "https://Stackoverflow.com/users/9545762",
"pm_score": 2,
"selected": true,
"text": "window.loacation.search = urlParams.toString()\n history let url = new URL(window.location.href);\nif(!(url.searchParams.has('search'))){\n url.searchParams.append('search', question);\n}\nif(!(url.searchParams.has('page'))){\n url.searchParams.append('page', pageIndex);\n}\nhistory.pushState({},'',url.href);\n page search url.searchParams.set() url.searchParams.set('page', pageIndex);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9998252/"
] |
74,545,358
|
<p>In Flutter I have Gridview with three static containers. I am trying to achieve tap action in the Container. The container have Image and Text. I tried with Inkwell.</p>
<pre><code> @override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "4.0",
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: GridView.count(
crossAxisCount: 3,
children: [
Container(
color: Colors.green,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.work,
color: Colors.white,
size: 60,
),
Text("Work ", style: TextStyle(color: Colors.white, fontSize: 18))
],
),
),
Container(
color: Colors.green,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(
Icons.account_circle,
color: Colors.white,
),
Text("Account", style: TextStyle(color: Colors.white))
],
),
),
Container(
color: Colors.green,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(
Icons.message,
color: Colors.white,
),
Text("Messages", style: TextStyle(color: Colors.white))
],
),
),
],
shrinkWrap: true,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
)));
}
</code></pre>
<p>I am not sure about where to set InkWell in the container. I am bit new to Flutter, Any suggestions would be helpful.</p>
|
[
{
"answer_id": 74545496,
"author": "ericmp",
"author_id": 14569750,
"author_profile": "https://Stackoverflow.com/users/14569750",
"pm_score": 0,
"selected": false,
"text": "path urlParams history.pushState() const question = \"the question\";\nconst pageIndex = 3;\n\nconst urlParams = new URLSearchParams(window.location.search);\n\nif (! urlParams.has('search')) {\n urlParams.append('search', question);\n}\n\nif (! urlParams.has('page')) {\n urlParams.append('page', pageIndex);\n}\n\nconst path = window.location.href.split('?')[0];\nconst newURL = `${path}?${urlParams}`;\n\nhistory.pushState({}, '', newURL);\n"
},
{
"answer_id": 74545593,
"author": "mohammad ali",
"author_id": 9545762,
"author_profile": "https://Stackoverflow.com/users/9545762",
"pm_score": 2,
"selected": true,
"text": "window.loacation.search = urlParams.toString()\n history let url = new URL(window.location.href);\nif(!(url.searchParams.has('search'))){\n url.searchParams.append('search', question);\n}\nif(!(url.searchParams.has('page'))){\n url.searchParams.append('page', pageIndex);\n}\nhistory.pushState({},'',url.href);\n page search url.searchParams.set() url.searchParams.set('page', pageIndex);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1954020/"
] |
74,545,391
|
<p>I am trying to find a minimum value in a dataframe with all column values.</p>
<p><strong>Sample data:</strong></p>
<pre><code>**Fitness Value MSU Locations MSU Range**
1.180694 {17, 38, 15} 2.017782
1.202132 {10, 22, 39} 2.032507
1.179097 {10, 5, 38} 2.048932
1.175793 {27, 20, 36} 1.820395
1.187460 {33, 10, 34} 1.922506
</code></pre>
<p>I am trying to find a minimum value in <code>Fitness Value</code> column and keeping the whole row record. For intance, If I get the minimum value (<code>1.175793</code>), I want to keep its respective header values which are <code>{27, 20, 36}</code> and <code>1.820395</code>. So, the final <strong>output</strong> should be:</p>
<pre><code>1.175793 {27, 20, 36} 1.820395
</code></pre>
<p><strong>My sample code:</strong></p>
<pre><code>minValue = df_2['Fitness Value'].min()
print("minimum value in column 'y': " , minValue)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>minimum value in column 'y': 1.175793
</code></pre>
<p><strong>I also tried this code:</strong></p>
<pre><code>df_y = pd.DataFrame ()
df_y = df_2.loc[[df_2['Fitness Value']].min()
</code></pre>
<p><strong>How can I get an output like this?</strong></p>
<pre><code>1.175793 {27, 20, 36} 1.820395
</code></pre>
|
[
{
"answer_id": 74545400,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "Series.idxmin DataFrame.loc Fitness Value df = df_2.loc[[df_2['Fitness Value'].idxmin()]]\nprint (df)\n Fitness Value MSU Locations MSU Range\n3 1.175793 {27,20,36} 1.820395\n L = df_2.loc[df_2['Fitness Value'].idxmin()].tolist()\n out = []\nfor x in range(0, 2, 1): \n new_generation = genetic_algorithm(initial_pop_chromosome_fitness) \n initial_pop_chromosome_fitness = new_generation\n\n #create Series and append to list of Series out\n s = df_2.loc[df_2['Fitness Value'].idxmin()]\n out.append(L)\n\ndf = pd.DataFrame(out)\n\n \n"
},
{
"answer_id": 74545406,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "min df.loc[df['Fitness Value'].eq(df['Fitness Value'].min())]\n Fitness Value MSU Locations MSU Range\n3 1.175793 {27, 20, 36} 1.820395\n idxmin"
},
{
"answer_id": 74545528,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 2,
"selected": false,
"text": "minValue df[df[\"Fitness Value\"]==minValue]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13373167/"
] |
74,545,392
|
<p>I am developing a reusable workflow using <a href="https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#runs-for-javascript-actions" rel="nofollow noreferrer">Javascript</a> actions by following this <a href="https://docs.github.com/en/actions/creating-actions/creating-a-javascript-action#prerequisites" rel="nofollow noreferrer">tutorial</a>. My <code>action.yml</code> looks like this.</p>
<pre><code>name: "Test"
description: "Reusable workflow"
inputs:
input-one:
required: false
type: string
runs:
using: 'node16'
main: 'dist/index.js'
</code></pre>
<p>But my question is how to access the <em><strong>secrets</strong></em> in <code>dist/index.js</code>?. Please note that I don't want the user to supply the secret as input, I would like to store the secret in my reusable workflow repository and use it whenever it's needed.</p>
<p>I tried to change the <code>action.yml</code> with <code>env</code>(So that I can use node <code>process.env</code> API to get the secret) but it's failing with an error saying that <code>Unexpected value 'env'</code>.</p>
<pre><code>name: "Test"
description: "Reusable workflow"
inputs:
input-one:
required: false
type: string
runs:
using: 'node16'
main: 'dist/index.js'
env:
DUMMY_VAL: ${{ secrets.MY_REPOSITORY_SECRET }}
</code></pre>
|
[
{
"answer_id": 74573990,
"author": "lukee",
"author_id": 1606260,
"author_profile": "https://Stackoverflow.com/users/1606260",
"pm_score": 3,
"selected": true,
"text": "default on:\n workflow_call:\n secrets:\n access-token:\n description: 'Your secret'\n required: false\n default: ${{ secrets.your-secret }}\n\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6699447/"
] |
74,545,435
|
<p>Let us assume that we have an enum class:</p>
<pre><code>class MyEnum(Enum):
foo = 1
bar = 2
</code></pre>
<p>How to get the list of values <code>[1, 1, 2]</code> from the above list of enumerations?</p>
<pre><code>mylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar]
</code></pre>
<p>I know it is possible to create a new list using list comprehension, but I am wondering if there exists a more natural and straighforward way to get the same output.</p>
|
[
{
"answer_id": 74545462,
"author": "hide1nbush",
"author_id": 19825642,
"author_profile": "https://Stackoverflow.com/users/19825642",
"pm_score": 2,
"selected": true,
"text": "name value Enum .name .value class MyEnum(Enum):\n foo = 1\n bar = 2\nmylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar]\nmy_enum_val_list = [i.value for i in mylist]\n IntEnum class MyEnum(IntEnum):\n foo = 1\n bar = 2\nmylist = [MyEnum.foo, MyEnum.foo, MyEnum.bar]\n"
},
{
"answer_id": 74545551,
"author": "Piotr Sawicki",
"author_id": 8254496,
"author_profile": "https://Stackoverflow.com/users/8254496",
"pm_score": 0,
"selected": false,
"text": "myvaluelist = list(map(lambda _ : _.value, mylist))\n myvaluelist = [_.value for _ in mylist]\n"
},
{
"answer_id": 74545669,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "nb_foo=2\nnb_bar=1\n\nmylist1=[MyEnum.foo for i in range(nb_foo)]\nmylist2=[MyEnum.bar for i in range(nb_bar)]\n\nmylist = mylist1 + mylist2\nprint(mylist)\n [1, 1, 2]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4613815/"
] |
74,545,444
|
<p>I'm trying to create multiplane vms using for each function in terraform.</p>
<p><strong>Resource Group</strong></p>
<pre><code>resource "azurerm_resource_group" "rg" {
name = "${var.prefix}-rg"
location = "east us 2"
tags = var.tags
}
</code></pre>
<p><strong>VNET</strong></p>
<pre><code>resource "azurerm_virtual_network" "vnet" {
name = "${var.prefix}-network-1"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
tags = var.tags
}
</code></pre>
<p><strong>Subnet</strong></p>
<pre><code>resource "azurerm_subnet" "subnet" {
name = "${var.prefix}-network-subnet-1"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.2.0/24"]
}
</code></pre>
<p><strong>Variables for NICS</strong></p>
<pre><code>variable "nics" {
type = map
default = {
nic3 = {
name = "ubuntu-test-3"
}
nic4 = {
name = "ubuntu-test-4"
}
}
}
</code></pre>
<p><strong>NICS</strong></p>
<pre><code>resource "azurerm_network_interface" "nics" {
for_each = var.nics
name = each.value.name
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
ip_configuration {
name = "${each.value.name}-conf-1"
subnet_id = azurerm_subnet.subnet.id
private_ip_address_allocation = "Dynamic"
}
tags = var.tags
}
</code></pre>
<p><strong>Variables for VMS</strong></p>
<pre><code>variable "vms" {
description = "Virtual Machines"
type = map
default = {
vm3 = {
name = "ubuntu-test-3"
size = "Standard_DS1_v2"
}
vm4 = {
name = "ubuntu-test-4"
size = "Standard_DS1_v2"
}
}
</code></pre>
<p>}</p>
<p><strong>and the block for the VM ( not completed - i wrote only the section that i have issue with )</strong></p>
<pre><code>resource "azurerm_virtual_machine" "vms" {
for_each = var.vms
name = each.value.name
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
vm_size = each.value.size
tags = var.tags
network_interface_ids = [
azurerm_network_interface.nics[each.value].id,
]
</code></pre>
<p><strong>The issue is with this section</strong></p>
<pre><code>network_interface_ids = [
azurerm_network_interface.nics[each.value].id,
]
</code></pre>
<p><strong>I'm getting ERROR</strong></p>
<pre><code>│ Error: Invalid index
│
│ on main.tf line 247, in resource "azurerm_virtual_machine" "vms":
│ 247: azurerm_network_interface.nics[each.value].id,
│ ├────────────────
│ │ azurerm_network_interface.nics is object with 2 attributes
│ │ each.value is object with 2 attributes
│
│ The given key does not identify an element in this collection value: string required.
</code></pre>
<p><strong>Also tried with</strong></p>
<pre><code>network_interface_ids = [
azurerm_network_interface.nics[each.key].id,
]
</code></pre>
<p><strong>and got ERROR</strong></p>
<pre><code>│ Error: Invalid index
│
│ on main.tf line 249, in resource "azurerm_virtual_machine" "vms":
│ 249: azurerm_network_interface.nics[each.key].id,
│ ├────────────────
│ │ azurerm_network_interface.nics is object with 2 attributes
│ │ each.key is "vm3"
│
│ The given key does not identify an element in this collection value.
╵
╷
│ Error: Invalid index
│
│ on main.tf line 249, in resource "azurerm_virtual_machine" "vms":
│ 249: azurerm_network_interface.nics[each.key].id,
│ ├────────────────
│ │ azurerm_network_interface.nics is object with 2 attributes
│ │ each.key is "vm4"
│
│ The given key does not identify an element in this collection value
</code></pre>
<p>What I'm doing wrong ?</p>
|
[
{
"answer_id": 74546175,
"author": "Marko E",
"author_id": 8343484,
"author_profile": "https://Stackoverflow.com/users/8343484",
"pm_score": 1,
"selected": false,
"text": "variable \"vms\" {\n description = \"Virtual Machines\"\n type = map\n default = {\n vm3 = {\n name = \"ubuntu-test-3\"\n size = \"Standard_DS1_v2\"\n nic = \"nic3\"\n }\n vm4 = {\n name = \"ubuntu-test-4\"\n size = \"Standard_DS1_v2\"\n nic = \"nic4\"\n }\n }\n}\n resource \"azurerm_virtual_machine\" \"vms\" {\n for_each = var.vms\n name = each.value.name\n resource_group_name = azurerm_resource_group.rg.name\n location = azurerm_resource_group.rg.location\n vm_size = each.value.size\n tags = var.tags\n network_interface_ids = [\n azurerm_network_interface.nics[each.value.nic].id,\n ]\n}\n for_each resource \"azurerm_virtual_machine\" \"vms\" {\n for_each = azurerm_network_interface.nics\n name = each.value.name\n resource_group_name = azurerm_resource_group.rg.name\n location = azurerm_resource_group.rg.location\n vm_size = var.vm_size # or set it to be equal to \"Standard_DS1_v2\"\n tags = var.tags\n network_interface_ids = [\n each.value.id,\n ]\n}\n vm_size variable \"vm_size\" {\n type = string\n description = \"VM size.\"\n\n default = \"Standard_DS1_v2\"\n}\n vms"
},
{
"answer_id": 74548497,
"author": "Swarna Anipindi",
"author_id": 20264791,
"author_profile": "https://Stackoverflow.com/users/20264791",
"pm_score": 3,
"selected": true,
"text": "network_interface_ids = [azurerm_network_interface.nics[each.value.nic].id,] provider \"azurerm\" {\n features {}\n }\nvariable \"prefix\" {\n default = \"rg_swarna\"\n}\n\nresource \"azurerm_resource_group\" \"rg\" {\n name = \"${var.prefix}-rg\"\n location = \"West US\"\n // tags = var.tags\n}\nresource \"azurerm_virtual_network\" \"vnet\" {\n name = \"${var.prefix}-network-1\"\n address_space = [\"10.0.0.0/16\"]\n location = azurerm_resource_group.rg.location\n resource_group_name = azurerm_resource_group.rg.name\n // tags = var.tags\n}\nresource \"azurerm_subnet\" \"subnet\" {\n name = \"${var.prefix}-network-subnet-1\"\n resource_group_name = azurerm_resource_group.rg.name\n virtual_network_name = azurerm_virtual_network.vnet.name\n address_prefixes = [\"10.0.2.0/24\"]\n}\nresource \"azurerm_network_interface\" \"nics\" {\n for_each = var.nics\n name = each.value.name\n location = azurerm_resource_group.rg.location\n resource_group_name = azurerm_resource_group.rg.name\n\n ip_configuration {\n name = \"${each.value.name}-conf-1\"\n subnet_id = azurerm_subnet.subnet.id\n private_ip_address_allocation = \"Dynamic\"\n }\n\n //tags = var.tags\n}\nresource \"azurerm_virtual_machine\" \"vms\" {\n for_each = var.vms\n name = each.value.name\n vm_size = \"Standard_DS1_v2\"\n resource_group_name = azurerm_resource_group.rg.name\n location = azurerm_resource_group.rg.location\n network_interface_ids = [azurerm_network_interface.nics[each.value.nic].id,]\n storage_os_disk {\n name = \"myosdisk${each.value.name}\"\n caching = \"ReadWrite\"\n create_option = \"FromImage\"\n managed_disk_type = \"Standard_LRS\"\n }\n storage_image_reference {\n publisher = \"Canonical\"\n offer = \"UbuntuServer\"\n sku = \"16.04-LTS\"\n version = \"latest\"\n }\n os_profile {\n computer_name = \"TestDemo\"\n admin_username = \"azureuser\"\n admin_password = \"*****@123\"\n }\n os_profile_linux_config {\n disable_password_authentication = false\n }\n}\n variable \"allowed_subnet_ids\" {\n type = list(string)\n description = \"access\"\n}\nvariable \"nics\" {\n type = map\n default = {\n \n nic3 = {\n name = \"ubun3\"\n }\n\n nic4 = {\n name = \"ubun4\"\n }\n }\n}\nvariable \"vms\" {\n description = \"VM\"\n type = map\n default = {\n vm3 = {\n name = \"ubun3\"\n size = \"Standard_DS1_v2\"\n nic = \"nic3\"\n }\n vm4 = {\n name = \"ubuntu4\"\n size = \"Standard_DS1_v2\"\n nic = \"nic4\"\n }\n }\n}\nvariable \"allowed_ips\" {\n type = list(string)\n description = \"IP addresses\"\n}\n\nvariable \"sku\" {\n type = string\n description = \"SKU\"\n}\nvariable \"resource_group_name\" {\n type = string\n description = \"resource_group_name\"\n}\nvariable \"location\" {\n type = string\n description = \"location\"\n} \n terraform plan\nterraform apply -auto-approve\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17173417/"
] |
74,545,457
|
<p>in my <code>Laravel</code> app I have 3 tables : <code>users</code>, <code>documents</code> and <code>type_documents</code>, the user have multiple documents and document have one type_document <br></p>
<pre><code>| Documents |
| -------- |
| id |
| file |
| type_document_id|
| user_id |
| type_documents |
| -------- |
| id |
| name |
| users |
| -------- |
| id |
| name |
| type_document_d|
</code></pre>
<p>I want select the types that are not used in <code>documents</code> table for the current user with <code>eloquent</code> <br>
I try with this, but it give me the used type_documents :</p>
<pre><code>$document_types = TypeDocument::leftJoin('docments' , function ($join) {
$join->on('type_documents.id', '=', 'douments.type_document_id')
->where('documents.user_id', auth()->id());
})
->applyFilters($request->all())
->latest()
->paginateData($limit);
</code></pre>
<p>I use Laravel version 8</p>
|
[
{
"answer_id": 74545695,
"author": "Maulik",
"author_id": 20581202,
"author_profile": "https://Stackoverflow.com/users/20581202",
"pm_score": 0,
"selected": false,
"text": "TypeDocument::whereNotIn('id', function($query){\n\n $query->select('type_document_id')\n ->from(with(new Documents)->getTable())\n ->where('type_document_id', $query->id)\n ->where('user_id', auth()->id());\n \n})->get();\n"
},
{
"answer_id": 74545699,
"author": "Erhan URGUN",
"author_id": 9476192,
"author_profile": "https://Stackoverflow.com/users/9476192",
"pm_score": 1,
"selected": true,
"text": "<?php\n// whereNotIn\n$types = TypeDocument::whereNotIn('id', function($query) {\n $query->select('type_document_id')\n ->from('documents')\n ->where('user_id', auth()->id);\n})->get();\n <?php\n// whereNotExists\n$types = TypeDocument::whereNotExists(function($query) {\n $query->select(DB::raw(1))\n ->from('documents')\n ->whereRaw('type_documents.id = documents.type_document_id')\n ->where('user_id', '=', Auth::user()->id);\n})->get();\n <?php\n// leftJoin\n$types = TypeDocument::leftJoin('documents', function($join) {\n $join->on('type_documents.id', '=', 'documents.type_document_id')\n ->where('user_id', '=', Auth::user()->id);\n})->whereNull('documents.type_document_id')->get();\n"
},
{
"answer_id": 74546159,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 1,
"selected": false,
"text": "TypeDocument::class User::class public function users()\n{\n return $this->belongsToMany(User::class, 'documents', 'type_document_id', 'user_id')->withPivot('file');\n}\n TypeDocument::whereDoesntHave('users', function($userQuery) {\n $userQuery->where('users.id', '=', auth()->id());\n }) \n ->applyFilters($request->all())\n ->latest()\n ->paginateData($limit);\n public function documents()\n{\n return $this->hasMany(Document::class);\n}\n public function user()\n{\n return $this->belongsTo(User::class);\n}\n TypeDocument::whereDoesntHave('documents.user', function($userQuery) {\n $userQuery->where('users.id', '=', auth()->id());\n }) \n ->applyFilters($request->all())\n ->latest()\n ->paginateData($limit);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17505634/"
] |
74,545,459
|
<p>I would like to know how I print my application logs to console in a specific format of my choice.</p>
<p>Our ELK stack's FileBeat daemon is configured to recognise only those Kubernetes pod logs that are in this pattern - <code>appender.console.layout.pattern = %d{ISO8601} - %-5level: %msg%n</code></p>
<p>This is done so as to keep track of all incoming requests and some attributes of responses. Generally <code>msg</code> part in above pattern contains http requests and responses. Now, I built a new Microservice in Spring Boot that does not have any http interactions. It consumes messages from Kafka and processes them. So, the logs would be mostly application log statements and exceptions.</p>
<p>If I follow the above pattern, my exceptions will be logged as strings and I cannot index logs and filter based on any keys in Kibana. To solve this problem, I need to log msg as JSON just like in JSON layout of log4j2.</p>
<p>I tried putting the following in log4j2.properties file. I am getting a cool json for each log statement but filebeat won't pick this up since it is configured to pick only logs in previously specified format.</p>
<pre><code>log4j2.appender.console.json.type = JsonTemplateLayout
log4j2.appender.console.json.eventTemplateUri = classpath:EcsLayout.json
</code></pre>
<p>Could anyone help me arrive at a solution where I can log in the acceptable format only which the <code>msg</code> part is a json that looks like following.</p>
<pre><code>{
"@timestamp": "2017-05-25T19:56:23.370Z",
"ecs.version": "1.2.0",
"log.level": "ERROR",
"message": "Hello, error!",
"process.thread.name": "main",
"log.logger": "org.apache.logging.log4j.JsonTemplateLayoutDemo",
"error.type": "java.lang.RuntimeException",
"error.message": "test",
"error.stack_trace": "java.lang.RuntimeException: test\n\tat org.apache.logging.log4j.JsonTemplateLayoutDemo.main(JsonTemplateLayoutDemo.java:11)\n"
}
</code></pre>
<p>In essence, my log statement should be</p>
<pre><code>2022-11-23T15:50:05,802 - ERROR : {"@timestamp":"2017-05-25T19:56:23.370Z","ecs.version":"1.2.0","log.level":"ERROR","message":"Hello, error!","process.thread.name":"main","log.logger":"org.apache.logging.log4j.JsonTemplateLayoutDemo","error.type":"java.lang.RuntimeException","error.message":"test","error.stack_trace":"java.lang.RuntimeException: test\n\tat org.apache.logging.log4j.JsonTemplateLayoutDemo.main(JsonTemplateLayoutDemo.java:11)\n"}
</code></pre>
<p>I tried using Pattern Layout and JSON Layout. But I am expecting a Custom Layout that mentioned above.</p>
|
[
{
"answer_id": 74545695,
"author": "Maulik",
"author_id": 20581202,
"author_profile": "https://Stackoverflow.com/users/20581202",
"pm_score": 0,
"selected": false,
"text": "TypeDocument::whereNotIn('id', function($query){\n\n $query->select('type_document_id')\n ->from(with(new Documents)->getTable())\n ->where('type_document_id', $query->id)\n ->where('user_id', auth()->id());\n \n})->get();\n"
},
{
"answer_id": 74545699,
"author": "Erhan URGUN",
"author_id": 9476192,
"author_profile": "https://Stackoverflow.com/users/9476192",
"pm_score": 1,
"selected": true,
"text": "<?php\n// whereNotIn\n$types = TypeDocument::whereNotIn('id', function($query) {\n $query->select('type_document_id')\n ->from('documents')\n ->where('user_id', auth()->id);\n})->get();\n <?php\n// whereNotExists\n$types = TypeDocument::whereNotExists(function($query) {\n $query->select(DB::raw(1))\n ->from('documents')\n ->whereRaw('type_documents.id = documents.type_document_id')\n ->where('user_id', '=', Auth::user()->id);\n})->get();\n <?php\n// leftJoin\n$types = TypeDocument::leftJoin('documents', function($join) {\n $join->on('type_documents.id', '=', 'documents.type_document_id')\n ->where('user_id', '=', Auth::user()->id);\n})->whereNull('documents.type_document_id')->get();\n"
},
{
"answer_id": 74546159,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 1,
"selected": false,
"text": "TypeDocument::class User::class public function users()\n{\n return $this->belongsToMany(User::class, 'documents', 'type_document_id', 'user_id')->withPivot('file');\n}\n TypeDocument::whereDoesntHave('users', function($userQuery) {\n $userQuery->where('users.id', '=', auth()->id());\n }) \n ->applyFilters($request->all())\n ->latest()\n ->paginateData($limit);\n public function documents()\n{\n return $this->hasMany(Document::class);\n}\n public function user()\n{\n return $this->belongsTo(User::class);\n}\n TypeDocument::whereDoesntHave('documents.user', function($userQuery) {\n $userQuery->where('users.id', '=', auth()->id());\n }) \n ->applyFilters($request->all())\n ->latest()\n ->paginateData($limit);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580822/"
] |
74,545,479
|
<p>I would like to add a string at the beginning of each row- either positive or negative - depending on the value in the columns:
<a href="https://i.stack.imgur.com/iSDUK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iSDUK.png" alt="enter image description here" /></a></p>
<p>I keep getting ValueError, as per screenshot</p>
|
[
{
"answer_id": 74545559,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "Series.map df.index = df['positive'].eq(1).map({True:'positive_', False:'negative_'}) + df.index\n numpy.where df.index = np.where(df['positive'].eq(1), 'positive_','negative_') + df.index\n"
},
{
"answer_id": 74545633,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "pandas.from_dummies cols = ['positive', 'negative']\n\nuser_input_1.index = (pd.from_dummies(user_input_1[cols]).squeeze()\n +'_'+user_input_1.index\n )\n Score positive negative\nA 1 1 0\nB 2 0 1\nC 3 1 0\n Score positive negative\npositive_A 1 1 0\nnegative_B 2 0 1\npositive_C 3 1 0\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17277677/"
] |
74,545,516
|
<p>What is the best way to convert an HH:MM:SS format string to an integer in minutes?</p>
<p><strong>For example</strong> <code>"01:10:00"</code> would give me an integer of 70.</p>
<p>It would round down so <code>"01:10:30"</code> would also give me 70.</p>
|
[
{
"answer_id": 74545578,
"author": "OMi Shah",
"author_id": 5882307,
"author_profile": "https://Stackoverflow.com/users/5882307",
"pm_score": 1,
"selected": false,
"text": "final String time = '01:10:00'; // your time string\n\nfinal parts = time.split(':').map((e) => int.parse(e)).toList(); // split the time string by colon as separator and then parse each splitted string to int using the map method.\n\nfinal minutes = Duration(hours: parts[0], minutes: parts[1], seconds: parts[2])\n .inMinutes; // create a duration instance from the splitted time (hours, minutes and seconds) and then use .inMinutes to get the duration in minutes\n\nlog(minutes.toString()); // 70\n"
},
{
"answer_id": 74545655,
"author": "Siddharth Mehra",
"author_id": 16985146,
"author_profile": "https://Stackoverflow.com/users/16985146",
"pm_score": 2,
"selected": false,
"text": "String string = \"01:10:00\"; //string in duration format\nint hour = int.parse(string.split(\":\")[0]); //extracting hours from string\nint minute = int.parse(string.split(\":\")[1]); //extracting minutes\nint second = int.parse(string.split(\":\")[2]); //extracting seconds\nDuration duration = Duration(hours: hour, minutes: minute, seconds: second); //creating duration out of hour, min & seconds\nprint(\"Minutes is: ${duration.inMinutes}\"); //finally printing the minutes\n"
},
{
"answer_id": 74545719,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 1,
"selected": false,
"text": ": int final match = RegExp(r'(\\d+):(\\d+):(\\d+)').firstMatch(\"01:10:00\");\n final minutes = match == null\n ? 0\n : 60 * int.parse(match.group(1)!) +\n int.parse(match.group(2)!) + \n int.parse(match.group(3)!) ~/ 60;\n final match = RegExp(r'(\\d+):(\\d+):(\\d+)').firstMatch(\"01:10:00\");\n final minutes = match == null\n ? 0\n : Duration(\n hours: int.parse(match.group(1)!),\n minutes: int.parse(match.group(2)!),\n seconds: int.parse(match.group(3)!),\n ).inMinutes;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17441006/"
] |
74,545,537
|
<p>I have a dataset like that:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Sex</th>
<th>q1</th>
<th>q...</th>
<th>q10</th>
</tr>
</thead>
<tbody>
<tr>
<td>Male</td>
<td>Agree</td>
<td>Strongly agree</td>
<td>Strongly disagree</td>
</tr>
<tr>
<td>Female</td>
<td>Desagree</td>
<td>Agree</td>
<td>Disagree</td>
</tr>
<tr>
<td>Male</td>
<td>Agree</td>
<td>Strongly agree</td>
<td>Disagree</td>
</tr>
<tr>
<td>Female</td>
<td>Desagree</td>
<td>Agree</td>
<td>Strongly disagree</td>
</tr>
</tbody>
</table>
</div>
<p>I've been doing this:</p>
<pre><code>df$q1 <- factor(df$q1, levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree"))
df$q2 <- factor(df$q2, levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree"))
df$qn <- factor(df$qn, levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree"))
</code></pre>
<p>So I'm seeking for a smart way to order these levels to all the q1:qn subset of my dataset.</p>
|
[
{
"answer_id": 74545578,
"author": "OMi Shah",
"author_id": 5882307,
"author_profile": "https://Stackoverflow.com/users/5882307",
"pm_score": 1,
"selected": false,
"text": "final String time = '01:10:00'; // your time string\n\nfinal parts = time.split(':').map((e) => int.parse(e)).toList(); // split the time string by colon as separator and then parse each splitted string to int using the map method.\n\nfinal minutes = Duration(hours: parts[0], minutes: parts[1], seconds: parts[2])\n .inMinutes; // create a duration instance from the splitted time (hours, minutes and seconds) and then use .inMinutes to get the duration in minutes\n\nlog(minutes.toString()); // 70\n"
},
{
"answer_id": 74545655,
"author": "Siddharth Mehra",
"author_id": 16985146,
"author_profile": "https://Stackoverflow.com/users/16985146",
"pm_score": 2,
"selected": false,
"text": "String string = \"01:10:00\"; //string in duration format\nint hour = int.parse(string.split(\":\")[0]); //extracting hours from string\nint minute = int.parse(string.split(\":\")[1]); //extracting minutes\nint second = int.parse(string.split(\":\")[2]); //extracting seconds\nDuration duration = Duration(hours: hour, minutes: minute, seconds: second); //creating duration out of hour, min & seconds\nprint(\"Minutes is: ${duration.inMinutes}\"); //finally printing the minutes\n"
},
{
"answer_id": 74545719,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 1,
"selected": false,
"text": ": int final match = RegExp(r'(\\d+):(\\d+):(\\d+)').firstMatch(\"01:10:00\");\n final minutes = match == null\n ? 0\n : 60 * int.parse(match.group(1)!) +\n int.parse(match.group(2)!) + \n int.parse(match.group(3)!) ~/ 60;\n final match = RegExp(r'(\\d+):(\\d+):(\\d+)').firstMatch(\"01:10:00\");\n final minutes = match == null\n ? 0\n : Duration(\n hours: int.parse(match.group(1)!),\n minutes: int.parse(match.group(2)!),\n seconds: int.parse(match.group(3)!),\n ).inMinutes;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3645120/"
] |
74,545,596
|
<p>I am working in Reactjs and using Nextjs,I am facing problem with "text box",whenever i use "value" in textbox then i cant type anything in "textbox" and if i use "defaultvalue" in "textbox" then i am getting validation message "Please enter your email"
How can i fix this ?
Here is my code</p>
<pre><code><input
type="text"
name="email"
id="email"
placeholder="Type your email here"
value={state.name}
onChange={handleChange2}
/>
</code></pre>
<p>And here if nextjs code</p>
<pre><code>const value = e.target.value;
setState({
...state,
[e.target.email]: value
});
};
const handleSubscribe = (e) => {
e.preventDefault();
//if (state.email == '') {
if (value.email == '') {
$("#error2").show("slow").delay(5000).fadeOut();
$("#msg2").hide();
} else {
$("#msg2").show("slow").delay(5000).fadeOut();
$("#error2").hide();
//alert(state.email);
const data = {
name: value.email
}; // making array and will pass to api as parameter
//input type text empty after click
setState({
...value.email,
name: ""
});
axios.post('https://diggdevelopment.com/blackstallion_new/api/testinfo/', data).then(function (response) {
console.log(response.data);
});
}
</code></pre>
<p>};</p>
|
[
{
"answer_id": 74545578,
"author": "OMi Shah",
"author_id": 5882307,
"author_profile": "https://Stackoverflow.com/users/5882307",
"pm_score": 1,
"selected": false,
"text": "final String time = '01:10:00'; // your time string\n\nfinal parts = time.split(':').map((e) => int.parse(e)).toList(); // split the time string by colon as separator and then parse each splitted string to int using the map method.\n\nfinal minutes = Duration(hours: parts[0], minutes: parts[1], seconds: parts[2])\n .inMinutes; // create a duration instance from the splitted time (hours, minutes and seconds) and then use .inMinutes to get the duration in minutes\n\nlog(minutes.toString()); // 70\n"
},
{
"answer_id": 74545655,
"author": "Siddharth Mehra",
"author_id": 16985146,
"author_profile": "https://Stackoverflow.com/users/16985146",
"pm_score": 2,
"selected": false,
"text": "String string = \"01:10:00\"; //string in duration format\nint hour = int.parse(string.split(\":\")[0]); //extracting hours from string\nint minute = int.parse(string.split(\":\")[1]); //extracting minutes\nint second = int.parse(string.split(\":\")[2]); //extracting seconds\nDuration duration = Duration(hours: hour, minutes: minute, seconds: second); //creating duration out of hour, min & seconds\nprint(\"Minutes is: ${duration.inMinutes}\"); //finally printing the minutes\n"
},
{
"answer_id": 74545719,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 1,
"selected": false,
"text": ": int final match = RegExp(r'(\\d+):(\\d+):(\\d+)').firstMatch(\"01:10:00\");\n final minutes = match == null\n ? 0\n : 60 * int.parse(match.group(1)!) +\n int.parse(match.group(2)!) + \n int.parse(match.group(3)!) ~/ 60;\n final match = RegExp(r'(\\d+):(\\d+):(\\d+)').firstMatch(\"01:10:00\");\n final minutes = match == null\n ? 0\n : Duration(\n hours: int.parse(match.group(1)!),\n minutes: int.parse(match.group(2)!),\n seconds: int.parse(match.group(3)!),\n ).inMinutes;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5308126/"
] |
74,545,604
|
<p>I am trying to make a function that receives a list/array and returns the index of the maximum
value in that sequence. The function should raise an exception if non-numerical values are
present in the list.</p>
<pre><code>def maxvalue(values):
"""
Function that receives a list/array and returns the index of the maximum
value in that sequence
"""
indices = []
max_value = max(values)
for i in range(len(values)):
if type(i) not in (float, int): # raise an exception if the value is not float or integer
raise TypeError("Only numberical values are allowed")
if values[i] == max_value:
indices.append(i)
return indices
maxvalue([1, 1, 1.5, "e", 235.8, 9, 220, 220])
</code></pre>
<p>The function works when it receives a list containing floats and integers and doesn't work if there is a string in it.</p>
<p>How do I get the function to produce "TypeError("Only numberical values are allowed")" error quote when there is a str present in the list?</p>
<p>Currently, it produces "TypeError: '>' not supported between instances of 'str' and 'float'"</p>
|
[
{
"answer_id": 74545711,
"author": "Piotr Sawicki",
"author_id": 8254496,
"author_profile": "https://Stackoverflow.com/users/8254496",
"pm_score": 2,
"selected": true,
"text": "def maxvalue(values):\n \"\"\"\n Function that receives a list/array and returns the index of the maximum\n value in that sequence\n\n \"\"\"\n\n try:\n max_value = max(values)\n except TypeError:\n raise TypeError(\"Only numberical values are allowed\")\n\n indices = []\n for idx, val in enumerate(values):\n if val == max_value:\n indices.append(idx)\n\n return indices\n"
},
{
"answer_id": 74546132,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "def maxvalue(values):\n indices = []\n print(values)\n int_values = []\n \"\"\"the max function cannot fetch a max value with a string as part of the list so you can filter the list to get only integer values before you get max value\"\"\"\n for x in values: \n if type(x)==int:\n int_values.append(x)\n\n max_value = max(int_values)\n\n for i in range(len(int_values)):\n if int_values[i] == max_value:\n indices.append(i)\n return indices\n\nprint(maxvalue([1, 1, 1.5, \"e\", 235.8, 9, 220, 220]))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573938/"
] |
74,545,631
|
<p>Python. How can I convert list of lists to list of columns lists according to number of indexes in lists. But every time I can have different matrix(dimension), different number of row/list and different number of numbers in list</p>
<p>For example from this list of lists:</p>
<pre><code> x = [
[1, 0, 0, 0, 1, 0, 0],
[0, 0, 2, 2, 0, 0, 0],
[0, 1, 0, 0, 0, 2, 2]
]
</code></pre>
<p>To this list of column lists:</p>
<pre><code>y = [[1,0,0],[0,0,1],[0,2,0],[0,2,0],[1,0,0],[0,0,2],[0,0,2]]
</code></pre>
|
[
{
"answer_id": 74545711,
"author": "Piotr Sawicki",
"author_id": 8254496,
"author_profile": "https://Stackoverflow.com/users/8254496",
"pm_score": 2,
"selected": true,
"text": "def maxvalue(values):\n \"\"\"\n Function that receives a list/array and returns the index of the maximum\n value in that sequence\n\n \"\"\"\n\n try:\n max_value = max(values)\n except TypeError:\n raise TypeError(\"Only numberical values are allowed\")\n\n indices = []\n for idx, val in enumerate(values):\n if val == max_value:\n indices.append(idx)\n\n return indices\n"
},
{
"answer_id": 74546132,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "def maxvalue(values):\n indices = []\n print(values)\n int_values = []\n \"\"\"the max function cannot fetch a max value with a string as part of the list so you can filter the list to get only integer values before you get max value\"\"\"\n for x in values: \n if type(x)==int:\n int_values.append(x)\n\n max_value = max(int_values)\n\n for i in range(len(int_values)):\n if int_values[i] == max_value:\n indices.append(i)\n return indices\n\nprint(maxvalue([1, 1, 1.5, \"e\", 235.8, 9, 220, 220]))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20556266/"
] |
74,545,632
|
<p>This is what they want us exactly to do :</p>
<p>Create a page (+ JavaScript) where it will implement a simple adder, i.e. you will type numbers in a Text Box and with the click of a button they will be added to the total that will be displayed in a second Text Box.</p>
<p>In case the total sum exceeds 1000 a message is displayed.</p>
<p>I ve already tried this but no matter what i try to do it doesnt seem to work. I would appriciate some help</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="txt1" value="0"/>
<button onclick="AddNumbers()">Add</button>
<input type="text" id="txt2" value="0"/>
<script>
function AddNumbers() {
var t1 = document.getElementById("txt1").value;
var t2 = document.getElementById("txt2").value;
var sum = parseFloat("t1").value + parseFloat("t2").value ;
if (sum > 1000){
window.alert("Over 1000");
} else {
t2=sum;
document.getElementById("txt2").innerHTML=t2;
}
}
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74545711,
"author": "Piotr Sawicki",
"author_id": 8254496,
"author_profile": "https://Stackoverflow.com/users/8254496",
"pm_score": 2,
"selected": true,
"text": "def maxvalue(values):\n \"\"\"\n Function that receives a list/array and returns the index of the maximum\n value in that sequence\n\n \"\"\"\n\n try:\n max_value = max(values)\n except TypeError:\n raise TypeError(\"Only numberical values are allowed\")\n\n indices = []\n for idx, val in enumerate(values):\n if val == max_value:\n indices.append(idx)\n\n return indices\n"
},
{
"answer_id": 74546132,
"author": "Tat",
"author_id": 19269506,
"author_profile": "https://Stackoverflow.com/users/19269506",
"pm_score": 0,
"selected": false,
"text": "def maxvalue(values):\n indices = []\n print(values)\n int_values = []\n \"\"\"the max function cannot fetch a max value with a string as part of the list so you can filter the list to get only integer values before you get max value\"\"\"\n for x in values: \n if type(x)==int:\n int_values.append(x)\n\n max_value = max(int_values)\n\n for i in range(len(int_values)):\n if int_values[i] == max_value:\n indices.append(i)\n return indices\n\nprint(maxvalue([1, 1, 1.5, \"e\", 235.8, 9, 220, 220]))\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581075/"
] |
74,545,639
|
<p>I would really appreciate some assistance...</p>
<p>I'm trying to retrieve an ISBN number (13 digits) from pages, but the number set in so many different formats and that's why I can't retrieve all the different instances:</p>
<pre><code>ISBN-13: 978 1 4310 0862 9
ISBN: 9781431008629
ISBN9781431008629
ISBN 9-78-1431-008-629
ISBN: 9781431008629 more text of the number
isbn : 9781431008629
</code></pre>
<p>My output should be: <code>ISBN: 9781431008629</code></p>
<pre class="lang-py prettyprint-override"><code>myISBN = re.findall("ISBN" + r'[\w\W]{1,17}',text)
myISBN = myISBN[0]
print (myISBN)
</code></pre>
<p>I appreciate your time</p>
|
[
{
"answer_id": 74545793,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "(?i)ISBN(?:-13)?\\D*(\\d(?:\\W*\\d){12})\n (?i) re.I ISBN ISBN (?:-13)? -13 \\D* (\\d(?:\\W*\\d){12}) import re\ntexts = ['ISBN-13: 978 1 4310 0862 9',\n 'ISBN: 9781431008629',\n 'ISBN9781431008629',\n 'ISBN 9-78-1431-008-629',\n 'ISBN: 9781431008629 more text of the number',\n 'isbn : 9781431008629']\nrx = re.compile(r'ISBN(?:-13)?\\D*(\\d(?:\\W*\\d){12})', re.I)\nfor text in texts:\n m = rx.search(text)\n if m:\n print(text, '=> ISBN:', ''.join([d for d in m.group(1) if d.isdigit()]))\n ISBN-13: 978 1 4310 0862 9 => ISBN: 9781431008629\nISBN: 9781431008629 => ISBN: 9781431008629\nISBN9781431008629 => ISBN: 9781431008629\nISBN 9-78-1431-008-629 => ISBN: 9781431008629\nISBN: 9781431008629 more text of the number => ISBN: 9781431008629\nisbn : 9781431008629 => ISBN: 9781431008629\n"
},
{
"answer_id": 74545828,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "import re\n\ntext = \"\"\"\\\nISBN-13: 978 1 4310 0862 9\nISBN: 9781431008629\nISBN9781431008629\nISBN 9-78-1431-008-629\nISBN: 9781431008629 more text of the number\nisbn : 9781431008629\"\"\"\n\npat1 = re.compile(r\"(?i)ISBN(?:-13)?\\s*:?([ \\d-]+)\")\npat2 = re.compile(r\"\\d+\")\n\nfor m in pat1.findall(text):\n numbers = \"\".join(pat2.findall(m))\n if len(numbers) == 13:\n print(\"ISBN:\", numbers)\n ISBN: 9781431008629\nISBN: 9781431008629\nISBN: 9781431008629\nISBN: 9781431008629\nISBN: 9781431008629\nISBN: 9781431008629\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1835437/"
] |
74,545,649
|
<p>I have a dataframe with multiple levels of Multiindex. One of the levels is <code>latlon</code>, which is a string of the numbers with an <code>;</code> between them.
However, for further processing, it makes much more sense to have a <code>lat</code> level and a <code>lon</code> level. with floats for the numbers, instead of the combined string.</p>
<p>How do I best partition this level into two levels?</p>
<p>I have a solution, but it doesn't seem very <em>pythonic</em> and requires building a new dataframe, so I'm looking for a better way.</p>
<p><strong>MWE:</strong></p>
<p>Set up a simple test df:</p>
<pre><code>number = [1, 2, 3]
name = ['foo', 'bar', 'baz']
latlon = ['10.1;50.1', '12.2;52.2', '13.3;53.3']
idx = pd.MultiIndex.from_arrays([number, name, latlon],
names=('number','name', 'latlon'))
data = np.random.rand(4,3)
df = pd.DataFrame(data=data, columns=idx)
</code></pre>
<p>(Original data has 10 levels in the Multiindex and is of size <code>25000, 750</code>)
As you can see, <code>latlon</code> is easily human-readble, but not particularly useful. I want a <code>lat</code> and <code>lon</code> level, with floats.</p>
<p>What I've come up with:</p>
<pre><code># get a list of them, to iterate through
latlons = df.columns.get_level_values('latlon').to_list()
# set up emptly lists and start iterating
lats = []
lons = []
for i in latlons:
# do some string searches and split by positions
start_str = i.find(';')+1
end_str = i.find('\n')
lon_str = i[0:start_str-1]
lon = float(lon_str)
lons.append(lon)
lat_str = i[start_str:end_str]
lat = float(lat_str)
lats.append(lat)
</code></pre>
<p>Now there's two lists, one with lats and one with lons, which can be used to build a new index and thus a new df:</p>
<pre><code>number = df.columns.get_level_values('number').to_list()
# I can't reuse 'number' from the initial setup, since the original
# comes from an excel import, so I must extract it here.
name = df.columns.get_level_values('name').to_list()
idx = pd.MultiIndex.from_arrays([number, name, lats, lons],
names=('number','name', 'lat', 'lon'))
data = df.values
df2 = pd.DataFrame(data=data, columns=idx)
</code></pre>
<p>This works and is very easy to understand, but it all feels very hacky and one hickup away from mixing up data.</p>
<p>Is there a simpler/better way?</p>
|
[
{
"answer_id": 74545914,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "DataFrame new_idx = pd.MultiIndex.from_frame(\n df.columns.to_frame()\n .pipe(lambda d: d.join(d.pop('latlon')\n .str.split(';', expand=True)\n .set_axis(['lat', 'lon'], axis=1)\n ))\n .astype({'lat': float, 'lon': float})\n)\n\ndf.columns = new_idx\n number 1 2 3\nname foo bar baz\nlat 10.1 12.2 13.3\nlon 50.1 52.2 53.3\n0 0.796467 0.769194 0.733470\n1 0.272247 0.558985 0.345007\n2 0.209480 0.669443 0.648002\n3 0.466146 0.262006 0.236987\n"
},
{
"answer_id": 74546066,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "arr = df.columns\narrays = [arr.get_level_values(num) for num in range(arr.nlevels)]\n*arrays, latlon = arrays\nlatlon = latlon.str.split(';')\nlon = latlon.str[-1].astype(float).rename('lon')\nlat = latlon.str[0].astype(float).rename('lat')\narrays.extend([lat,lon])\ndf.columns = pd.MultiIndex.from_arrays(arrays)\ndf\nnumber 1 2 3\nname foo bar baz\nlat 10.1 12.2 13.3\nlon 50.1 52.2 53.3\n0 0.469529 0.356716 0.287799\n1 0.786352 0.557752 0.318536\n2 0.877670 0.503199 0.225858\n3 0.324959 0.253091 0.967328\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4340985/"
] |
74,545,685
|
<p>As we know, I can use several gems to implement OTP but I'm fresher so I want to know, what is the procedure to set an otp for different kind of reason.</p>
|
[
{
"answer_id": 74545914,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "DataFrame new_idx = pd.MultiIndex.from_frame(\n df.columns.to_frame()\n .pipe(lambda d: d.join(d.pop('latlon')\n .str.split(';', expand=True)\n .set_axis(['lat', 'lon'], axis=1)\n ))\n .astype({'lat': float, 'lon': float})\n)\n\ndf.columns = new_idx\n number 1 2 3\nname foo bar baz\nlat 10.1 12.2 13.3\nlon 50.1 52.2 53.3\n0 0.796467 0.769194 0.733470\n1 0.272247 0.558985 0.345007\n2 0.209480 0.669443 0.648002\n3 0.466146 0.262006 0.236987\n"
},
{
"answer_id": 74546066,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "arr = df.columns\narrays = [arr.get_level_values(num) for num in range(arr.nlevels)]\n*arrays, latlon = arrays\nlatlon = latlon.str.split(';')\nlon = latlon.str[-1].astype(float).rename('lon')\nlat = latlon.str[0].astype(float).rename('lat')\narrays.extend([lat,lon])\ndf.columns = pd.MultiIndex.from_arrays(arrays)\ndf\nnumber 1 2 3\nname foo bar baz\nlat 10.1 12.2 13.3\nlon 50.1 52.2 53.3\n0 0.469529 0.356716 0.287799\n1 0.786352 0.557752 0.318536\n2 0.877670 0.503199 0.225858\n3 0.324959 0.253091 0.967328\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20390732/"
] |
74,545,703
|
<p>How can I get video duration without</p>
<pre><code>https://pub.dev/packages/video_player
</code></pre>
<p>package or base this player. Is there any other way?</p>
<p>video player duration</p>
|
[
{
"answer_id": 74545855,
"author": "Risheek Mittal",
"author_id": 16973338,
"author_profile": "https://Stackoverflow.com/users/16973338",
"pm_score": 0,
"selected": false,
"text": " class ClassName {\n final FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();\n ...\n void someFunction() {\n _flutterFFmpeg\n .getMediaInformation(\"<file path or uri>\")\n .then((info) => print(info));\n }\n }\n"
},
{
"answer_id": 74545921,
"author": "Moïse Rajesearison",
"author_id": 20517248,
"author_profile": "https://Stackoverflow.com/users/20517248",
"pm_score": -1,
"selected": false,
"text": "VideoPlayerController _controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')\n ..initialize().then((_) {\n // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.\n });\n\n Duration durationOfVideo = _controller.value.duration;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20147144/"
] |
74,545,761
|
<p>I have created a dataframe</p>
<pre><code>df=pd.DataFrame({'Weather':[32,45,12,18,19,27,39,11,22,42],
'Id':[1,2,3,4,5,1,6,7,8,2]})
df.head()
</code></pre>
<p>You can see Id on index 5th and 9th are duplicated. So, I want to append string --duplicated with Id on 5th and 9th index.</p>
<pre><code>df.loc[df['Id'].duplicated()]
</code></pre>
<p><strong>Output</strong></p>
<pre><code> Weather Id
5 27 1
9 42 2
</code></pre>
<p><strong>Expected output</strong></p>
<pre><code> Weather Id
5 27 1--duplicated
9 42 2--duplicated
</code></pre>
|
[
{
"answer_id": 74545855,
"author": "Risheek Mittal",
"author_id": 16973338,
"author_profile": "https://Stackoverflow.com/users/16973338",
"pm_score": 0,
"selected": false,
"text": " class ClassName {\n final FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();\n ...\n void someFunction() {\n _flutterFFmpeg\n .getMediaInformation(\"<file path or uri>\")\n .then((info) => print(info));\n }\n }\n"
},
{
"answer_id": 74545921,
"author": "Moïse Rajesearison",
"author_id": 20517248,
"author_profile": "https://Stackoverflow.com/users/20517248",
"pm_score": -1,
"selected": false,
"text": "VideoPlayerController _controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')\n ..initialize().then((_) {\n // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.\n });\n\n Duration durationOfVideo = _controller.value.duration;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18455931/"
] |
74,545,815
|
<p>I want to align my contact elements as in the picture but I don't want to use padding and spacer, because it will look different on different devices(mb Im wrong). So how can I get such an output of elements?</p>
<p>[This is what I want it to look like] (<a href="https://i.stack.imgur.com/L8GLZ.png" rel="nofollow noreferrer">https://i.stack.imgur.com/L8GLZ.png</a>)</p>
<p>Tryed using horizontalAlignment = Alignment.CenterHorizontall on the columb block and different horizontalAlignments on the rows but couldn't manage to get what I wanted(</p>
<pre><code>@Composable
fun Greeting() {
loadLogo()
loadContactInfo()
}
@Composable
fun loadLogo(
fio: String = stringResource(R.string.FIO),
logo: Int = R.drawable.android_logo,
title: String = stringResource(R.string.title)
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(bottom = 100.dp)
) {
Image(
painter = painterResource(id = logo),
contentDescription = stringResource(R.string.logo_desc),
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
.height(150.dp)
.width(150.dp)
)
Text(text = fio, fontSize = 32.sp, modifier = Modifier.padding(bottom = 4.dp))
Text(text = title, fontSize = 16.sp, color = Color.Green)
}
}
@Composable
fun loadContactInfo(
phoneNum: String = stringResource(R.string.my_phone_num),
TGLink: String = stringResource(R.string.telegram_link),
emailAddress: String = stringResource(R.string.email_adress)
) {
Column(
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Row() {
Icon(
imageVector = Icons.Default.Phone,
contentDescription = "Phone icon",
)
Text(text = phoneNum)
}
Spacer(modifier = Modifier.height(35.dp))
Row() {
Icon(
imageVector = Icons.Default.Share,
contentDescription = "Phone icon",
)
Text(text = TGLink)
}
Spacer(modifier = Modifier.height(35.dp))
Row(
modifier = Modifier
.padding(bottom = 45.dp)
) {
Icon(
imageVector = Icons.Default.Email,
contentDescription = "Phone icon",
)
Text(text = emailAddress)
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/WJKEe.png" rel="nofollow noreferrer">Looks like this</a></p>
|
[
{
"answer_id": 74546225,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 1,
"selected": false,
"text": "Column weight(1f) Column(Modifier.fillMaxSize()){\n loadLogo(modifier = Modifier.fillMaxWidth().weight(1f))\n loadContactInfo()\n}\n\n@Composable\nfun loadLogo(\n modifier : Modifier = Modifier,\n fio: String = \"Fio\",\n logo: Int = R.drawable.ic_launcher_foreground,\n title: String = \"Title\"\n) {\n Column(\n modifier = modifier,\n verticalArrangement = Arrangement.Center,\n horizontalAlignment = Alignment.CenterHorizontally,\n ) {\n //\n }\n}\n\n@Composable\nfun loadContactInfo(\n modifier : Modifier = Modifier,\n phoneNum: String = \"+XX YYYY.YYYY.YYYY\",\n TGLink: String = \"Android Dev\",\n emailAddress: String = \"@androidDev\"\n) {\n Column(\n modifier = modifier,\n ) {\n //...\n }\n}\n"
},
{
"answer_id": 74546248,
"author": "Hamed",
"author_id": 8357673,
"author_profile": "https://Stackoverflow.com/users/8357673",
"pm_score": 0,
"selected": false,
"text": "Modifier.fillMaxWidth() Modifier.fillMaxHeight() Modifier.fillMaxSize() TextWithIcon @Composable\nfun TextWithIcon(\n modifier: Modifier = Modifier,\n title: String,\n icon: ImageVector\n) {\n Row(\n modifier = modifier.padding(vertical = 16.dp, horizontal = 8.dp),\n verticalAlignment = Alignment.CenterVertically\n ) {\n Icon(imageVector = icon, contentDescription = null)\n Spacer(modifier = Modifier.width(8.dp))\n Text(text = title)\n }\n} \n @Composable\nfun loadContactInfo(\n phoneNum: String = stringResource(R.string.my_phone_num),\n TGLink: String = stringResource(R.string.telegram_link),\n emailAddress: String = stringResource(R.string.email_adress)\n) {\n Column(\n verticalArrangement = Arrangement.Bottom,\n horizontalAlignment = Alignment.CenterHorizontally,\n modifier = Modifier.fillMaxWidth()\n ) {\n TextWithIcon(\n modifier = Modifier.fillMaxWidth(),\n title = phoneNum,\n icon = Icons.Default.Phone\n )\n TextWithIcon(\n modifier = Modifier.fillMaxWidth(),\n title = TGLink,\n icon = Icons.Default.Share\n )\n TextWithIcon(\n modifier = Modifier.fillMaxWidth(),\n title = emailAddress,\n icon = Icons.Default.Email\n )\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581138/"
] |
74,545,816
|
<p>so here's my problem:</p>
<p>I have two CSV files with each files having around 500 000 lines.</p>
<p>File 1 looks like this:</p>
<pre><code>ID|NAME|OTHER INFO
353253453|LAURENT|STUFF 1
563636345|MARK|OTHERS
786970908|GEORGES|THINGS
</code></pre>
<p>File 2 looks like this:</p>
<pre><code>LOCATION;ID_PERSON;PHONE
CA;786970908;555555
NY;353253453;555666
</code></pre>
<p>So what I have to do is look look for the lines where there are the same IDs, and add the line from file 2 to the end of corresponding line from file 1 in a new file, and if there's no corresponding IDs, add empty columns, like this:</p>
<pre><code>ID;NAME;OTHER INFO;LOCATION;ID_PERSON;PHONE
353253453;LAURENT;STUFF 1;NY;353253453;555666
563636345;MARK;OTHERS;;;
786970908;GEORGES;THINGS;CA;786970908;555555
</code></pre>
<p>File 1 is the primary one if that makes sense.</p>
<p>The thing is I have found a solution but it takes way too long since for each lines of file 1 I loop through file 2.</p>
<p>Here's my code:</p>
<pre><code>input1 = open(filename1, 'r', errors='ignore')
input2 = open(filename2, 'r', errors='ignore')
output = open('result.csv', 'w', newline='')
for line1 in input1:
line_splitted = line1.split("|")
id_1 = line_splitted[0]
index = 0
find = False
for line2 in file2:
file2_splitted = line2.split(";")
if id_1 in file2_splitted[1]:
output.write((";").join(line1.split("|"))+line2)
find = True
file2.remove(line2)
break
index+=1
if index == len(file2) and find == True:
output.write((";").join(line1.split("|")))
for j in range(nbr_col_2):
output.write(";")
output.write("\n")
</code></pre>
<p>So I was wondering if there is a faster way to do that, or if I just have to be patient, because right now after 20 minutes, only 20000 lines have been written...</p>
|
[
{
"answer_id": 74546225,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 1,
"selected": false,
"text": "Column weight(1f) Column(Modifier.fillMaxSize()){\n loadLogo(modifier = Modifier.fillMaxWidth().weight(1f))\n loadContactInfo()\n}\n\n@Composable\nfun loadLogo(\n modifier : Modifier = Modifier,\n fio: String = \"Fio\",\n logo: Int = R.drawable.ic_launcher_foreground,\n title: String = \"Title\"\n) {\n Column(\n modifier = modifier,\n verticalArrangement = Arrangement.Center,\n horizontalAlignment = Alignment.CenterHorizontally,\n ) {\n //\n }\n}\n\n@Composable\nfun loadContactInfo(\n modifier : Modifier = Modifier,\n phoneNum: String = \"+XX YYYY.YYYY.YYYY\",\n TGLink: String = \"Android Dev\",\n emailAddress: String = \"@androidDev\"\n) {\n Column(\n modifier = modifier,\n ) {\n //...\n }\n}\n"
},
{
"answer_id": 74546248,
"author": "Hamed",
"author_id": 8357673,
"author_profile": "https://Stackoverflow.com/users/8357673",
"pm_score": 0,
"selected": false,
"text": "Modifier.fillMaxWidth() Modifier.fillMaxHeight() Modifier.fillMaxSize() TextWithIcon @Composable\nfun TextWithIcon(\n modifier: Modifier = Modifier,\n title: String,\n icon: ImageVector\n) {\n Row(\n modifier = modifier.padding(vertical = 16.dp, horizontal = 8.dp),\n verticalAlignment = Alignment.CenterVertically\n ) {\n Icon(imageVector = icon, contentDescription = null)\n Spacer(modifier = Modifier.width(8.dp))\n Text(text = title)\n }\n} \n @Composable\nfun loadContactInfo(\n phoneNum: String = stringResource(R.string.my_phone_num),\n TGLink: String = stringResource(R.string.telegram_link),\n emailAddress: String = stringResource(R.string.email_adress)\n) {\n Column(\n verticalArrangement = Arrangement.Bottom,\n horizontalAlignment = Alignment.CenterHorizontally,\n modifier = Modifier.fillMaxWidth()\n ) {\n TextWithIcon(\n modifier = Modifier.fillMaxWidth(),\n title = phoneNum,\n icon = Icons.Default.Phone\n )\n TextWithIcon(\n modifier = Modifier.fillMaxWidth(),\n title = TGLink,\n icon = Icons.Default.Share\n )\n TextWithIcon(\n modifier = Modifier.fillMaxWidth(),\n title = emailAddress,\n icon = Icons.Default.Email\n )\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580916/"
] |
74,545,823
|
<p>My list can not have an option value like</p>
<pre><code><option value="some_value"> Some text</option>
</code></pre>
<p>My current code is</p>
<pre><code><select id="select1">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
$("option[value='Three']").remove()
</script>
</code></pre>
<p>I can not find a way to remove an option from a list if the option does not have a value.</p>
<p>I tried removing it with JQuery but it didn't work well.</p>
<p>Thanks</p>
|
[
{
"answer_id": 74545913,
"author": "user3258996",
"author_id": 3258996,
"author_profile": "https://Stackoverflow.com/users/3258996",
"pm_score": 1,
"selected": false,
"text": ":contains() $(\"option:contains('Three')\").remove()\n"
},
{
"answer_id": 74545929,
"author": "Yosi Leibman",
"author_id": 9162901,
"author_profile": "https://Stackoverflow.com/users/9162901",
"pm_score": 0,
"selected": false,
"text": "opt-1, opt-2 ...."
},
{
"answer_id": 74545966,
"author": "jeremy-denis",
"author_id": 3054722,
"author_profile": "https://Stackoverflow.com/users/3054722",
"pm_score": 1,
"selected": false,
"text": "#select1 option $(\"#select1 option\").each((index, option) => {\n if({your condition}) {\n $(option).remove();\n }\n});\n $(\"#select1 option\").each((index, option) => {\n if($(option).text() === 'Three') {\n $(option).remove();\n }\n}); <select id=\"select1\">\n <option>One</option>\n <option>Two</option>\n <option>Three</option>\n</select>\n<script src=\"https://code.jquery.com/jquery-3.3.1.min.js\">\n</script>"
},
{
"answer_id": 74546041,
"author": "Coozywana",
"author_id": 18492554,
"author_profile": "https://Stackoverflow.com/users/18492554",
"pm_score": 1,
"selected": true,
"text": "<select id=\"select1\"> \n <option>One</option> \n <option>Two</option> \n <option>Three</option> \n</select>\n<script src= \n\"https://code.jquery.com/jquery-3.3.1.min.js\"> \n</script>\n<script>\n$(\"option:contains(Three)\").remove()\n</script>"
},
{
"answer_id": 74546106,
"author": "Pankaj",
"author_id": 7080671,
"author_profile": "https://Stackoverflow.com/users/7080671",
"pm_score": 0,
"selected": false,
"text": "remove() $(\"option:contains('Three')\").remove()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18492554/"
] |
74,545,928
|
<p>I have written some basic JS code in React Native to generate a random number then render the number. I would now like to add every generated number to a list.</p>
<p>Currently the generated random number can be added to a list, to do this I need to first generate the number (using</p>
<pre><code>onPress={getRandomInt}
</code></pre>
<p>) THEN to add to the list on a separate button:</p>
<pre><code>onPress={addNumber}
</code></pre>
<p>.</p>
<p>I've tried combining the functions and for the life of me can't get it to work. Any help would be much appreciated, thank you.</p>
<pre><code>import React, { useEffect, useState } from 'react';
import { View, Text, Button } from 'react-native';
import Calls from './Calls';
export default function NumberGen() {
const [number, setNumber] = React.useState();
const [names, setNames] = React.useState([]);
const getRandomInt = (min, max) => {
min = Math.ceil(1);
max = Math.floor(90);
const randomNumber = Math.floor(Math.random() * (max - min +1) + min);
setNumber(randomNumber)
}
const addNumber = () => {
getRandomInt
setNames(current => [...current, number]);
}
return (
<>
<View>
<Button
title='get random number'
onPress={getRandomInt}
/>
<Text>{number}</Text>
<Text>{Calls.call[number-1]}</Text>
</View>
<Button title='add to list' onPress={addNumber}/>
<View>
{names.map((element) => {
return(
<Text>{element}</Text>
)
})}
</View>
</>
);
};
</code></pre>
<p>I've tried:</p>
<ul>
<li>Adding a new array to state</li>
<li>Combining both functions</li>
<li>Using .then after the random number is generated but before it's set to state.</li>
</ul>
|
[
{
"answer_id": 74546044,
"author": "Yosi Leibman",
"author_id": 9162901,
"author_profile": "https://Stackoverflow.com/users/9162901",
"pm_score": 0,
"selected": false,
"text": " const addNumber = () => {\ngetRandomInt()\nsetNames(current => [...current, number]);\n"
},
{
"answer_id": 74546062,
"author": "Vin Xi",
"author_id": 19450576,
"author_profile": "https://Stackoverflow.com/users/19450576",
"pm_score": -1,
"selected": false,
"text": "const getRandomInt = (min, max) => {\n\n min = Math.ceil(1);\n max = Math.floor(90);\n\n const randomNumber = Math.floor(Math.random() * (max - min +1) + min);\n setNumber(randomNumber)\n }\n const addNumber = () => {\n getRandomInt()\n setNames(current => [...current, number]);\n }\n"
},
{
"answer_id": 74546219,
"author": "Hardik prajapati",
"author_id": 18241250,
"author_profile": "https://Stackoverflow.com/users/18241250",
"pm_score": -1,
"selected": false,
"text": "const getRandomInt = (min, max) => {\nmin = Math.ceil(1);\nmax = Math.floor(90);\nconst randomNumber = Math.floor(Math.random() * (max - min + 1) + min);\nsetNumber(randomNumber);\nreturn randomNumber;\n const addNumber = () => {\nif (names.length > 0) {\n const updateValue = getRandomInt();\n setNames(current => [...current, updateValue]);\n} else {\n setNames(current => [...current, number]);\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16600568/"
] |
74,545,930
|
<p>I have regular expression that search for rows containing 4 digit numbers, specific 19xx.
It gives too many matches so I am looking for a way to exclude the things I dont want.</p>
<p>This is my current regex:</p>
<pre><code>^\s*[^\/].*19\d{2}
</code></pre>
<p>Here are some example rows:</p>
<pre><code>short param1 = 1994;
short param2 = 1918;
// 1998-08-20
// 1998-08-20
//## begin protected section initialization list [51935568]
//## begin protected section initialization list [51935568]
</code></pre>
<p><em>(Row 2, 4 and 5 have spaces in the beginning.)</em></p>
<p>My regex manage to correctly:</p>
<ul>
<li>find row 1, 2</li>
<li>exclude row 3, 6</li>
</ul>
<p>But incorrectly also matches row 4 & 5.
I cant find a way to make te regex exlude these rows.</p>
|
[
{
"answer_id": 74546044,
"author": "Yosi Leibman",
"author_id": 9162901,
"author_profile": "https://Stackoverflow.com/users/9162901",
"pm_score": 0,
"selected": false,
"text": " const addNumber = () => {\ngetRandomInt()\nsetNames(current => [...current, number]);\n"
},
{
"answer_id": 74546062,
"author": "Vin Xi",
"author_id": 19450576,
"author_profile": "https://Stackoverflow.com/users/19450576",
"pm_score": -1,
"selected": false,
"text": "const getRandomInt = (min, max) => {\n\n min = Math.ceil(1);\n max = Math.floor(90);\n\n const randomNumber = Math.floor(Math.random() * (max - min +1) + min);\n setNumber(randomNumber)\n }\n const addNumber = () => {\n getRandomInt()\n setNames(current => [...current, number]);\n }\n"
},
{
"answer_id": 74546219,
"author": "Hardik prajapati",
"author_id": 18241250,
"author_profile": "https://Stackoverflow.com/users/18241250",
"pm_score": -1,
"selected": false,
"text": "const getRandomInt = (min, max) => {\nmin = Math.ceil(1);\nmax = Math.floor(90);\nconst randomNumber = Math.floor(Math.random() * (max - min + 1) + min);\nsetNumber(randomNumber);\nreturn randomNumber;\n const addNumber = () => {\nif (names.length > 0) {\n const updateValue = getRandomInt();\n setNames(current => [...current, updateValue]);\n} else {\n setNames(current => [...current, number]);\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18419195/"
] |
74,545,954
|
<p>how should the datetime comparison work if the datetimes are in diff timezones.</p>
<p>For example:</p>
<pre><code>WITH datetime("2022-11-01T08:00+01:00") AS d1, datetime("2022-11-01T07:00") AS d2
RETURN d1=d2
</code></pre>
<p>returns false!?</p>
<p>I am using 4.4.12 community edition under OSX.</p>
<p>Even more strange is the following:</p>
<pre><code>WITH datetime("2022-11-01T08:00:00+01:00") AS d1, datetime("2022-11-01T07:00") AS d2
RETURN duration.between(d1,d2)
</code></pre>
<p>Result: PT0S</p>
<pre><code>WITH datetime("2022-11-01T08:00:00+01:00") AS d1, datetime("2022-11-01T07:00") AS d2
RETURN d1.year, d2.year, d1.month, d2.month, d1.day, d2.day, d1.hour, d2.hour, d1.minute, d2.minute, d1.second, d2.second, d1.millisecond, d2.millisecond, d1.timeZone, d2.timeZone, d1.offset, d2.offset, d1.epochMillis, d2.epochMillis
</code></pre>
<p>The hours, offset and timezone is different for d1 and d2.</p>
|
[
{
"answer_id": 74546044,
"author": "Yosi Leibman",
"author_id": 9162901,
"author_profile": "https://Stackoverflow.com/users/9162901",
"pm_score": 0,
"selected": false,
"text": " const addNumber = () => {\ngetRandomInt()\nsetNames(current => [...current, number]);\n"
},
{
"answer_id": 74546062,
"author": "Vin Xi",
"author_id": 19450576,
"author_profile": "https://Stackoverflow.com/users/19450576",
"pm_score": -1,
"selected": false,
"text": "const getRandomInt = (min, max) => {\n\n min = Math.ceil(1);\n max = Math.floor(90);\n\n const randomNumber = Math.floor(Math.random() * (max - min +1) + min);\n setNumber(randomNumber)\n }\n const addNumber = () => {\n getRandomInt()\n setNames(current => [...current, number]);\n }\n"
},
{
"answer_id": 74546219,
"author": "Hardik prajapati",
"author_id": 18241250,
"author_profile": "https://Stackoverflow.com/users/18241250",
"pm_score": -1,
"selected": false,
"text": "const getRandomInt = (min, max) => {\nmin = Math.ceil(1);\nmax = Math.floor(90);\nconst randomNumber = Math.floor(Math.random() * (max - min + 1) + min);\nsetNumber(randomNumber);\nreturn randomNumber;\n const addNumber = () => {\nif (names.length > 0) {\n const updateValue = getRandomInt();\n setNames(current => [...current, updateValue]);\n} else {\n setNames(current => [...current, number]);\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3782499/"
] |
74,545,960
|
<p>Hello I am trying to drop rows that have in a specific column string that is not a year.
For example <a href="https://i.stack.imgur.com/SdQEQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SdQEQ.png" alt="here" /></a> I have the in last rows year formats that have decimal points or '-'.</p>
<p>I have tried to convert the year column into a string and then drop them using the code below but it only removes the row with 2011-21, the ones with decimal points stay.</p>
<pre><code>df.level_1=df.level_1.astype(str)
df.loc[
(~df.level_1.str.contains("."))
|~(df.level_1.str.contains("-")),
:]
</code></pre>
<p>is there a way to fix this issue ??</p>
|
[
{
"answer_id": 74546951,
"author": "Tranbi",
"author_id": 13525512,
"author_profile": "https://Stackoverflow.com/users/13525512",
"pm_score": 2,
"selected": true,
"text": "level_1 df[~df.level_1.str.contains('\\D')]\n"
},
{
"answer_id": 74547042,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "df['level_1']=df['level_1'].astype(str)\ndf = df[df['level_1'].str.contains('\\d\\d\\d\\d-\\d\\d',regex=True)]\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20521674/"
] |
74,545,964
|
<p>I'm trying to write some js that adds an extra class of .active to an already existing class called .option on click. As well as removing said .active class from anoy div with both classes .option.active.</p>
<p>This is what I have so far</p>
<pre><code>console.log(`It Works!`);
const option = document.querySelector(`.option:not(.active)`);
const activeOption = document.querySelector(`.option.active`);
function handleClickAdd() {
console.log(`IT GOT ADDED`);
option.classList.add('active');
}
function handleClickRemove() {
console.log(`IT GOT REMOVED`);
activeOption.classList.remove(`active`);
}
option.addEventListener(`click`, handleClickAdd);
activeOption.addEventListener(`click`, handleClickRemove);
</code></pre>
<p>the console is returning the logs, but both the add and remove functions are only seeming to work once. Is there a way i can make it continue so that you can toggle about the options?</p>
<p>Please bear in mind I am very new to Javascript and only halfway through a beginners course!</p>
<p>many thanks in advance</p>
<p>Ive added console logs to the functions to see that they are definietly running</p>
|
[
{
"answer_id": 74545997,
"author": "Yosi Leibman",
"author_id": 9162901,
"author_profile": "https://Stackoverflow.com/users/9162901",
"pm_score": 1,
"selected": false,
"text": "activeOption.classList.toggle(\"active\");\n"
},
{
"answer_id": 74546700,
"author": "Nishant",
"author_id": 4632239,
"author_profile": "https://Stackoverflow.com/users/4632239",
"pm_score": 0,
"selected": false,
"text": "console.log(`It Works!`);\n\nconst option = document.getElementsByTagName(`ul`)[0];\n\nfunction handleClickAddRemove(e) {\n console.log(`IT GOT ADDED OR REMOVED`, e.target.classList.value);\n e.target.classList.toggle('active');\n}\n\noption.addEventListener(`click`, handleClickAddRemove); <ul>\n <li class=\"option active\">1</li>\n <li class=\"option\">2</li>\n <li class=\"option\">3</li>\n <li class=\"option\">4</li>\n <li class=\"option\">5</li>\n</ul>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16845914/"
] |
74,545,972
|
<p>I am fairly new to Python, so excuse me if this question has been answered before or can be easily solved.
I have a long data frame with numerical variables and categorical variables. It looks something like this:</p>
<pre><code> Category Detail Gender Weight
Food Apple Female 30
Food Apple Male 40
Beverage Milk Female 10
Beverage Milk Male 5
Beverage Milk Male 20
Food Banana Female 50
</code></pre>
<p>What I want to do is this: Group by Category and Detail and then count all instances of 'Female' and 'Male'. I then want to weight these instances (see column 'Weight'). This should be done by taking the value from column 'Weight' and then deviding that by the summed weight. (so here for the group: Beverage, Milk, Male, it would be 25 devided by 35). It also would be nice to have the share of the gender.
At the end of the day I want my data frame to look something like this:</p>
<pre><code>Category Detail Female Male
Beverage Milk 29% 71%
Food Apple 43% 57%
Food Banana 100% 0%
</code></pre>
<p>So in addition to the grouping, I want to kind of 'unmelt' the data frame by taking Female and Male an adding them as new columns.</p>
<p>I could just sum the weights with groupby on different levels, but how can I reshape the data frame in that way of adding these new columns?</p>
<p>Is there any way to do that? Thanks for any help in advance!</p>
|
[
{
"answer_id": 74545997,
"author": "Yosi Leibman",
"author_id": 9162901,
"author_profile": "https://Stackoverflow.com/users/9162901",
"pm_score": 1,
"selected": false,
"text": "activeOption.classList.toggle(\"active\");\n"
},
{
"answer_id": 74546700,
"author": "Nishant",
"author_id": 4632239,
"author_profile": "https://Stackoverflow.com/users/4632239",
"pm_score": 0,
"selected": false,
"text": "console.log(`It Works!`);\n\nconst option = document.getElementsByTagName(`ul`)[0];\n\nfunction handleClickAddRemove(e) {\n console.log(`IT GOT ADDED OR REMOVED`, e.target.classList.value);\n e.target.classList.toggle('active');\n}\n\noption.addEventListener(`click`, handleClickAddRemove); <ul>\n <li class=\"option active\">1</li>\n <li class=\"option\">2</li>\n <li class=\"option\">3</li>\n <li class=\"option\">4</li>\n <li class=\"option\">5</li>\n</ul>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16864161/"
] |
74,545,999
|
<p>Here</p>
<blockquote>
<p>1] I am trying to use custom color scheme instead of default theme
provided by highcharts. But It is not working as expected. I have
implemented colors array and it should serially apply the colors, but
it is randomizing the color sequence and sometimes even repeating the
colors.</p>
<p>2] And also trying to implement custom tool-tip but the code is giving
an error.</p>
</blockquote>
<p>I have created a stackblitz as below:</p>
<p><a href="https://stackblitz.com/edit/angular-ivy-mz3dhi?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.module.ts,package.json" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-mz3dhi?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.module.ts,package.json</a></p>
<p>Any help would be appreciated!</p>
|
[
{
"answer_id": 74555449,
"author": "Duniyadnd",
"author_id": 293291,
"author_profile": "https://Stackoverflow.com/users/293291",
"pm_score": 2,
"selected": true,
"text": "data: [\n {\n id: '0.0',\n parent: ' ',\n name: 'Parent',\n },\n {\n id: '1.3',\n parent: '0.0',\n name: 'Steve',\n },\n {\n id: '1.2',\n parent: '0.0',\n name: 'Sam',\n },\n {\n id: '1.1',\n parent: '0.0',\n name: 'Stefy',\n },\n {\n id: '2.1',\n parent: '1.1',\n name: 'Section1',\n },\n ...\n ...\n ...\n ]\n"
},
{
"answer_id": 74558718,
"author": "Sebastian Hajdus",
"author_id": 12171673,
"author_profile": "https://Stackoverflow.com/users/12171673",
"pm_score": 0,
"selected": false,
"text": "interface extendPointLabelObject extends Highcharts.PointLabelObject {\n}\n\n\ntooltip: {\n formatter: function( this: extendPointLabelObject) {\n return 'custom tooltip'\n }\n},\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74545999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16507742/"
] |
74,546,006
|
<p>I have problems with merging two unconnected git branches. The situation is the following: originally the was a svn repository, at one point a new git repository with the code from svn as an initial commit - without any history was created. And some changes already made etc.</p>
<p>Now i imported the old svn history to this existing repository on a new branch, <code>from-svn</code>. Now the repository contains one branch, <code>master</code>, where all the work since switching to the git repository is stored, and one <code>from-svn</code> where the old commits leading up to the initial commit in the <code>master</code> are stored. However for git they seem to be unrelated (understandably and of course probably).</p>
<p>Now i want to connect it somehow, to have the complete history on one branch. Is this possible? I tried merging, but i cant. <code>git merge master</code> (also the other way around) tells me everything is up-to-date (also tried <code>--allow-unrelated-histories</code>). If specify the most recent commit-id it tells me it is <code>not something we can merge</code>, even with <code>--allow-unrelated-histories</code>.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 74555449,
"author": "Duniyadnd",
"author_id": 293291,
"author_profile": "https://Stackoverflow.com/users/293291",
"pm_score": 2,
"selected": true,
"text": "data: [\n {\n id: '0.0',\n parent: ' ',\n name: 'Parent',\n },\n {\n id: '1.3',\n parent: '0.0',\n name: 'Steve',\n },\n {\n id: '1.2',\n parent: '0.0',\n name: 'Sam',\n },\n {\n id: '1.1',\n parent: '0.0',\n name: 'Stefy',\n },\n {\n id: '2.1',\n parent: '1.1',\n name: 'Section1',\n },\n ...\n ...\n ...\n ]\n"
},
{
"answer_id": 74558718,
"author": "Sebastian Hajdus",
"author_id": 12171673,
"author_profile": "https://Stackoverflow.com/users/12171673",
"pm_score": 0,
"selected": false,
"text": "interface extendPointLabelObject extends Highcharts.PointLabelObject {\n}\n\n\ntooltip: {\n formatter: function( this: extendPointLabelObject) {\n return 'custom tooltip'\n }\n},\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171541/"
] |
74,546,008
|
<p>I am making an app with <strong>flutter</strong>. I want to store data after 24 hours and update UI in app.
I try with <strong>Timer.periodic()</strong> but it does not count the time when app is close. It only works when the application is open.</p>
<p>Is it possible to execute a function after a specific time even if the app is closed?</p>
<p>Here is my current code:</p>
<pre class="lang-dart prettyprint-override"><code>void callbackDispatcher() async{
Workmanager().executeTask((task, inputData) {
switch(sdDaily){
case 'StoreDataDaily':
storeData.storeDailyData();
break;
default:
}
return Future.value(true);
});
}
</code></pre>
<pre class="lang-dart prettyprint-override"><code>void main() async{
WidgetsFlutterBinding.ensureInitialized();
Directory directory = await path_provider.getApplicationDocumentsDirectory();
print(directory.path);
Hive.init(directory.path);
await Hive.initFlutter(directory.path);
Hive.registerAdapter(UserAdapter());
Hive.registerAdapter(WaterAdapter());
Hive.registerAdapter(WeekAdapter());
Get.put(UserController());
Get.put(WaterController());
await Hive.openBox<User>('data');
await Hive.openBox<Water>('water_data');
await Hive.openBox<Week>('week_data');
await notificationPlugin.showNotification();
await Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
var uniqueId = DateTime.now().second.toString();
var userBox = Hive.box<User>('data');
if(userBox.get(0)?.status == 1){
await Workmanager().registerOneOffTask(uniqueId, sdDaily,);
}
runApp(const MyApp());
}
</code></pre>
|
[
{
"answer_id": 74555449,
"author": "Duniyadnd",
"author_id": 293291,
"author_profile": "https://Stackoverflow.com/users/293291",
"pm_score": 2,
"selected": true,
"text": "data: [\n {\n id: '0.0',\n parent: ' ',\n name: 'Parent',\n },\n {\n id: '1.3',\n parent: '0.0',\n name: 'Steve',\n },\n {\n id: '1.2',\n parent: '0.0',\n name: 'Sam',\n },\n {\n id: '1.1',\n parent: '0.0',\n name: 'Stefy',\n },\n {\n id: '2.1',\n parent: '1.1',\n name: 'Section1',\n },\n ...\n ...\n ...\n ]\n"
},
{
"answer_id": 74558718,
"author": "Sebastian Hajdus",
"author_id": 12171673,
"author_profile": "https://Stackoverflow.com/users/12171673",
"pm_score": 0,
"selected": false,
"text": "interface extendPointLabelObject extends Highcharts.PointLabelObject {\n}\n\n\ntooltip: {\n formatter: function( this: extendPointLabelObject) {\n return 'custom tooltip'\n }\n},\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19368462/"
] |
74,546,032
|
<p>[<a href="https://i.stack.imgur.com/ZLdOJ.png" rel="nofollow noreferrer">enter image description here</a>](<a href="https://i.stack.imgur.com/jgD0e.png" rel="nofollow noreferrer">https://i.stack.imgur.com/jgD0e.png</a>)</p>
<p>Hi,
When I try to define the variable const items = [];
My localhost refuse to connect. I get ERR_CONNECTION_REFUSED. or (This site can't be reached).
When I comment out the the line where I've declared the variable, the site works.</p>
<p>Does anybody have an idea about why?</p>
<p>My firewall is off and I disabled all proxies. But nothing.</p>
|
[
{
"answer_id": 74546092,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 3,
"selected": true,
"text": "res.render(\"list\", { dayWeek: day, newListItem: items });\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581325/"
] |
74,546,078
|
<pre><code>describe('download',function()
{
it('fils',function()
{
cy.visit('url')
cy.get('.ds_class_data_sheet').click()
cy.wait(3000)
const numberoftest=68;
for (let i = 1; i <= numberoftest; i ++) {
cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i).then(function(e1)
{
const url=e1.prop('href')
cy.downloadFile(url,'cypress/downloads/Datasheet','file1.pdf')
}
)
}
}
)
})
</code></pre>
<p>I tried by writing the code like this. There happen the downloads but my question is how do I name the downloaded file using the loop.</p>
|
[
{
"answer_id": 74550254,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": -1,
"selected": false,
"text": "describe('download',() => {\n it('fils',() => { \n cy.visit('url')\n cy.get('.ds_class_data_sheet').click()\n cy.wait(3000)\n const numberoftest=68;\n Cypress._.times(numberoftest, (i) => {\n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink')\n .eq(i)\n .then(e1 => {\n const url=e1.prop('href')\n cy.downloadFile(url,'cypress/downloads/Datasheet','file1.pdf')\n })\n })\n})\n"
},
{
"answer_id": 74552093,
"author": "Alcock",
"author_id": 20580470,
"author_profile": "https://Stackoverflow.com/users/20580470",
"pm_score": 2,
"selected": true,
"text": "for (let i = 1; i <= numberoftest; i ++) { \n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i)\n .then(function(e1) {\n const url = e1.prop('href')\n\n // name whatever format desired, maybe last part of url\n const id = url.split('/')[3]\n const name = `file_${id}` \n\n cy.downloadFile(url,'cypress/downloads/Datasheet', name)\n })\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20516932/"
] |
74,546,107
|
<p>How can I force 'Read Only' in Power Query</p>
<ul>
<li>Or save the source file as 'Share Deny Write'?</li>
</ul>
<p>Every day my Excel report joins information from several different sources, and saves the results in separate xlsx files. These xlsx files (sheets) are then being used as source for other reports.</p>
<p>But the problem is if anyone opens one of these other reports where Power Query Connection has been used. It will also keeps the source file busy for me to update. (by overwrite with my SaveAs Macro below)<br />
The result is that none of the reports is up to date – as there is no easy way to set the Query or Connection to a Read Only on its source.</p>
<p>In earlier Excel versions users could select souse connection to Read Only like this :[Connecting to a workbook]<a href="https://i.stack.imgur.com/2L72p.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/2L72p.jpg</a></p>
<p>My code for save the Sheets goes like this:</p>
<pre><code>Sub Sap_Ordrer_SaveAs()
Dim wb As Workbook
Application.DisplayAlerts = False
' SaveAs File : Sap-Ordrer.xlsx
Sheets("SAP-ordrer").Copy
Set wb = ActiveWorkbook
With wb
.SaveAs GetWorkingPath() & "\Sap-Ordrer"
.Close False
End With
Set wb = Nothing
Application.DisplayAlerts = True
End Sub
</code></pre>
|
[
{
"answer_id": 74550254,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": -1,
"selected": false,
"text": "describe('download',() => {\n it('fils',() => { \n cy.visit('url')\n cy.get('.ds_class_data_sheet').click()\n cy.wait(3000)\n const numberoftest=68;\n Cypress._.times(numberoftest, (i) => {\n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink')\n .eq(i)\n .then(e1 => {\n const url=e1.prop('href')\n cy.downloadFile(url,'cypress/downloads/Datasheet','file1.pdf')\n })\n })\n})\n"
},
{
"answer_id": 74552093,
"author": "Alcock",
"author_id": 20580470,
"author_profile": "https://Stackoverflow.com/users/20580470",
"pm_score": 2,
"selected": true,
"text": "for (let i = 1; i <= numberoftest; i ++) { \n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i)\n .then(function(e1) {\n const url = e1.prop('href')\n\n // name whatever format desired, maybe last part of url\n const id = url.split('/')[3]\n const name = `file_${id}` \n\n cy.downloadFile(url,'cypress/downloads/Datasheet', name)\n })\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20416519/"
] |
74,546,138
|
<p>I got a onBackgroundMessage function for FCM that get triggered in background has intended</p>
<pre><code>Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (kDebugMode) {
print('Handling a background message ${message.messageId}');
print('message: ${message.data}');
}
GlobalStream.addBackgroundMessage(message);
}
</code></pre>
<p>The addBackground message is suppose to add the message event from FCM to a list to be reemitted when the app came back in foreground</p>
<pre><code>static final _onBcakgroundMessages = <dynamic>[];
static void addBackgroundMessage(dynamic data) {
log('Adding background message to background messages');
_onBcakgroundMessages.add(data);
}
</code></pre>
<p>Both of them seem to be triggered too but when the app came back in foreground the list is empty.</p>
<p>In the FCM doc I read that I can update data in background and thought that a simple list can be updated.</p>
<p>Can it be done with a list like that or need i to store them in a database or something like that ?</p>
<p>Thanks for anyone that can help me with that !!!</p>
|
[
{
"answer_id": 74550254,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": -1,
"selected": false,
"text": "describe('download',() => {\n it('fils',() => { \n cy.visit('url')\n cy.get('.ds_class_data_sheet').click()\n cy.wait(3000)\n const numberoftest=68;\n Cypress._.times(numberoftest, (i) => {\n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink')\n .eq(i)\n .then(e1 => {\n const url=e1.prop('href')\n cy.downloadFile(url,'cypress/downloads/Datasheet','file1.pdf')\n })\n })\n})\n"
},
{
"answer_id": 74552093,
"author": "Alcock",
"author_id": 20580470,
"author_profile": "https://Stackoverflow.com/users/20580470",
"pm_score": 2,
"selected": true,
"text": "for (let i = 1; i <= numberoftest; i ++) { \n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i)\n .then(function(e1) {\n const url = e1.prop('href')\n\n // name whatever format desired, maybe last part of url\n const id = url.split('/')[3]\n const name = `file_${id}` \n\n cy.downloadFile(url,'cypress/downloads/Datasheet', name)\n })\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15625077/"
] |
74,546,145
|
<p>Is there any (performance) difference of passing the use state hook directly to parent vs passing a function to parent in which I call use state setter?</p>
<pre><code>const Parent = () => {
const [name, setName] = useState(null);
return <Child onSelect={setName}/>
};
</code></pre>
<p>vs</p>
<pre><code>const Parent = () => {
const [name, setName] = useState(null);
const handleName = (input) => {
setName(input)
};
return <Child onSelect={handleName}/>
};
</code></pre>
<pre><code>const Child = ({onSelect}) => {
return (
//code to get name
<Button onClick={() => onSelect(name)}/>
)
}
</code></pre>
|
[
{
"answer_id": 74550254,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": -1,
"selected": false,
"text": "describe('download',() => {\n it('fils',() => { \n cy.visit('url')\n cy.get('.ds_class_data_sheet').click()\n cy.wait(3000)\n const numberoftest=68;\n Cypress._.times(numberoftest, (i) => {\n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink')\n .eq(i)\n .then(e1 => {\n const url=e1.prop('href')\n cy.downloadFile(url,'cypress/downloads/Datasheet','file1.pdf')\n })\n })\n})\n"
},
{
"answer_id": 74552093,
"author": "Alcock",
"author_id": 20580470,
"author_profile": "https://Stackoverflow.com/users/20580470",
"pm_score": 2,
"selected": true,
"text": "for (let i = 1; i <= numberoftest; i ++) { \n cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i)\n .then(function(e1) {\n const url = e1.prop('href')\n\n // name whatever format desired, maybe last part of url\n const id = url.split('/')[3]\n const name = `file_${id}` \n\n cy.downloadFile(url,'cypress/downloads/Datasheet', name)\n })\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74546145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6377312/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.