qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,375,556 | <p>My tables</p>
<ol>
<li>users</li>
</ol>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
<ol start="2">
<li>group</li>
</ol>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
<ol start="3">
<li>group_users</li>
</ol>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>user_id</th>
<th>group_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 4</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
<td>Cell 6</td>
</tr>
</tbody>
</table>
</div>
<pre><code>// All users which are members of group
public function users()
{
return $this->belongsToMany(User::class);
}
</code></pre>
<pre><code>// All groups user belong to
public function groups()
{
return $this->belongsToMany(Group::class);
}
</code></pre>
<p>This is what I have tried to do. I think the problem is that I have to make the $users an array of ids that were fetched and I'm unable to do that. Please help</p>
<pre><code>public function show(Group $group)
{
//Fetching all members of the group
$users = $group->users()->get()
return Inertia::render('Clients/Show', [
'users' => Group::whereNotIn('id', $users)->get()
]);
}
</code></pre>
| [
{
"answer_id": 74375600,
"author": "Techno",
"author_id": 2595985,
"author_profile": "https://Stackoverflow.com/users/2595985",
"pm_score": 1,
"selected": false,
"text": "$users = User\n ::whereDoesntHave('groups', fn($query) => $query->where('id', 1))\n ->get();\n"
},
{
"answer_id": 74412200,
"author": "Lindani Dube",
"author_id": 12625165,
"author_profile": "https://Stackoverflow.com/users/12625165",
"pm_score": 1,
"selected": true,
"text": "public function show(Group $group)\n{\n //Fetching all members of the group\n $exceptId = $group->users()->pluck('users.id');\n\n return Inertia::render('Clients/Show', [\n //Here it will fetch all users except those with ids matching $exceptId array\n 'users' => Group::whereNotIn('id', $exceptId)->get(),\n ]);\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12625165/"
] |
74,375,562 | <h2>Scenario:</h2>
<p>Invoice has many purchase_orders and purchase_orders has many invoices. Intermediate table is npayment_links which has foreign key invoice_id, purchase_order_id.</p>
<h2>Tech Stack</h2>
<p>Rails 5.x,
Postgresql</p>
<p>Here is my sample data</p>
<h2>invoices</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>status</th>
</tr>
</thead>
<tbody>
<tr>
<td>100</td>
<td>sample.pdf</td>
<td>archived</td>
</tr>
<tr>
<td>101</td>
<td>sample1.pdf</td>
<td>archived</td>
</tr>
<tr>
<td>102</td>
<td>sample2.pdf</td>
<td>archived</td>
</tr>
<tr>
<td>103</td>
<td>sample2.pdf</td>
<td>active</td>
</tr>
<tr>
<td>104</td>
<td>sample2.pdf</td>
<td>active</td>
</tr>
</tbody>
</table>
</div><h2>purchase_orders</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>first po</td>
</tr>
<tr>
<td>2</td>
<td>second po</td>
</tr>
<tr>
<td>3</td>
<td>third po</td>
</tr>
<tr>
<td>4</td>
<td>fourth po</td>
</tr>
</tbody>
</table>
</div><h2>npayment_links</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>purchase_order_id</th>
<th>invoice_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>100</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>101</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>102</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>100</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>103</td>
</tr>
<tr>
<td>6</td>
<td>3</td>
<td>104</td>
</tr>
<tr>
<td>7</td>
<td>4</td>
<td>100</td>
</tr>
</tbody>
</table>
</div>
<p>I am expecting query which returns all purchase_orders whose all invoices are archived.</p>
<ul>
<li>If you see npayment_links
<ul>
<li>purchase_orders with id=1 is associated with 3 invoices (100, 101, 102), which has all archived invoices.</li>
<li>purchase_orders with id=2 is associated with 2 invoices (100, 103), which has archived and active invoices.</li>
<li>purchase_orders with id=3 is associated with 1 invoice (104), which has active invoice.</li>
<li>purchase_orders with id=4 is associated with 1 invoice (100), which has archived invoice.</li>
</ul>
</li>
</ul>
<p>I'm searching for Sql query which returns PO list which contains all archived invoices.</p>
<h2>Expected purchase_orders</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>first po</td>
</tr>
<tr>
<td>4</td>
<td>fourth po</td>
</tr>
</tbody>
</table>
</div><h2>I have achieved above issue with Rails AR way. But, I'm searching for some Sql query to achieve this:</h2>
<pre><code>Invoice.find(100).purchase_orders.each do |po|
if po.invoices.all? { |inv| inv.archived? }
# po.update(status: :done) # I will do some operation here. And If there are 1000s of data in which each PO again have many invoices, I might feel this will add query complexity. So, I am searching for some optimized solution here.
end
end
</code></pre>
<p>Any feedback would be appreciated.</p>
| [
{
"answer_id": 74375600,
"author": "Techno",
"author_id": 2595985,
"author_profile": "https://Stackoverflow.com/users/2595985",
"pm_score": 1,
"selected": false,
"text": "$users = User\n ::whereDoesntHave('groups', fn($query) => $query->where('id', 1))\n ->get();\n"
},
{
"answer_id": 74412200,
"author": "Lindani Dube",
"author_id": 12625165,
"author_profile": "https://Stackoverflow.com/users/12625165",
"pm_score": 1,
"selected": true,
"text": "public function show(Group $group)\n{\n //Fetching all members of the group\n $exceptId = $group->users()->pluck('users.id');\n\n return Inertia::render('Clients/Show', [\n //Here it will fetch all users except those with ids matching $exceptId array\n 'users' => Group::whereNotIn('id', $exceptId)->get(),\n ]);\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606967/"
] |
74,375,568 | <p><a href="https://i.stack.imgur.com/i0gPn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i0gPn.png" alt="enter image description here" /></a>I Have a list containing some ids, I have to call an api with each of ids in the list and store all the data that comes from the api in a list,I am mapping through the list and calling the api with each id and then pushing the data into an array,but when I finally check the array it gives inconsistent result,sometimes it returns all the data,some time some of the data or sometimes the list is empty,here is my react code</p>
<pre><code>let deviceidlist=['eb77fa554fbdbed47dkubk','ebbaa8d217947ff4d1fk3w','ebe55d36879c7fd71emtf0','eb645acaa1efb456877nss','ebc32ad422bc5dc3eecapa','ebf5bb435e688e96e8mt5z','45102754e09806133d2d','eb7c72ba426f92b9a1pb81','eb84a574ecfa372e6ccapr','eb458f73adadf67170uxdv']
let devicelist=[]
useEffect(()=>{
const datafetch=async()=>{
deviceidlist.map((item)=>{fetch(`http://localhost:8000/api/switch/${item}`).then(data=>data.json()).then(data=>devicelist.push(data))})
}
datafetch()
}
,[])
console.log(devicelist)
</code></pre>
<p>I am trying to store all the data that I get back from api to store in a list but getting an empty array</p>
| [
{
"answer_id": 74375791,
"author": "Naveen",
"author_id": 16260451,
"author_profile": "https://Stackoverflow.com/users/16260451",
"pm_score": 1,
"selected": false,
"text": "const[deviceList, setDeviceList] = useState([]);\n useEffect(()=>{\n const datafetch=async()=>{\n deviceidlist.map((item)=>{fetch(`http://localhost:8000/api/switch/${item}`).then(data=>data.json()).then(data=>{\nsetDeviceList([...deviceList, data]);\n})})\n }\ndatafetch()\n}\n,[])\n"
},
{
"answer_id": 74375892,
"author": "Saidamir",
"author_id": 15148870,
"author_profile": "https://Stackoverflow.com/users/15148870",
"pm_score": 0,
"selected": false,
"text": "import React from 'react';\nimport { useEffect } from 'react';\n\nexport default function App() {\n\n let deviceidlist = [\n 'eb77fa554fbdbed47dkubk',\n 'ebbaa8d217947ff4d1fk3w',\n 'ebe55d36879c7fd71emtf0',\n 'eb645acaa1efb456877nss',\n 'ebc32ad422bc5dc3eecapa',\n 'ebf5bb435e688e96e8mt5z',\n '45102754e09806133d2d',\n 'eb7c72ba426f92b9a1pb81',\n 'eb84a574ecfa372e6ccapr',\n 'eb458f73adadf67170uxdv',\n ];\n\n const deviceList = [];\n\n\n useEffect( async() => {\n try {\n let response = await deviceidlist.map((item) => { fetch(`http://localhost:8000/api/switch/${item}`) })\n if (response.ok) {\n let data = await response.json()\n deviceList.push(data)\n } else {\n console.log(\"failed\")\n }\n } catch(error) {\n console.log(error)\n }\n })\n\n return (\n <div></div>\n );\n} \n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20288092/"
] |
74,375,607 | <p>I need to get the value of an environment variable from a kubernetes pod. I have my values listed in a hash table.</p>
<p>I call
<code>$hash["service-testurl"].spec.template.spec.containers.env</code>
And it returns a table:</p>
<pre><code>name value
---- -----
ADDR https://test.com
TOKEN 123456789
CERT_PATH public-certs/test
ENVIRONMENT dev
</code></pre>
<p>I need to get <a href="https://test.com" rel="nofollow noreferrer">https://test.com</a> into a variable in my ps1 script, but i'm not sure how to get this value. (consider that for each deployment the url will be different, like abc.com, def.com, ghj.com... so i can't filter by the name test.com)</p>
<p>I was looking for something like <code>$hash["service-testurl"].spec.template.spec.containers.env.name["ADDR"].value</code></p>
<p>Running <code>$hash["service-testurl"].spec.template.spec.containers.env.PSTypeNames</code> returns</p>
<pre><code>System.Object[]
System.Array
System.Object
</code></pre>
| [
{
"answer_id": 74377435,
"author": "wolfdebs",
"author_id": 11119465,
"author_profile": "https://Stackoverflow.com/users/11119465",
"pm_score": 1,
"selected": false,
"text": "$hash[\"service-testurl\"].spec.template.spec.containers.env.where{$_.name -eq 'ADDR'}.value\n"
},
{
"answer_id": 74378262,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 3,
"selected": true,
"text": "$hash[\"service-testurl\"].spec.template.spec.containers.env"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11119465/"
] |
74,375,608 | <p>im having this byte class</p>
<pre><code>b'ToCountry=US&ToState=WA&SmsMessageSid=SM2c04173b9a5f684be8019e177978c791&NumMedia=0&ToCity=&FromZip=&SmsSid=SM2c04173b9a5f684be8019e177978c791&FromState=&SmsStatus=received&FromCity=&Body=Bbjhggggggg&FromCountry=EE&To=%2B15095121752&ToZip=&NumSegments=1&ReferralNumMedia=0&MessageSid=SM2c04173b9a5f684be8019e177978c791&AccountSid=ACee01b40141d9e1237769375c269f4a76&From=%2B37253055607&ApiVersion=2010-04-01'
</code></pre>
<p>how can i convert to json</p>
| [
{
"answer_id": 74375668,
"author": "ikibir",
"author_id": 12194720,
"author_profile": "https://Stackoverflow.com/users/12194720",
"pm_score": 2,
"selected": false,
"text": "a = b'ToCountry=US&ToState=WA&SmsMessageSid=SM2c04173b9a5f684be8019e177978c791&NumMedia=0&ToCity=&FromZip=&SmsSid=SM2c04173b9a5f684be8019e177978c791&FromState=&SmsStatus=received&FromCity=&Body=Bbjhggggggg&FromCountry=EE&To=%2B15095121752&ToZip=&NumSegments=1&ReferralNumMedia=0&MessageSid=SM2c04173b9a5f684be8019e177978c791&AccountSid=ACee01b40141d9e1237769375c269f4a76&From=%2B37253055607&ApiVersion=2010-04-01'\n\ndict = {e.split(\"=\")[0]:e.split(\"=\")[1] for e in a.decode().split(\"&\")}\n\n{'ToCountry': 'US', 'ToState': 'WA', 'SmsMessageSid': 'SM2c04173b9a5f684be8019e177978c791', 'NumMedia': '0', 'ToCity': '', 'FromZip': '', 'SmsSid': 'SM2c04173b9a5f684be8019e177978c791', 'FromState': '', 'SmsStatus': 'received', 'FromCity': '', 'Body': 'Bbjhggggggg', 'FromCountry': 'EE', 'To': '%2B15095121752', 'ToZip': '', 'NumSegments': '1', 'ReferralNumMedia': '0', 'MessageSid': 'SM2c04173b9a5f684be8019e177978c791', 'AccountSid': 'ACee01b40141d9e1237769375c269f4a76', 'From': '%2B37253055607', 'ApiVersion': '2010-04-01'}\n"
},
{
"answer_id": 74376073,
"author": "bereal",
"author_id": 770830,
"author_profile": "https://Stackoverflow.com/users/770830",
"pm_score": 0,
"selected": false,
"text": "urllib.parse"
},
{
"answer_id": 74380863,
"author": "ukBaz",
"author_id": 7721752,
"author_profile": "https://Stackoverflow.com/users/7721752",
"pm_score": 0,
"selected": false,
"text": "import json\nfrom urllib.parse import parse_qs\nraw_data = b'ToCountry=US&ToState=WA&SmsMessageSid=SM2c04173b9a5f684be8019e177978c791&NumMedia=0&ToCity=&FromZip=&SmsSid=SM2c04173b9a5f684be8019e177978c791&FromState=&SmsStatus=received&FromCity=&Body=Bbjhggggggg&FromCountry=EE&To=%2B15095121752&ToZip=&NumSegments=1&ReferralNumMedia=0&MessageSid=SM2c04173b9a5f684be8019e177978c791&AccountSid=ACee01b40141d9e1237769375c269f4a76&From=%2B37253055607&ApiVersion=2010-04-01'\n\nparam_data = parse_qs(raw_data.decode())\njson_data = json.dumps(param_data, indent=4)\nprint(json_data)\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3073987/"
] |
74,375,611 | <p><strong>Scenario:</strong>
The API basically calls an endpoint to get the token and then sets the token in the header and calls another endpoint along with other query parameters.</p>
<p><strong>Problem:</strong>
I'm getting the null resolving to address issue.</p>
<pre><code>[2022-11-09 18:08:19,327] INFO {LogMediator} - {api:MsaasproEsb} To: http://www.w3.org/2005/08/addressing/anonymous, WSAction: , SOAPAction: , MessageID: urn:uuid:e763462f-c7dc-4f3d-a8ba-b23c5f66a241, correlation_id: 7dba4bab-4218-48ca-9871-e4c2d249a91b, Direction: request, Payload: {"Data": {"status": 200, "id": 190, "user_id": "secpapi", "email": "Faisal.furqan@secp.gov.pk", "token": "9704e4de2acde3af0686c22d409f831db3d1fd76"}}
[2022-11-09 18:08:19,328] INFO {TRACE_LOGGER} - Sending message through endpoint : null resolving to address = https://msaaspro.com/api/v1/scan/pep-scan/?fullname={uri.var.name}&searchtype=fuzzy&fathername={uri.var.fatherName}&dobyear={uri.var.dobYear}&cnic={uri.var.cnic}&mobile={uri.var.mobile}&country={uri.var.country}&name_similarity=90
[2022-11-09 18:08:19,328] INFO {TRACE_LOGGER} - SOAPAction:
[2022-11-09 18:08:19,328] INFO {TRACE_LOGGER} - WSA-Action:
[2022-11-09 18:09:17,775] INFO {SourceHandler} - Writer null when calling informWriterError
[2022-11-09 18:09:17,775] WARN {SourceHandler} - STATE_DESCRIPTION = Socket Timeout occurred after accepting the request headers and the request body, INTERNAL_STATE = REQUEST_DONE, DIRECTION = REQUEST, CAUSE_OF_ERROR = Connection between the client and the EI timeouts, HTTP_URL = /msaaspro/send, HTTP_METHOD = POST, SOCKET_TIMEOUT = 180000, CLIENT_ADDRESS = /127.0.0.1:55470, CONNECTION http-incoming-4 Correlation ID : 965986e6-2d6b-4108-aefe-3a7a648eb61a
[2022-11-09 18:10:44,079] INFO {SourceHandler} - Writer null when calling informWriterError
[2022-11-09 18:10:44,079] WARN {SourceHandler} - STATE_DESCRIPTION = Socket Timeout occurred after accepting the request headers and the request body, INTERNAL_STATE = REQUEST_DONE, DIRECTION = REQUEST, CAUSE_OF_ERROR = Connection between the client and the EI timeouts, HTTP_URL = /msaaspro/send, HTTP_METHOD = POST, SOCKET_TIMEOUT = 180000, CLIENT_ADDRESS = /127.0.0.1:58755, CONNECTION http-incoming-5 Correlation ID : 1fc72034-a9d1-46ad-9198-d18810065c10
[2022-11-09 18:11:19,011] INFO {SourceHandler} - Writer null when calling informWriterError
[2022-11-09 18:11:19,011] WARN {SourceHandler} - STATE_DESCRIPTION = Socket Timeout occurred after accepting the request headers and the request body, INTERNAL_STATE = REQUEST_DONE, DIRECTION = REQUEST, CAUSE_OF_ERROR = Connection between the client and the EI timeouts, HTTP_URL = /msaaspro/send, HTTP_METHOD = POST, SOCKET_TIMEOUT = 180000, CLIENT_ADDRESS = /127.0.0.1:58781, CONNECTION http-incoming-6 Correlation ID : 7dba4bab-4218-48ca-9871-e4c2d249a91b
</code></pre>
<p><strong>Source code</strong>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<api context="/msaaspro" name="MsaasproEsb" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="POST" uri-template="/send">
<inSequence>
<property description="username" name="username" scope="default" type="STRING" value="json-eval($.username)"/>
<property description="password" name="password" scope="default" type="STRING" value="json-eval($.password)"/>
<call>
<endpoint>
<http method="post" statistics="enable" uri-template="https://msaaspro.com/api/v1/auth/auth-token/">
<suspendOnFailure>
<initialDuration>-1</initialDuration>
<progressionFactor>-1</progressionFactor>
<maximumDuration>0</maximumDuration>
</suspendOnFailure>
<markForSuspension>
<retriesBeforeSuspension>0</retriesBeforeSuspension>
</markForSuspension>
</http>
</endpoint>
</call>
<property description="token" name="token" scope="default" type="STRING" value="json-eval($.Data.token)"/>
<property description="Authorization" name="Authorization" scope="transport" type="STRING" value="fn:concat('Token ', get-property('token'))"/>
<property description="name" name="uri.var.name" scope="default" type="STRING" value="json-eval($.name)"/>
<property description="fatherName" name="uri.var.fatherName" scope="default" type="STRING" value="json-eval($.fatherName)"/>
<property description="dobYear" name="uri.var.dobYear" scope="default" type="STRING" value="json-eval($.dobYear)"/>
<property description="uniqueKey" name="uri.var.cnic" scope="default" type="STRING" value="json-eval($.cnic)"/>
<property description="country" name="uri.var.country" scope="default" type="STRING" value="json-eval($.country)"/>
<property description="mobile" name="uri.var.mobile" scope="default" type="STRING" value="json-eval($.mobile)"/>
<log level="full"/>
<call>
<endpoint>
<http method="get" statistics="enable" trace="enable" uri-template="https://msaaspro.com/api/v1/scan/pep-scan/?fullname={uri.var.name}&amp;searchtype=fuzzy&amp;fathername={uri.var.fatherName}&amp;dobyear={uri.var.dobYear}&amp;cnic={uri.var.cnic}&amp;mobile={uri.var.mobile}&amp;country={uri.var.country}&amp;name_similarity=90">
<suspendOnFailure>
<initialDuration>-1</initialDuration>
<progressionFactor>-1</progressionFactor>
<maximumDuration>0</maximumDuration>
</suspendOnFailure>
<markForSuspension>
<retriesBeforeSuspension>0</retriesBeforeSuspension>
</markForSuspension>
</http>
</endpoint>
</call>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence/>
</resource>
</api>
</code></pre>
<p><strong>Question:</strong>
My exact question is why I'm getting null resolving issue while I've set properties for all the parameters that I've passed to the endpoint. I'm able to call the first endpoint and I successfully get the token but somehow I'm unable to call the second endpoint.</p>
| [
{
"answer_id": 74376084,
"author": "ycr",
"author_id": 2627018,
"author_profile": "https://Stackoverflow.com/users/2627018",
"pm_score": 0,
"selected": false,
"text": "pep-scan"
},
{
"answer_id": 74386771,
"author": "sanoJ",
"author_id": 9263083,
"author_profile": "https://Stackoverflow.com/users/9263083",
"pm_score": 2,
"selected": true,
"text": "expression"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7454536/"
] |
74,375,620 | <p>I know there are <em>many</em> questions about <code>this</code>, and I have read many answers and references, including <a href="https://stackoverflow.com/a/20279485/1925272">this canonical answer</a>. However, I am not able to derive a solution to my specific problem.</p>
<p>Here is a sample code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class A {
myField;
constructor(myField) {
this.myField = myField;
}
myMethod() {
console.log(this.myField);
}
}
class B {
constructor(myFunc) {
myFunc();
}
}
const a = new A("Hello");
const b = new B(a.myMethod);</code></pre>
</div>
</div>
</p>
<p>I get this error:</p>
<blockquote>
<p>Cannot read properties of undefined (reading 'myField')</p>
</blockquote>
<p>It seems that <code>this</code> inside <code>myMethod</code> is <code>undefined</code> and does not refer to the instance of <code>A</code>, as I would expect (coming from C#...).</p>
<p>What can I do to refer to <code>myField</code>?</p>
| [
{
"answer_id": 74375761,
"author": "StephenHawking",
"author_id": 13988248,
"author_profile": "https://Stackoverflow.com/users/13988248",
"pm_score": 0,
"selected": false,
"text": "class A {\n\n constructor(myField) {\n this.myField = myField;\n }\n\n myMethod(instance) {\n console.log(instance.myField);\n }\n}\n\nclass B {\n constructor(myFunc, instance) {\n myFunc(instance);\n }\n}\n\nconst a = new A(\"Hello\");\nconst b = new B(a.myMethod, a);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925272/"
] |
74,375,621 | <p>How to convert <code>List<string></code> to <code>List<object></code> property in c#</p>
<p>We have a list of email id's</p>
<pre><code>List<string> str= new List<string>{"abc1@gmail.com","abc2@gmail.com"};
</code></pre>
<p>and now we have to assign these email IDs to the list of an employee <code>List<Employee></code> emailId property.</p>
<pre><code>var emplist = new List<Employee>() ;
</code></pre>
| [
{
"answer_id": 74375622,
"author": "Samadhan",
"author_id": 5521340,
"author_profile": "https://Stackoverflow.com/users/5521340",
"pm_score": 0,
"selected": false,
"text": "List<string>"
},
{
"answer_id": 74375691,
"author": "Prasad Telkikar",
"author_id": 6299857,
"author_profile": "https://Stackoverflow.com/users/6299857",
"pm_score": 3,
"selected": false,
"text": "Select()"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5521340/"
] |
74,375,624 | <p>I am currently trying to get the Size and reshape my rectangle to the actual size of the image (width and height). However when i use Image.Height or Image.Width its always 0. The picture that is displayed when i start the program takes up the entire screen</p>
<pre><code> Uri imageUri = new Uri(FileListe[position]);
Image Bild = new Image();
Bild.Source = new BitmapImage(imageUri);
Interface.Width = Bild.Width;
Interface.Height = Bild.Height;
brush.ImageSource = new BitmapImage(imageUri);
Interface.Fill = brush;
</code></pre>
| [
{
"answer_id": 74375622,
"author": "Samadhan",
"author_id": 5521340,
"author_profile": "https://Stackoverflow.com/users/5521340",
"pm_score": 0,
"selected": false,
"text": "List<string>"
},
{
"answer_id": 74375691,
"author": "Prasad Telkikar",
"author_id": 6299857,
"author_profile": "https://Stackoverflow.com/users/6299857",
"pm_score": 3,
"selected": false,
"text": "Select()"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20450256/"
] |
74,375,659 | <p>Considering this code:</p>
<pre><code>var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
println(x);
</code></pre>
<p>Why would the output be 6? Can someone break it down for me?</p>
<p>I understand that x will continue adding 1 to it's value, but why does the i<3 limit it to 6?</p>
| [
{
"answer_id": 74375710,
"author": "arthur",
"author_id": 1275802,
"author_profile": "https://Stackoverflow.com/users/1275802",
"pm_score": 1,
"selected": false,
"text": "i = 0 => x +1 = 4\ni = 1 => x + 1 = 5\ni = 2 => x + 1 = 6\ni = 3 => exit loop\n"
},
{
"answer_id": 74377098,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "var x = 3;\nvar i = 0;\nwhile (i < 3) {\n x += 1;\n i += 1;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19944757/"
] |
74,375,662 | <pre><code>print(n1)
print(n2)
print(type(n1), type(n2))
print(scipy.stats.spearmanr(n1, n2))
print(n1.corr(n2, method="spearman"))
0 2317.0
1 2293.0
2 1190.0
3 972.0
4 1391.0
Name: r6000, dtype: float64
0.0 2317.0
1.0 2293.0
3.0 1190.0
4.0 972.0
5.0 1391.0
Name: 6000, dtype: float64
<class 'pandas.core.series.Series'> <class 'pandas.core.series.Series'>
SpearmanrResult(correlation=0.9999999999999999, pvalue=1.4042654220543672e-24)
0.7999999999999999
</code></pre>
<p>The problem is that scipy was reporting a different correlation value than pandas.</p>
<p>Edit to add:</p>
<p>The issue is the indexes are off. Pandas does automatic intrinsic data alignment, but scipy doesn't. I've answered it below.</p>
| [
{
"answer_id": 74375710,
"author": "arthur",
"author_id": 1275802,
"author_profile": "https://Stackoverflow.com/users/1275802",
"pm_score": 1,
"selected": false,
"text": "i = 0 => x +1 = 4\ni = 1 => x + 1 = 5\ni = 2 => x + 1 = 6\ni = 3 => exit loop\n"
},
{
"answer_id": 74377098,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "var x = 3;\nvar i = 0;\nwhile (i < 3) {\n x += 1;\n i += 1;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538524/"
] |
74,375,664 | <pre><code></code></pre>
<pre><code>vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
int prevColor = image[sr][sc];
int m = image.size();
int n = image[0].size();
image[sr][sc] = color;
stack <pair<int, int>> positionToVisit;
positionToVisit.push({sr, sc});
int t = 3000;
while (!positionToVisit.empty() && t--) { //There is a problem I couldn't solve, except giving t is getting time limit error
if (sr>0 && image[sr-1][sc] == prevColor ) {
image[sr-1][sc] = color;
positionToVisit.push({sr-1, sc});
}
if (sr<m-1 && image[sr+1][sc] == prevColor ) {
image[sr+1][sc] = color;
positionToVisit.push({sr+1, sc});
}
if (sc>0 && image[sr][sc-1] == prevColor ) {
image[sr][sc-1] = color;
positionToVisit.push({sr, sc-1});
}
if (sr<n-1 && image[sr][sc+1] == prevColor ) {
image[sr][sc+1] = color;
positionToVisit.push({sr, sc+1});
}
sr = positionToVisit.top().first;
sc = positionToVisit.top().second;
image[sr][sc] = color;
positionToVisit.pop();
}
return image;
}
</code></pre>
<pre><code></code></pre>
<p>If I don't use the 't' variable in the while() condition, it falls in time limit exceeded and it is not stopping when stack getting empty and continuing infinity loop. But when I'm using t here it immediately breaks when the stack is being empty. I couldn't figure out the problem.</p>
| [
{
"answer_id": 74376352,
"author": "jwezorek",
"author_id": 1413244,
"author_profile": "https://Stackoverflow.com/users/1413244",
"pm_score": 1,
"selected": false,
"text": "if (sr<n-1 && image[sr][sc+1] == prevColor )\n"
},
{
"answer_id": 74377343,
"author": "olaf",
"author_id": 7205387,
"author_profile": "https://Stackoverflow.com/users/7205387",
"pm_score": 0,
"selected": false,
"text": "if(color == prevColor) {\n return image;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12315498/"
] |
74,375,681 | <p>I'm fairly new to React. I am working on a note app and when I add 2 notes, they have the same key and the next 2 notes also share their own key and so on. I started off with prop drilling from the App to the AddNote file via NotesList.js and it was working fine and the problem has only occurred since I used useContext API so maybe I am not coding the useContext in the correct way. The useContext component looks like this:</p>
<pre><code>import { createContext } from "react";
const HandleAddContext = createContext();
export default HandleAddContext;
</code></pre>
<p>This is my App.js</p>
<pre><code>import { useState } from "react";
import { v4 as uuid } from "uuid";
import NotesList from "./components/NotesList";
import HandleAddContext from "./components/UseContext/HandleAddContext";
const unique_id = uuid();
const small_id = unique_id.slice(0, 8);
const initialState = [
{
id: small_id,
text: "1st note",
date: "12/10/22022",
},
{
id: small_id,
text: "2nd note",
date: "15/10/22022",
},
{
id: small_id,
text: "3rd note",
date: "16/10/22022",
},
{
id: small_id,
text: "4th note",
date: "30/10/22022",
},
];
export const App = () => {
const [notes, setNote] = useState(initialState);
const addHandleNote = (text) => {
console.log(text);
const date = new Date();
const newNote = {
id: small_id,
text: text,
date: date.toLocaleDateString(),
};
console.log(newNote);
const newNotes = [...notes, newNote];
setNote(newNotes);
};
return (
<HandleAddContext.Provider value={addHandleNote}>
<div className="container">
<NotesList notes={notes} />
</div>
</HandleAddContext.Provider>
);
};
export default App;
</code></pre>
<p>This is the component with map notes</p>
<pre><code>import Note from "./Note";
import AddNote from "./AddNote";
const NotesList = ({ notes }) => {
return (
<div className="notes-list">
{notes.map((note) => (
<Note key={note.id} id={note.id} text={note.text} date={note.date} />
))}
<AddNote />
</div>
);
};
export default NotesList;
</code></pre>
<p>This is the Note:</p>
<pre><code>import { RiDeleteBin6Line } from "react-icons/ri";
const Note = ({ text, date }) => {
return (
<div className="note">
{/* <div> */}
<p>{text}</p>
{/* </div> */}
<div className="note-footer">
<p className="note-footer-text">{date}</p>
<RiDeleteBin6Line />
</div>
</div>
);
};
export default Note;
</code></pre>
<p>This is the AddNote.js component</p>
<pre><code>import { useState } from "react";
import { RiSave2Line } from "react-icons/ri";
const AddNote = ({ handleAddNote }) => {
const [addText, setAddText] = useState("");
const [errorMsg, setErrorMsg] = useState("");
//handle text input
const handleChange = (e) => {
console.log(e.target.value);
setAddText(e.target.value);
};
//handle save
const handleSaveClick = () => {
if (addText.trim().length > 0) {
handleAddNote(addText);
}
};
return (
<div>
<textarea
rows="8"
cols="10"
placeholder="Type here to add a note..."
value={addText}
onChange={handleChange}
/>
<div>
<p>200 characters remaining</p>
<RiSave2Line onClick={handleSaveClick} />
</div>
</div>
);
};
export default AddNote;
</code></pre>
| [
{
"answer_id": 74376352,
"author": "jwezorek",
"author_id": 1413244,
"author_profile": "https://Stackoverflow.com/users/1413244",
"pm_score": 1,
"selected": false,
"text": "if (sr<n-1 && image[sr][sc+1] == prevColor )\n"
},
{
"answer_id": 74377343,
"author": "olaf",
"author_id": 7205387,
"author_profile": "https://Stackoverflow.com/users/7205387",
"pm_score": 0,
"selected": false,
"text": "if(color == prevColor) {\n return image;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20396703/"
] |
74,375,683 | <p>im trying to learn how to reverse a number but came across a problem about this Do-While loop. Specifically
<code>while (n1)</code>. Usually i just see people put in a condition with about comparison.</p>
<pre><code>#include <iostream>
#include <conio.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{
long int n1, n2, Rinteger = 0;
cout << "Enter an integer: " << endl;
cin >> n1;
n2 = n1;
do
{
Rinteger *= 10;
int digit = n1 % 10;
Rinteger += digit;
n1 /= 10;
} while (n1);
cout << "Initial integer: " << n2 << "." << endl;
cout << "Reversed integer: " << Rinteger << "." << endl;
return 0;
}
</code></pre>
<p>There are other ways to reverse an integer but i am curious about how does this Do-While loop works</p>
| [
{
"answer_id": 74376352,
"author": "jwezorek",
"author_id": 1413244,
"author_profile": "https://Stackoverflow.com/users/1413244",
"pm_score": 1,
"selected": false,
"text": "if (sr<n-1 && image[sr][sc+1] == prevColor )\n"
},
{
"answer_id": 74377343,
"author": "olaf",
"author_id": 7205387,
"author_profile": "https://Stackoverflow.com/users/7205387",
"pm_score": 0,
"selected": false,
"text": "if(color == prevColor) {\n return image;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18519699/"
] |
74,375,686 | <p>There is <code>ParentFragment</code> that shows <code>DialogFragment</code>. I <code>collect</code> a dialog result through <code>SharedFlow</code>. When result received, dialog dismissed. Should I stop <code>collect</code> by additional code? What happens when dialog closed, but fragment still resumed?</p>
<pre><code>// ParentFragment
private fun save() {
val dialog = ContinueDialogFragment(R.string.dialog_is_save_task)
dialog.show(parentFragmentManager, "is_save_dialog")
lifecycleScope.launch {
dialog.resultSharedFlow.collect {
when (it) {
ContinueDialogFragment.RESULT_YES -> {
viewModel.saveTask()
closeFragment()
}
ContinueDialogFragment.RESULT_NO -> {
closeFragment()
}
ContinueDialogFragment.RESULT_CONTINUE -> {
// dont close fragment
}
}
}
}
}
class ContinueDialogFragment(
@StringRes private val titleStringId: Int,
@StringRes private val messageStringId: Int? = null
) : DialogFragment() {
private val _resultSharedFlow = MutableSharedFlow<Int>(1)
val resultSharedFlow = _resultSharedFlow.asSharedFlow()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let { context ->
AlertDialog.Builder(context)
.setTitle(getString(titleStringId))
.setMessage(messageStringId?.let { getString(it) })
.setPositiveButton(getString(R.string.dialog_yes)) { _, _ ->
_resultSharedFlow.tryEmit(RESULT_YES)
}
.setNegativeButton(getString(R.string.dialog_no)) { _, _ ->
_resultSharedFlow.tryEmit(RESULT_NO)
}
.setNeutralButton(getString(R.string.dialog_continue)) { _, _ ->
_resultSharedFlow.tryEmit(RESULT_CONTINUE)
}
.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
companion object {
const val RESULT_YES = 1
const val RESULT_NO = 0
const val RESULT_CONTINUE = 2
}
}
</code></pre>
| [
{
"answer_id": 74376352,
"author": "jwezorek",
"author_id": 1413244,
"author_profile": "https://Stackoverflow.com/users/1413244",
"pm_score": 1,
"selected": false,
"text": "if (sr<n-1 && image[sr][sc+1] == prevColor )\n"
},
{
"answer_id": 74377343,
"author": "olaf",
"author_id": 7205387,
"author_profile": "https://Stackoverflow.com/users/7205387",
"pm_score": 0,
"selected": false,
"text": "if(color == prevColor) {\n return image;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894542/"
] |
74,375,694 | <p>Are these 2 situations in Constraint Layout equivalent?</p>
<p><strong>First situation:</strong></p>
<p><em>Attributes of element 1:</em></p>
<pre><code> android:id="@+id/view1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
</code></pre>
<p><em>Attributes of element 2:</em></p>
<pre><code> android:id="@+id/view2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
</code></pre>
<p><strong>Second situation:</strong></p>
<p><em>Attributes of element 1:</em></p>
<pre><code> android:id="@+id/view1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
</code></pre>
<p><em>Attributes of element 2:</em></p>
<pre><code> android:id="@+id/view2"
app:layout_constraintEnd_toEndOf="@+id/view1"
app:layout_constraintStart_toStartOf="@+id/view1"
</code></pre>
<p>All the xml code:</p>
<p><strong>First situation:</strong></p>
<pre><code><androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<View
android:id="@+id/view1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/blue"
app:layout_constraintBottom_toTopOf="@+id/view2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/view2"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/black"
app:layout_constraintTop_toBottomOf="@+id/view1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p><strong>Second situation:</strong></p>
<pre><code> <androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/view1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/blue"
app:layout_constraintBottom_toTopOf="@+id/view2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/view2"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/black"
app:layout_constraintTop_toBottomOf="@+id/view1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/view1"
app:layout_constraintStart_toStartOf="@id/view1"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>In conclusion, is it the same to constraint both views to the same "thing" and to constraint one view to "something" and later constraining a second view to the first view? What situation is better implemented, First sutuation or Second situation?</p>
| [
{
"answer_id": 74376352,
"author": "jwezorek",
"author_id": 1413244,
"author_profile": "https://Stackoverflow.com/users/1413244",
"pm_score": 1,
"selected": false,
"text": "if (sr<n-1 && image[sr][sc+1] == prevColor )\n"
},
{
"answer_id": 74377343,
"author": "olaf",
"author_id": 7205387,
"author_profile": "https://Stackoverflow.com/users/7205387",
"pm_score": 0,
"selected": false,
"text": "if(color == prevColor) {\n return image;\n}\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20018861/"
] |
74,375,708 | <p>I want to remove specific or full parameters from the URL of the website when it is actively loading in the browser. I want to do this because some website including additional strings.</p>
<pre><code>https://www.example.com/?gclid=anything
https://www.example.com/?fbclid=anything
https://www.example.com/?msclid=anything
</code></pre>
<p>These are the tokens sent by third party like Google, Facebook, etc. I want to remove that.</p>
<p>For example, if peoples click my link on facebook <code>https://www.example.com/</code> than Facebook will include <code>https://www.example.com/?fbclid=something</code> but i want <code>?fbclid=something</code> should be removed and peoples land to <code>https://www.example.com/</code> instead of <code>https://www.example.com/?fbclid=something</code></p>
<p>My code :</p>
<pre><code>$url = strtok($_SERVER["REQUEST_URI"], '?');
</code></pre>
<p>I have already checked <a href="https://stackoverflow.com/questions/4937478/strip-off-url-parameter-with-php">Strip off URL parameter with PHP</a> & <a href="https://stackoverflow.com/questions/6969645/how-to-remove-the-querystring-and-get-only-the-url">How to remove the querystring and get only the URL?</a> but no success.</p>
<p>Please suggest me how to achieve this using PHP or JavaScript.</p>
| [
{
"answer_id": 74375867,
"author": "dvicemuse",
"author_id": 1155184,
"author_profile": "https://Stackoverflow.com/users/1155184",
"pm_score": 2,
"selected": true,
"text": "https://www.example.com/?fbclid=something"
},
{
"answer_id": 74378139,
"author": "Sted",
"author_id": 19897682,
"author_profile": "https://Stackoverflow.com/users/19897682",
"pm_score": 0,
"selected": false,
"text": "<script>\n//window.history.pushState('', '', '/');\n//window.history.pushState({}, '', '/'); \nwindow.history.pushState({}, '', window.location.pathname);\n</script>\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19897682/"
] |
74,375,721 | <p>I want to check if child component is mounted and I want to move that information to he parent component. For this I am using emits.
So with example here is my parent component:</p>
<pre><code><child @is-child-mounted="childMounted" />
export default {
data() {
return {
childMounted: false,
};
},
mounted() {
if (this.childMounted) {
//do something
}
},
}
</code></pre>
<p>and in child component, I am changing 'is-child-mounted' to true:</p>
<pre><code>mounted() {
this.$emit('isChildMounted', true);
},
</code></pre>
<p>But still <strong>if (this.childMounted)</strong> comes false. So how can I check in parent component if the child component is mounted?</p>
| [
{
"answer_id": 74375867,
"author": "dvicemuse",
"author_id": 1155184,
"author_profile": "https://Stackoverflow.com/users/1155184",
"pm_score": 2,
"selected": true,
"text": "https://www.example.com/?fbclid=something"
},
{
"answer_id": 74378139,
"author": "Sted",
"author_id": 19897682,
"author_profile": "https://Stackoverflow.com/users/19897682",
"pm_score": 0,
"selected": false,
"text": "<script>\n//window.history.pushState('', '', '/');\n//window.history.pushState({}, '', '/'); \nwindow.history.pushState({}, '', window.location.pathname);\n</script>\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19850691/"
] |
74,375,739 | <p><strong>I was using <a href="https://pub.dev/packages/sn_progress_dialog/install" rel="nofollow noreferrer">sn_progress_dialog</a> when I ran into the error that the asset for this dependency is not found..</strong></p>
<p>However, the official documentation does not mention anything about setting assets for this dependency.
<a href="https://i.stack.imgur.com/kcJTS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kcJTS.png" alt="enter image description here" /></a></p>
<p>I tried the guidelines to get the dependency and it was working fine. when I reopened the project and it stopped throwing this error.</p>
<p>**I have tried:</p>
<p>flutter pub get and
flutter pub add sn_progress_dialog commands**</p>
<p><em>My pubspec.yaml file is</em></p>
<pre><code> name: multi_store_app
description: By RRB Productions
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=2.19.0-201.0.dev <3.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
animated_text_kit: ^4.2.2
image_picker: ^0.8.6
firebase_auth: ^3.11.2
cloud_firestore: ^3.5.1
firebase_storage: ^10.3.11
firebase_core: ^1.24.0
firebase_app_check: ^0.0.9+1
uuid: ^3.0.6
flutter_staggered_grid_view: ^0.6.2
staggered_grid_view_flutter: ^0.0.4
firebase_core_platform_interface: 4.5.1
flutter_swiper_null_safety: ^1.0.2
flutter_launcher_icons: ^0.10.0
font_awesome_flutter: ^10.2.1
provider: ^6.0.4
awesome_snackbar_content: ^0.0.9
badges: ^2.0.3
sn_progress_dialog: ^1.0.8
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
flutter_icons:
image_path: "assets/images/icon.png"
# image_path_android: "assets/images/android/icon.png"
# image_path_ios: "aseets/images/ios/icon.png"
android: true
ios: true
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/accessories/
- images/bags/
- images/try/
- images/beauty/
- images/electronics/
- images/homegarden/
- images/inapp/
- images/kids/
- images/men/
- images/shoes/
- images/women/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
fonts:
- family: Acme
fonts:
- asset: fonts/Acme-Regular.ttf
- family: AKayaTelivigala
fonts:
- asset: fonts/AkayaTelivigala-Regular.ttf
</code></pre>
<p><em>My code for the dependency is here</em></p>
<p><a href="https://i.stack.imgur.com/yCRHt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yCRHt.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74375867,
"author": "dvicemuse",
"author_id": 1155184,
"author_profile": "https://Stackoverflow.com/users/1155184",
"pm_score": 2,
"selected": true,
"text": "https://www.example.com/?fbclid=something"
},
{
"answer_id": 74378139,
"author": "Sted",
"author_id": 19897682,
"author_profile": "https://Stackoverflow.com/users/19897682",
"pm_score": 0,
"selected": false,
"text": "<script>\n//window.history.pushState('', '', '/');\n//window.history.pushState({}, '', '/'); \nwindow.history.pushState({}, '', window.location.pathname);\n</script>\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12898752/"
] |
74,375,746 | <p>I want to convert a VARCHAR2-value like '-28:15:00' to INTERVAL.</p>
<p>With a literal value, this works:</p>
<pre><code>select interval '-09:11:36' hour to second from dual;
</code></pre>
<p>However, this does not (ORA-00923: FROM keyword not found where expected):</p>
<pre><code>select interval MY_VARCHAR hour to second from MY_TABLE;
--comparable to select interval to_char(sysdate, 'hh:mm:ss') hour to second from dual;
</code></pre>
<p>My assumption is that the literal value is implicitly cast while the explicit varchar-value from MY_VARCHAR (or char from to_char respectively) is not valid between "interval" and "hour".</p>
<p>CAST like this does not work (ORA-00963: unsupported interval type):</p>
<pre><code>select cast(MY_VARCHAR as interval hour to second) from MY_TABLE;
--comparable to select cast('09:11:36' as interval hour to second) from dual;
</code></pre>
<p>What does work is concatenating '0 ' as the day-value and cast it to INTERVAL DAY TO SECOND:</p>
<pre><code>select cast('0 ' || '09:11:36' as interval day to second) from dual;
</code></pre>
<p>However this only works for positive values, and as long as the value for hour is below 24.
Is there a better solution than dissecting the VARCHAR-value with CASE, SUBSTR and so on?</p>
| [
{
"answer_id": 74375867,
"author": "dvicemuse",
"author_id": 1155184,
"author_profile": "https://Stackoverflow.com/users/1155184",
"pm_score": 2,
"selected": true,
"text": "https://www.example.com/?fbclid=something"
},
{
"answer_id": 74378139,
"author": "Sted",
"author_id": 19897682,
"author_profile": "https://Stackoverflow.com/users/19897682",
"pm_score": 0,
"selected": false,
"text": "<script>\n//window.history.pushState('', '', '/');\n//window.history.pushState({}, '', '/'); \nwindow.history.pushState({}, '', window.location.pathname);\n</script>\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206791/"
] |
74,375,747 | <p>How can I turn each element in a numpy array into its index in another array?</p>
<p>Take the following example. Let <code>a = np.array(["a", "c", "b", "c", "a", "a"])</code> and <code>b = np.array(["b", "c", "a"])</code>. How can I turn each element in <code>a</code> into its index in <code>b</code> to obtain <code>c = np.array([2, 1, 0, 1, 2, 2])</code>?</p>
| [
{
"answer_id": 74375913,
"author": "Bharat Adhikari",
"author_id": 17731030,
"author_profile": "https://Stackoverflow.com/users/17731030",
"pm_score": 2,
"selected": false,
"text": "import numpy as np\na = np.array([\"a\", \"c\", \"b\", \"c\", \"a\", \"a\"])\n\nb = np.array([\"b\", \"c\", \"a\"])\n\n# Create hashmap/dictionary to store indexes \nhashmap ={}\nfor index,value in enumerate(b):\n hashmap[value]=index\n\n# Create empty np array to store results\nc=np.array([])\n\n# Check the corresponding index using hashmap and append to result\nfor value in a:\n c= np.append(c,hashmap[value])\n"
},
{
"answer_id": 74376001,
"author": "Piotr Żak",
"author_id": 9455902,
"author_profile": "https://Stackoverflow.com/users/9455902",
"pm_score": 0,
"selected": false,
"text": "for j in a:\n for i, val in enumerate(b):\n if val == j:\n print(i)\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5308892/"
] |
74,375,751 | <p>I would like to create a <code>const std::vector</code> to contain all the elements of two other <code>const std::vector</code> of the same type. Since the vector is <code>const</code> I can not concatenate it step by step with the two <code>const std::vector</code> using the method mentioned in <a href="https://stackoverflow.com/questions/201718/concatenating-two-stdvectors">Concatenating two std::vectors</a>.</p>
<pre><code>#include <iostream>
#include <vector>
int main()
{
const std::vector<int> int_a{0,1};
const std::vector<int> int_b{2,3};
const std::vector<int> all_ints;
for (int i: all_ints)
std::cout << i << ' ';
return 0;
}
</code></pre>
<p>For the example above I would like to define <code>all_ints</code> in a way that the output is <code>0 1 2 3</code>.</p>
<p>How could that be done?</p>
| [
{
"answer_id": 74375849,
"author": "Ayxan Haqverdili",
"author_id": 10147399,
"author_profile": "https://Stackoverflow.com/users/10147399",
"pm_score": 4,
"selected": true,
"text": "const std::vector<int> int_a{0,1};\nconst std::vector<int> int_b{2,3};\nconst std::vector<int> all_ints = concat(int_a, int_b);\n"
},
{
"answer_id": 74375902,
"author": "Saeed Amiri",
"author_id": 416926,
"author_profile": "https://Stackoverflow.com/users/416926",
"pm_score": 2,
"selected": false,
"text": "const std::vector<int> int_a{0,1};\nconst std::vector<int> int_b{2,3};\nstd::vector<int> middle(int_a);\nmiddle.insert(middle.begin(),int_b.begin(),int_b.end());\nconst std::vector<int> all_ints(middle);\n"
},
{
"answer_id": 74376170,
"author": "Fareanor",
"author_id": 11455384,
"author_profile": "https://Stackoverflow.com/users/11455384",
"pm_score": 1,
"selected": false,
"text": "template <template <typename, typename> typename C, typename ... Args>\nC<Args...> concat(const C<Args...> & lhs, const C<Args...> & rhs)\n{\n C<Args...> res(lhs.cbegin(), lhs.cend());\n res.insert(res.cend(), rhs.cbegin(), rhs.cend());\n return res;\n}\n"
},
{
"answer_id": 74379908,
"author": "MarkB",
"author_id": 17841694,
"author_profile": "https://Stackoverflow.com/users/17841694",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <array>\n#include <ranges>\n#include <vector>\n#include <utility>\n\ntemplate<typename T1, typename T2>\nauto concat_view(T1& lhs, T2& rhs)\n{\n static_assert(std::is_same_v<std::decay_t<T1>, std::decay_t<T2>>);\n using T1_ = std::remove_reference_t<T1>;\n using T2_ = std::remove_reference_t<T2>;\n if constexpr (std::is_const_v<T1_> || std::is_const_v<T2_>)\n {\n using Iter = typename std::decay_t<T1>::const_iterator;\n return std::array<std::ranges::subrange<Iter>, 2>{std::as_const(lhs), std::as_const(rhs)} | std::views::join;\n }\n else\n {\n using Iter = typename std::decay_t<T1>::iterator;\n return std::array<std::ranges::subrange<Iter>, 2>{lhs, rhs} | std::views::join;\n } \n}\n\nint main()\n{\n std::vector<int> v1{1,2,3}, v2{4,5,6};\n for (int& val : concat_view(v1, v2))\n ++val;\n for (const auto& val : concat_view(std::as_const(v1), v2))\n std::cout << val << '\\n';\n return 0;\n}\n"
},
{
"answer_id": 74380785,
"author": "doug",
"author_id": 5282154,
"author_profile": "https://Stackoverflow.com/users/5282154",
"pm_score": 1,
"selected": false,
"text": "all_ints"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12828370/"
] |
74,375,757 | <p>I have a list of lists of strings (Essentially it's a corpus) and I'd like to convert it to a matrix where a row is a document in the corpus and the columns are the corpus' vocabulary.</p>
<p>I can do this with <code>CountVectorizer</code> but it would require quite a lot of memory as I would need to convert each list into a string that in turn <code>CountVectorizer</code> would tokenize.</p>
<p>I think it's possible to do it with Pandas only but I'm not sure how.</p>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>corpus = [['a', 'b', 'c'],['a', 'a'],['b', 'c', 'c']]
</code></pre>
<p>expected result:</p>
<pre><code>| a | b | c |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 0 | 0 |
| 0 | 1 | 2 |
</code></pre>
| [
{
"answer_id": 74376135,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "collections.Counter"
},
{
"answer_id": 74376241,
"author": "dapetillo",
"author_id": 12481326,
"author_profile": "https://Stackoverflow.com/users/12481326",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ncorpus = pd.DataFrame(corpus).T\ncorpus_freq = corpus.apply(pd.Series.value_counts).T\ncorpus_freq = corpus_freq.fillna(0)\n"
},
{
"answer_id": 74376251,
"author": "Serge de Gosson de Varennes",
"author_id": 5363686,
"author_profile": "https://Stackoverflow.com/users/5363686",
"pm_score": 2,
"selected": false,
"text": "Set =[]\nfrom collections import Counter\nfor lst in corpus:\n r = dict(Counter(lst).most_common(3))\n Set.append(r)\n \npd.DataFrame(Set).fillna(0, downcast='infer')\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19239577/"
] |
74,375,768 | <p>In my Xamarin Forms project I have:</p>
<pre><code>[BroadcastReceiver(Permission = "RECEIVE_BOOT_COMPLETED",
Exported = true,
Enabled = true)]
[IntentFilter(new[] {Intent.ActionBootCompleted})]
public class GeofenceReceiver: BroadcastReceiver
</code></pre>
<p>I use it for GeofenceTransitionEnter and GeofenceTransitionExit events.
I also have ACCESS_FINE_LOCATION and ACCESS_BACKGROUND_LOCATION permissions.</p>
<p>But OnReceive method is not called on API 31. I have not this problem with lower APIs.</p>
<p><a href="https://stackoverflow.com/questions/70935464/android-12-targetsdkversion-31-challenges-broadcast-receiver-pending-intent-c">Android 12 targetSDKVersion 31 challenges (Broadcast Receiver, Pending Intent) Crash Issues</a> - doesn't work for me</p>
| [
{
"answer_id": 74376135,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "collections.Counter"
},
{
"answer_id": 74376241,
"author": "dapetillo",
"author_id": 12481326,
"author_profile": "https://Stackoverflow.com/users/12481326",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ncorpus = pd.DataFrame(corpus).T\ncorpus_freq = corpus.apply(pd.Series.value_counts).T\ncorpus_freq = corpus_freq.fillna(0)\n"
},
{
"answer_id": 74376251,
"author": "Serge de Gosson de Varennes",
"author_id": 5363686,
"author_profile": "https://Stackoverflow.com/users/5363686",
"pm_score": 2,
"selected": false,
"text": "Set =[]\nfrom collections import Counter\nfor lst in corpus:\n r = dict(Counter(lst).most_common(3))\n Set.append(r)\n \npd.DataFrame(Set).fillna(0, downcast='infer')\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16059485/"
] |
74,375,778 | <p>I am obtaining undesired results in python.</p>
<p>Goal: I want to assign the constant value to the respective element of the 2D matrix.
I have indey list of the row and colum</p>
<pre><code>idx_container_phi = [22, 19, 25, 23, 22, 21, 22, 30, 16, 12, 14] # row index
idx_container_theta = [22, 19, 10, 23, 22, 7, 22, 8, 16, 19, 11] # column index
thickness = 0.85
sphere_pixels = 36
</code></pre>
<p>What I have done:
(1) First I have initialized the 2D matrix with certain shape.</p>
<pre><code>matrix_thickness = np.array([ [0]*sphere_pixels for i in range(sphere_pixels)])
</code></pre>
<p>(2) I initialized for loop which excexutes till the range of the index list and assign the constant value.</p>
<pre><code>for j in range(len(idx_container_phi)):
matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] = matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] + thickness
</code></pre>
<p>However, while running the code, I got the matrix with null values in every element. How can I assign the constant value to the each respective index postion in the 2D matrix?</p>
<p>Desire Output: Matrix of the size 36 X 36. I want to assign the value of thickness (0.85) to the index position <code>[22, 22], [19, 19], [25, 10], [23, 23], [22, 22], [21, 7], [22, 22], [30, 8], [16, 16], [12, 19], [14, 11]</code>.</p>
<p>If any index comes two times, for ex. <code>[22, 22], [22, 22]</code>, then in this case, value of the <code>thickness (0.85)</code> should be added (0.85 + 0.85 = 1.70).</p>
| [
{
"answer_id": 74376219,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 2,
"selected": true,
"text": "idx_container_phi = [1, 7, 3, 4, 1] # row index\nidx_container_theta = [3, 5, 2, 4, 3] # column index\nthickness = 0.85\nsphere_pixels = 10\n\nmatrix_thickness = np.zeros(shape=(sphere_pixels, sphere_pixels))\n\nfor row, col in zip(idx_container_phi, idx_container_theta):\n matrix_thickness[row, col] += thickness\nprint(matrix_thickness)\n"
},
{
"answer_id": 74376604,
"author": "Urvesh",
"author_id": 17289097,
"author_profile": "https://Stackoverflow.com/users/17289097",
"pm_score": 0,
"selected": false,
"text": "dtype = int"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17289097/"
] |
74,375,816 | <p>I am trying to remove redundant rows in my parametrized tests. Redundant - I mean I repeat this kind of code all the time.</p>
<p>Here is example of my test:</p>
<pre><code>1 @pytest.mark.parametrize("field, violations", [
2 (None, [NULL_VIOLATION]),
3 (True, []),
4 (False, [])
5 ])
6 def test_validate_field(field: str, violations: [str]):
7 ...
</code></pre>
<p>As you can see, lines: 2,3,4 are simple test of annotation @NotNull in my Controller Class.<br />
Line 2 is <strong>bad path</strong> test and line 3,4 are <strong>happy path</strong>.</p>
<hr />
<p>I repeat those 3 lines in every test when I need to check @NotNull<br />
<strong>Is it possible to inline this somehow?</strong></p>
<hr />
<p>What I want to achieve is something similar to that pseudo code:</p>
<pre><code>1 @pytest.mark.parametrize("field, violations", [
2 check_not_null_constraint()
3 ])
4 def test_validate_field(field: str, violations: [str]):
5 ...
</code></pre>
<hr />
<p>I don't want to get rid of parametrized because instead of checking that not_null I am testing many other things like size etc. I am testing everything per parameter. So 1 test for 1 parameter in class.</p>
| [
{
"answer_id": 74380691,
"author": "picobit",
"author_id": 6030926,
"author_profile": "https://Stackoverflow.com/users/6030926",
"pm_score": 0,
"selected": false,
"text": "pytest_generate_tests"
},
{
"answer_id": 74462798,
"author": "Mariya Fetishcheva",
"author_id": 12380994,
"author_profile": "https://Stackoverflow.com/users/12380994",
"pm_score": 1,
"selected": false,
"text": "path_params = [(None, [NULL_VIOLATION]), (True, []), (False, [])]\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20212721/"
] |
74,375,887 | <p>I am new to python, may i know</p>
<p>Define a procedure that finds the index of the second instance of a string in a larger string.</p>
<pre><code>def find_second(findin, whattofind):
return
find_second('dance, dance, dance everyday', 'dance')
find_second('learning about data, surprisingly, requires a lot of data','data')
</code></pre>
| [
{
"answer_id": 74380691,
"author": "picobit",
"author_id": 6030926,
"author_profile": "https://Stackoverflow.com/users/6030926",
"pm_score": 0,
"selected": false,
"text": "pytest_generate_tests"
},
{
"answer_id": 74462798,
"author": "Mariya Fetishcheva",
"author_id": 12380994,
"author_profile": "https://Stackoverflow.com/users/12380994",
"pm_score": 1,
"selected": false,
"text": "path_params = [(None, [NULL_VIOLATION]), (True, []), (False, [])]\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459673/"
] |
74,375,922 | <p>Lets say we have a 12 tasks, we need to runn all of them with one condition: we can have only 3 tasks running simultaneously. So we can start only 3 tasks at the beggining, then wayt until one of them finishes and launch another one. I am using Asyncio with semafore for this purpose in the simple code below.</p>
<pre><code>import asyncio
import random
max_tasks = 12
sem = asyncio.Semaphore(3)
async def counter(n):
print(f'counter with argument {n} has been launched')
for i in range(n):
for j in range(n):
for k in range(n):
pass
await asyncio.sleep(1)
print(f'counter with argument {n} has FINISHED')
async def safe_calc(n):
async with sem:
await counter(n)
async def main():
tasks = [asyncio.ensure_future(safe_calc(random.randint(100, 600))) for _ in range(max_tasks)]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
</code></pre>
<p>but what if we have variable max_tasks dynamic, like it is another function or coroutine returnin number of tasks we have to do and during the main loop run we get this number changed and from this point we need to calculate more tasks in the loop?</p>
<p>And could you please explain what exactly does this line- "loop.run_until_complete(loop.shutdown_asyncgens())"</p>
| [
{
"answer_id": 74380691,
"author": "picobit",
"author_id": 6030926,
"author_profile": "https://Stackoverflow.com/users/6030926",
"pm_score": 0,
"selected": false,
"text": "pytest_generate_tests"
},
{
"answer_id": 74462798,
"author": "Mariya Fetishcheva",
"author_id": 12380994,
"author_profile": "https://Stackoverflow.com/users/12380994",
"pm_score": 1,
"selected": false,
"text": "path_params = [(None, [NULL_VIOLATION]), (True, []), (False, [])]\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426821/"
] |
74,375,976 | <p>im trying to make a search box with a magnifying glass icon that becomes blue when the input field is focused.</p>
<p>the MagnifyingGlass component inherits its color from its parent element.</p>
<pre><code>import styles from './Search.module.sass';
import { useState } from 'react';
import MagnifyingGlass from '../../icons/MagnifyingGlass';
const Search = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div className={styles.searchWrapper}>
<input
value={inputValue}
onChange={handleChange}
className={styles.searchInput}
type='text'
placeholder='Waar bent u naar opzoek?'
/>
<span> // needs to contain a className that results in the color to change
<MagnifyingGlass size='small' /> // inherits color from parent
</span>
</div>
);
};
export default Search;
</code></pre>
| [
{
"answer_id": 74376058,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "const Search = () => {\n \n\n const [inputValue, setInputValue] = useState('');\n \n const [show, toggle] = useState(false);\n \n const eventHandlers = useMemo(() => ({\n onFocus: () => toggle(true),\n onBlur: () => toggle(false),\n }), []);\n\n const handleChange = (e) => {\n setInputValue(e.target.value);\n \n };\n\n return (\n <div className={styles.searchWrapper}>\n <input\n value={inputValue}\n onChange={handleChange}\n className={styles.searchInput}\n type='text'\n placeholder='Waar bent u naar opzoek?'\n {...eventHandlers} \n />\n <span className={show ? 'your_class': ''}> // needs to contain a className that results in the color to change\n <MagnifyingGlass size='small' /> // inherits color from parent\n </span>\n </div>\n );\n};\nexport default Search;\n"
},
{
"answer_id": 74376086,
"author": "Boguz",
"author_id": 5509709,
"author_profile": "https://Stackoverflow.com/users/5509709",
"pm_score": 3,
"selected": true,
"text": ":focus-within"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74375976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20061501/"
] |
74,376,018 | <p>I am writing this code for simulation of earths magnetic field:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy
import pyvista as pv
ts = np.linspace(-8,8, 150)
t = np.linspace(-6,6, 150)
axis = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), ts]
aux = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), t]
def make_coil(pos, vertices):
coil = magpy.current.Line(
current = 100,
vertices = vertices,
position= pos,
style_color="green",
)
return coil
theta = np.sqrt(2)/2
r = 4
coil1 = make_coil((0,0,0), axis)
coil2 = make_coil((r*1,0,0), aux)
coil3 = make_coil((r*theta,r*theta,0), aux)
coil4 = make_coil((0,1*r,0), aux)
coil5 = make_coil((-r*theta,r*theta,0), aux)
coil6 = make_coil((-r*1,0,0), aux)
coil7 = make_coil((-r*theta,-r*theta,0), aux)
coil8 = make_coil((0,-r*1,0), aux)
coil9 = make_coil((r*theta,-r*theta,0), aux)
coil = coil1 + coil2 + coil3 + coil4 + coil5 + coil6 + coil7 + coil8 + coil9
coil.show()
grid = pv.UniformGrid(
dimensions=(41, 41, 41),
spacing=(2, 2, 2),
origin=(-40, -40, -40),
)
# compute B-field and add as data to grid
grid["B"] = coil.getB(grid.points)
# compute field lines
seed = pv.Disc(inner=1, outer=5.2, r_res=3, c_res=12)
strl = grid.streamlines_from_source(
seed,
vectors='B',
max_time=180,
initial_step_length=0.01,
integration_direction='both',
)
# create plotting scene
pl = pv.Plotter()
# add field lines and legend to scene
legend_args = {
'title': 'B [mT]',
'title_font_size': 20,
'color': 'black',
'position_y': 0.25,
'vertical': True,
}
# draw coils
magpy.show(coil, color="orange", canvas=pl, backend='pyvista')
# add streamlines
pl.add_mesh(
strl.tube(radius=.2),
cmap="bwr",
scalar_bar_args=legend_args,
)
# display scene
pl.camera.position=(160, 10, -10)
pl.set_background("white")
pl.show()
</code></pre>
<p>and I get this error message</p>
<pre><code>danieltran@eduroam-193-157-168-102 OneDrive-UniversitetetiOslo % /usr/local/bin/python3 "/Users/danieltran/Library/CloudStorage/OneDrive-UniversitetetiOslo/H22/FYS1120/Comp Essay/d
ouble_solenoids.py"
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/_vtk.py", line 547, in <module>
from vtk.vtkCommonKitPython import buffer_shared, vtkAbstractArray, vtkWeakReference
ModuleNotFoundError: No module named 'vtk'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/danieltran/Library/CloudStorage/OneDrive-UniversitetetiOslo/H22/FYS1120/Comp Essay/double_solenoids.py", line 4, in <module>
import pyvista as pv
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/__init__.py", line 12, in <module>
from pyvista.plotting import *
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/plotting/__init__.py", line 4, in <module>
from .charts import Chart2D, ChartMPL, ChartBox, ChartPie
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/plotting/charts.py", line 13, in <module>
from pyvista import _vtk
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/_vtk.py", line 549, in <module>
from vtk.vtkCommonCore import buffer_shared, vtkAbstractArray, vtkWeakReference
ModuleNotFoundError: No module named 'vtk'.
</code></pre>
| [
{
"answer_id": 74376058,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 0,
"selected": false,
"text": "const Search = () => {\n \n\n const [inputValue, setInputValue] = useState('');\n \n const [show, toggle] = useState(false);\n \n const eventHandlers = useMemo(() => ({\n onFocus: () => toggle(true),\n onBlur: () => toggle(false),\n }), []);\n\n const handleChange = (e) => {\n setInputValue(e.target.value);\n \n };\n\n return (\n <div className={styles.searchWrapper}>\n <input\n value={inputValue}\n onChange={handleChange}\n className={styles.searchInput}\n type='text'\n placeholder='Waar bent u naar opzoek?'\n {...eventHandlers} \n />\n <span className={show ? 'your_class': ''}> // needs to contain a className that results in the color to change\n <MagnifyingGlass size='small' /> // inherits color from parent\n </span>\n </div>\n );\n};\nexport default Search;\n"
},
{
"answer_id": 74376086,
"author": "Boguz",
"author_id": 5509709,
"author_profile": "https://Stackoverflow.com/users/5509709",
"pm_score": 3,
"selected": true,
"text": ":focus-within"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20275232/"
] |
74,376,039 | <p>My problem looks like this:</p>
<pre><code>data_example <-
c("Creditshelf Aktiengesellschaft / Key word(s): Forecast/Development of Sales\n\ncreditshelf Aktiengesellschaft",
"Swiss Life Holding AG / Key word(s): 9 Month figures\n\nSwiss Life increases fee income by 13%",
"tonies SE / Key word(s): Capital Increase\n\ntonies SE: tonies successfully places 12,000,000 new class A shares",
"init innovation in traffic systems SE / Key word(s): Contract/Incoming Orders\n\ninit innovation in traffic systems SEs")
strings_to_extract <-
c("Key word(s): Word1/Word2",
"Key word(s): Word1/Word2 Word3",
"Key word(s): Word1 Word2 Word3",
"Key word(s): Word1/Word2/Word3",
"Key word(s): Number Word1/Word2",
"Key word(s): Number Word1 Word2",
"Key word(s): Word1 Number Word2")
</code></pre>
<p>There will always be a whitespace or a "/" to separate them.
My try looks like this:</p>
<pre><code>str_extract(data, "Key word[[:punct:]]{1}s[[:punct:]]{2} [[:alpha:]]{1,}|Key word[[:punct:]]{1}s[[:punct:]]{2} [[:alpha:]]{1,}[[:punct:]]{1,}[[:alpha:]]{1,}Key word[[:punct:]]{1}s[[:punct:]]{2} [[:alpha:]]{1,}[[:punct:]]{1,}[[:alpha:]]{1,}[[:punct:]]{1,}[[:alpha:]]{1,}")
</code></pre>
<p>I mean I capture a good part of theme, but I think its too complicated.
Could somebody give me a advice how to do it better?</p>
<p>Thx amd KR</p>
| [
{
"answer_id": 74376131,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "str_extract(data, \"Key word\\\\(s\\\\):\\\\s*\\\\w+(?:\\\\W+\\w+){1,2}\")\n"
},
{
"answer_id": 74376322,
"author": "VvdL",
"author_id": 15589010,
"author_profile": "https://Stackoverflow.com/users/15589010",
"pm_score": 1,
"selected": false,
"text": "\\n"
},
{
"answer_id": 74377590,
"author": "Aivis B",
"author_id": 15401975,
"author_profile": "https://Stackoverflow.com/users/15401975",
"pm_score": 0,
"selected": false,
"text": "data_example <-\n c(\"Creditshelf Aktiengesellschaft / Key word(s): Forecast/Development of Sales\\n\\ncreditshelf Aktiengesellschaft\",\n \"Swiss Life Holding AG / Key word(s): 9 Month figures\\n\\nSwiss Life increases fee income by 13%\",\n \"tonies SE / Key word(s): Capital Increase\\n\\ntonies SE: tonies successfully places 12,000,000 new class A shares\",\n \"init innovation in traffic systems SE / Key word(s): Contract/Incoming Orders\\n\\ninit innovation in traffic systems SEs\")\n\nstringr::str_extract(string = data_example,\n pattern = '(?<=Key word\\\\(s\\\\): )[\\\\s\\\\S]+')\n\n#> [1] \"Forecast/Development of Sales\\n\\ncreditshelf Aktiengesellschaft\" \n#> [2] \"9 Month figures\\n\\nSwiss Life increases fee income by 13%\" \n#> [3] \"Capital Increase\\n\\ntonies SE: tonies successfully places 12,000,000 new class A shares\"\n#> [4] \"Contract/Incoming Orders\\n\\ninit innovation in traffic systems SEs\"\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7766771/"
] |
74,376,057 | <p>I need to clone a project of my company on my local machine.</p>
<p>Problem: There is a module required in the main <strong>composer.json</strong> from our old agency which does not exist anymore, so I don't have the access keys needed to download it, BUT I have the latest code of that module.</p>
<p>The composer.json of that module says its name is "randomagency/import", so I added the code at <code>vendor/randomagency/import</code>. Then I removed the module from the main composer.json.</p>
<p>But I get this error:</p>
<pre><code>Class 'RandomAgency\ProcessPipelines\Helper\Condition\AbstractCondition' not found#0 /var/www/company/src/vendor/composer/ClassLoader.php(444): include()
#1 /var/www/company/src/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile()
#2 [internal function]: Composer\Autoload\ClassLoader->loadClass()
#3 [internal function]: spl_autoload_call()
</code></pre>
<p>My colleague told me that I need to add the module in the main composer.json under the <a href="https://getcomposer.org/doc/04-schema.md#autoload" rel="nofollow noreferrer">autoload</a> section, but Im not sure how exactly it works.</p>
<hr />
<p>The best approach to solve it would be to create a new composer package and replace the agency URL in composer.json with my own, but I need a quick & dirty method for now.</p>
| [
{
"answer_id": 74377053,
"author": "Black",
"author_id": 4684797,
"author_profile": "https://Stackoverflow.com/users/4684797",
"pm_score": 0,
"selected": false,
"text": "\"autoload\": {\n \"psr-4\": {\n \"RandomAgency\\\\Import\\\\\": \"vendor/random-agency/import\"\n },\n"
},
{
"answer_id": 74408931,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 2,
"selected": true,
"text": "vendor-dir"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4684797/"
] |
74,376,061 | <p>The section I am doing is just 6 cards, 3 cards in a row of 2. When the screen goes to small (mobile phone size) I want each card just to be on their own row. Each card showing one by one as the user scrolls.</p>
<p>It functions this way when I resize the screen however, when I go to google tools, it does not show my desired outcome.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
padding: 4rem;
background-color: #F8F8FF;
border: 4px black;
colour: red;
}
.card {
background-color: #ddf;
padding: 30px;
margin: 20px;
transition: 0.40s;
}
.card:hover {
transform: scale(1.05);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<div class="container ">
<h1 class="display-4">My Projects/Work</h1>
<div class="row g-3">
<div class="col-12 col-md-6 col-lg-4">
<div class="card" id="proj1">
<img src="https://via.placeholder.com/300x200" class="card-img-top" alt="project_1" />
<div class="card-body">
<h5 class="card-title">Blog Project</h5>
<p class="card-text">
A simple blog website which I made from scratch using html , css and javascript for the frontend.The backend was done with Django and SQL.
</p>
<a href="#" class="btn btn-primary">Click to see</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4">
<div class="card" id="proj2">
<img src="https://via.placeholder.com/300x200" class="card-img-top" alt="project_2" />
<div class="card-body">
<h5 class="card-title">Social media clone </h5>
<p class="card-text">
A social media clone with all the main features of a social media site such as Facebook.In order to achieve this I used Django and React.
</p>
<a href="#" class="btn btn-primary">Click to see</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4">
<div class="card" id="proj3">
<img src="https://via.placeholder.com/300x200" class="card-img-top" alt="project_3" />
<div class="card-body">
<h5 class="card-title">E-commence site</h5>
<p class="card-text">
This is a website I build for a small tech company in my local area that specialized in databases .
</p>
<a href="#" class="btn btn-primary">Click to see</a>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74377053,
"author": "Black",
"author_id": 4684797,
"author_profile": "https://Stackoverflow.com/users/4684797",
"pm_score": 0,
"selected": false,
"text": "\"autoload\": {\n \"psr-4\": {\n \"RandomAgency\\\\Import\\\\\": \"vendor/random-agency/import\"\n },\n"
},
{
"answer_id": 74408931,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 2,
"selected": true,
"text": "vendor-dir"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16644505/"
] |
74,376,091 | <p>I am using a nested loop, and I want my inner loop to start from the index of the outer loop.</p>
<p>How can I implement this?</p>
<p>I want <code>j</code> to run from <code>i</code> till the end of the array.</p>
<pre><code>nums = [2,7,11,15]
for i in nums:
for j in nums:
print(j)
</code></pre>
| [
{
"answer_id": 74376121,
"author": "Piotr Żak",
"author_id": 9455902,
"author_profile": "https://Stackoverflow.com/users/9455902",
"pm_score": 1,
"selected": false,
"text": "nums = [2,7,11,15]\n\nfor i, val in enumerate(nums):\n for j in nums[i:]:\n print(j)\n"
},
{
"answer_id": 74376125,
"author": "rockzxm",
"author_id": 19598454,
"author_profile": "https://Stackoverflow.com/users/19598454",
"pm_score": 2,
"selected": true,
"text": "nums = [2, 7, 11, 15]\n\nfor i in range(len(nums)):\n for j in range(i, len(nums)):\n print(j)\n"
},
{
"answer_id": 74376210,
"author": "Claude Shannon",
"author_id": 20102259,
"author_profile": "https://Stackoverflow.com/users/20102259",
"pm_score": 0,
"selected": false,
"text": "for i in nums:\n for j in nums[nums.index(i):]:\n print(j)\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18003088/"
] |
74,376,103 | <p>I get a json file from a server in my Unity script. The json file looks like this.</p>
<pre><code>{
"drones": [
[
0.0,
0.0,
0.0,
1.0,
0.0,
],
[
0.0,
0.0,
1.0,
1.0,
0.0,
],
[
0.0,
0.0,
1.0,
0.0,
0.0,
]]
}
</code></pre>
<p>My method reads the data stream and converts it to a json format</p>
<pre class="lang-c# prettyprint-override"><code> String incoming_data = reader.ReadLine();
if(incoming_data != null)
{
JObject json = JObject.Parse(incoming_data);
}
</code></pre>
<p>But now I want to store the values of "drones" in a 2D int array. How would I do that?</p>
<p>Is there already a parser that can convert the values? Or am I already using JObject.Parse(incoming_data) incorrectly?</p>
| [
{
"answer_id": 74376260,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 1,
"selected": true,
"text": "int[][] drones= JObject.Parse(incoming_data)[\"drones\"].ToObject<int[][]>();\n"
},
{
"answer_id": 74376268,
"author": "Palle Due",
"author_id": 5516339,
"author_profile": "https://Stackoverflow.com/users/5516339",
"pm_score": -1,
"selected": false,
"text": "drones"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459630/"
] |
74,376,112 | <p>I'm creating a blog with ReactJS. I have a data component that only contains my data for each articles. I'm able to show all my list of articles on my blog page. The problems comes when I click on an article. I'm able to get the ID in the URL and other params and show it in my article.</p>
<p>The problem: I'd like to not pass all the params into the URL...</p>
<p>I just want to pass ID into the URL, and say to my app:</p>
<p>Get all the values of the row that contain this ID from this data file.</p>
<p>Here the code I tried to fix it (it show a blank page):</p>
<pre><code>import React, { useEffect, useState } from 'react'
import imgBien1 from '../../images/imgBien1.JPG'
import { ColumnSection, Section, SectionInterne, Column2, ContentWrapper2, Img, Column1,ContentWrapper, TopLine, Heading, Subtitle } from './stockUnique'
import {useParams} from 'react-router-dom';
import { posts } from '../Data/data'
const StockUnique = () => {
const { id } = useParams();
const [blog, setBlog] = useState(null);
useEffect(() => {
let blog = posts.find((blog) => blog.id === parseInt(id));
if (blog) {
setBlog(blog);
}
}, []);
return (
<Section >
<ColumnSection>
<SectionInterne>
<Column2>
<ContentWrapper2>
<Img src={imgBien1} alt='ok' />
</ContentWrapper2>
</Column2>
<Column1>
<ContentWrapper>
<TopLine>{id}</TopLine>
<Heading>{blog.title}</Heading>
<Subtitle>{blog.content}</Subtitle>
</ContentWrapper>
</Column1>
</SectionInterne>
</ColumnSection>
</Section>
)
}
export default StockUnique
</code></pre>
<p>My data list:</p>
<pre><code>export const posts = [
{ id: 1, title: 'Hello World', content: 'Mon article 1', typeDeBien: "maison" },
{ id: 2, title: 'Bravo', content: 'Mon article2', typeDeBien: "terrain" },
{ id: 3, title: 'Charlie', content: 'Mon article 3', typeDeBien: "appartement" }
];
</code></pre>
<p>edit: Navigation code:</p>
<pre><code>import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
import React from 'react'
import StockPage from './pages/stock';
import UniqueStockPage from './pages/unique'
const App = () => {
return (
<Router>
<Routes>
<Route path="/stock" element={<StockPage/>} exact />
<Route
path="/unique/:id"
// path="/unique/:id/:title/:content"
element={<UniqueStockPage/>} exact
/>
</Routes>
</Router>
)
}
export default App;
</code></pre>
| [
{
"answer_id": 74376163,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n if(id){\n let blog = posts.find((blog) => blog.id === parseInt(id));\n if (blog) {\n setBlog(blog);\n }\n }\n}, [id]);\n"
},
{
"answer_id": 74377879,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 1,
"selected": true,
"text": "<Route path=\"/unique/:id\" element={<UniqueStockPage />} />\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17026389/"
] |
74,376,115 | <p>Im in east 8+ timezone, and this expression return nil on my device.</p>
<p>I know it returned a value counting my timezone infomation. But, Why? I don't get it. How this function implemented and what puporse of it?
Thanks.</p>
| [
{
"answer_id": 74376163,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n if(id){\n let blog = posts.find((blog) => blog.id === parseInt(id));\n if (blog) {\n setBlog(blog);\n }\n }\n}, [id]);\n"
},
{
"answer_id": 74377879,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 1,
"selected": true,
"text": "<Route path=\"/unique/:id\" element={<UniqueStockPage />} />\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1773317/"
] |
74,376,134 | <p>I have txt file with 7 column...I want to mutiply a 3rd column with a constant number keeping all other column same and then output the file containing all the columns. Anyone can help?</p>
<pre><code>1 2 1
2 2 1
3 2 1
</code></pre>
<p>mutiplying column 3 with "14" the output should be like</p>
<pre><code>1 2 14
2 2 14
3 2 14
</code></pre>
| [
{
"answer_id": 74376163,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n if(id){\n let blog = posts.find((blog) => blog.id === parseInt(id));\n if (blog) {\n setBlog(blog);\n }\n }\n}, [id]);\n"
},
{
"answer_id": 74377879,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 1,
"selected": true,
"text": "<Route path=\"/unique/:id\" element={<UniqueStockPage />} />\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386542/"
] |
74,376,138 | <p>I have a date in format <code>dd/mm/yyyy</code>. I want to subtract one month from it.</p>
<p>I am using this code but the output is "09/10/2020" I don't know why my code does the subtraction of the year -2 also.</p>
<p>This is my request</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
FORMAT(CONVERT (DATE, DATEADD(MONTH, -1, CONVERT(char(9), GETDATE()))), 'dd/MM/yyyy')
</code></pre>
| [
{
"answer_id": 74376163,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n if(id){\n let blog = posts.find((blog) => blog.id === parseInt(id));\n if (blog) {\n setBlog(blog);\n }\n }\n}, [id]);\n"
},
{
"answer_id": 74377879,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 1,
"selected": true,
"text": "<Route path=\"/unique/:id\" element={<UniqueStockPage />} />\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16976676/"
] |
74,376,164 | <p>I am trying to add an array element inside the object but if I type text all the text boxes show the text and the text is added only to the first element . even if i added text in second and third text box it is addding into the first tag list plz help me how to fix it</p>
<pre><code>import React, { useState } from "react";
export default function App() {
const synonym = [
{ id: 1, keyword: "Caffeine", synonyms: ["Coffee", "Espresso"] },
{ id: 2, keyword: "Drowsiness", synonyms: ["Sleeping", "Fatigue"] },
{ id: 3, keyword: "Drowsiness", synonyms: [""] }
];
const [mysynonyms, setSynonyms] = useState(() => synonym);
const [addTagValue, setAddTagValue] = useState([]);
const handleChange = (e) => {
setAddTagValue(e.target.value);
};
const handleClick = () => {
setSynonyms((prevValue) => {
return prevValue.map((item, itemIndex) => {
if (itemIndex === 0) {
return { item, synonyms: [...item.synonyms, addTagValue] };
} else {
return item;
}
});
});
setAddTagValue("");
};
return (
<div className="App">
{mysynonyms.map((item, cid) => {
return (
<>
<p>{item.keyword}</p>
{item.synonyms.map((item, cid) => (
<span
style={{ border: "1px solid red", padding: "1px 1px 5px 7px" }}
>
{item} x
</span>
))}
<div>
<input
value={addTagValue}
className="form-control bg-color2 text-color7 border-end-0 fs-14 fw-bold"
type="text"
onChange={handleChange}
/>
<button onClick={handleClick}>add tag</button>
</div>
</>
);
})}
</div>
);
}
</code></pre>
| [
{
"answer_id": 74376373,
"author": "Bhavin Parghi",
"author_id": 6148640,
"author_profile": "https://Stackoverflow.com/users/6148640",
"pm_score": 0,
"selected": false,
"text": "<button onClick={() => handleClick(cid)}>add tag</button>\n"
},
{
"answer_id": 74376450,
"author": "Bikas Lin",
"author_id": 17582798,
"author_profile": "https://Stackoverflow.com/users/17582798",
"pm_score": 1,
"selected": false,
"text": "App.js"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9994689/"
] |
74,376,174 | <p>I have a list like this:</p>
<pre><code>test = ["Similar to Stxbp2: Syntaxin-binding protein 2 (Mus musculus)", "Protein of unknown function", "Similar to rab18b: Ras-related protein Rab-18-B (Danio rerio)", "Protein of unknown function", "Protein of unknown function"]
</code></pre>
<p>This object is, in actuality, a lot longer than this, but just for a simplified example:
My goal is to loop through <code>test</code> and edit it to where any value starting with "Similar to" will return the gene name proceeding directly after (e.g., for this example I'd like to replace the items in the list matching this beginning with "Stxb2" and "rab18b", respectively), which I presume would require specifying to start at character 12 and end when it reaches a colon. When a value includes "Protein of unknown function", I want it to return "Unknown". Thus, the output would be:</p>
<pre><code>["Stxbp2", "Unknown", "rab18b", "Unknown", "Unknown"]
</code></pre>
<p>I know this probably requires a for loop with if statements to match each condition, but am pretty lost in how to proceed from there to achieve the result I'm looking for.</p>
| [
{
"answer_id": 74376242,
"author": "It_is_Chris",
"author_id": 9177877,
"author_profile": "https://Stackoverflow.com/users/9177877",
"pm_score": 2,
"selected": false,
"text": "str.startswith"
},
{
"answer_id": 74376288,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "test = [\"Similar to Stxbp2: Syntaxin-binding protein 2 (Mus musculus)\", \"Protein of unknown function\", \"Similar to rab18b: Ras-related protein Rab-18-B (Danio rerio)\", \"Protein of unknown function\", \"Protein of unknown function\"]\nd = {'Similar to ': '', 'Protein of unknown function': 'unknown'}\nregex = r'\\b(?:' + r'|'.join(d.keys()) + r')\\b'\noutput = [re.sub(regex, lambda m: d[m.group()], x).split(':')[0] for x in test]\nprint(output) # ['Stxbp2', 'unknown', 'rab18b', 'unknown', 'unknown']\n"
},
{
"answer_id": 74376362,
"author": "Christian Sloper",
"author_id": 8111755,
"author_profile": "https://Stackoverflow.com/users/8111755",
"pm_score": 3,
"selected": true,
"text": "def parse(x):\n if x.startswith(\"Similar to\"):\n return x.split(\":\")[0].split()[-1]\n if x.startswith(\"Protein of unknown function\"):\n return \"Unknown\"\n raise ValueError(f\"Unknown value: {x}\")\n\nprint([parse(i) for i in test ])\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512945/"
] |
74,376,188 | <p>I am attempting to use the FPDF (<a href="http://www.fpdf.org/" rel="nofollow noreferrer">http://www.fpdf.org/</a>) PHP addon for my website that uses Laravel. I want to be able to dynamically create a PDF.</p>
<p>I have stored the libraries' files in the folder: '/public/vendor'.
This is what I have so far:</p>
<pre><code>require $_SERVER['DOCUMENT_ROOT'] . '/vendor/fpdf/fpdf.php';
</code></pre>
<p>which works fine. However when I try to use the FPDF class using:</p>
<pre><code> $pdf = new FPDF('P', 'pt', array(500,233));
</code></pre>
<p>I get the error: Class "'App\Console\Commands\FPDF' not found"</p>
<p>How can I fix this to use the library. I do not have access to command line so I have to manually import any folders or files.</p>
<p>Any help is greatly appreciated.</p>
<p>Update:: I do not have any access to the console so i cannot use composer. Any way to still do this?</p>
| [
{
"answer_id": 74376426,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 0,
"selected": false,
"text": " $pdf = new \\Fpdf\\Fpdf('P', 'pt', array(500,233));\n"
},
{
"answer_id": 74376479,
"author": "Richard Leishman",
"author_id": 17473064,
"author_profile": "https://Stackoverflow.com/users/17473064",
"pm_score": 2,
"selected": true,
"text": "composer install fpdf/fpdf"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13544299/"
] |
74,376,191 | <p>I need to update a MySql database from inside a JS function within a WordPress Woocommerce page. I'm using Ajax to do this. The following code works fine as a stand-alone code but when I put it into the WordPress page (on my localhost) it throws an error 500. Also I put the required data (which will eventually be a variable) onto the end of the url (?test=14230) because I couldn't get it to send the data when using the data: line in the Ajax.</p>
<p>Here's the Ajax:</p>
<pre><code>function db()
{
$.ajax({
url: 'update_db.php?test=14230',
type: 'post',
data: 0,
success: function(output)
{
alert('Success, server says '+output);
}, error: function()
{
alert('Something went wrong.');
}
});
}
</code></pre>
<p>Here's the update_db.php:</p>
<pre><code><?php
if(isset($_GET['test']) ){
$id = $_GET['test'];
}
include 'database-handler.php';
$sql = "UPDATE db_name SET column = 'Some Value' WHERE id = $id";
if(mysqli_query($conn, $sql)){
//echo ('<p>'."Success.".'</p>');
} else {
//echo ('<p>'."Something went wrong. $sql. " . mysqli_error($conn).'</p>');
}
mysqli_close($conn);
?>
</code></pre>
<p>So I'm just wondering why this works as a stand-alone code but not when it's inside WordPress?</p>
<p>Edit: Here is the error log:</p>
<p>[Wed Nov 09 15:16:47.543162 2022] [php:error] [pid 4564:tid 1828] [client ::1:5888] PHP Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, null given in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php:17\nStack trace:\n#0 C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php(17): mysqli_query(NULL, 'UPDATE new_card...')\n#1 {main}\n thrown in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php on line 17, referer: http://localhost/my-sites/wowcard/product/polka-dot-brush-strokes-two-photo-birthday-card-purple/?card=complete&id=14230</p>
| [
{
"answer_id": 74376545,
"author": "Richard Leishman",
"author_id": 17473064,
"author_profile": "https://Stackoverflow.com/users/17473064",
"pm_score": -1,
"selected": false,
"text": "global $wpdb;\n$results = $wpdb->query($wpdb->prepare( 'UPDATE db_name SET column = 'Some Value' WHERE id = %d' , $id ));\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18494930/"
] |
74,376,221 | <p>I have a file <code>data.php</code> looks like the below:</p>
<pre><code>$first_data = 0;
$second_data = 0;
$third_data = 0;
</code></pre>
<p>I have three HTML checkbox on frontend and I would like to store the value into <code>data.php</code>.</p>
<p>( The value is <code>1</code> if it's checked )</p>
<p>In <code>process.php</code>, I use <code>$_POST['data_value']</code> and store the value into the variables which looks like the below:</p>
<pre><code>$process_first_data = isset ( $_POST['first_checkbox'] ) ? 1 : 0;
$process_second_data = isset ( $_POST['second_checkbox'] ) ? 1 : 0;
$process_third_data = isset ( $_POST['third_checkbox'] ) ? 1 : 0;
</code></pre>
<p>And I use this <a href="https://stackoverflow.com/questions/3574999/replacing-file-content-in-php/3575012#3575012">method</a> with <code>preg_replace</code> to replace the value in <code>data.php</code> from <code>process.php</code> which looks like the below:</p>
<pre><code>$find_first_data = '/\$first_data = \d;/';
$find_second_data = '/\$second_data = \d;/';
$find_third_data = '/\$third_data = \d;/';
$replace_first_data = '$first_data = ' . $process_first_data . ';';
$replace_second_data = '$second_data = ' . $process_second_data . ';';
$replace_third_data = '$third_data = ' . $process_third_data . ';';
$dir = 'path/to/file';
$file_content = file_get_contents ( $dir );
file_put_contents ( $dir, preg_replace ( $find_first_data, $replace_first_data, $file_content ) );
file_put_contents ( $dir, preg_replace ( $find_second_data, $replace_second_data, $file_content ) );
file_put_contents ( $dir, preg_replace ( $find_third_data, $replace_third_data, $file_content ) );
</code></pre>
<p>But now the problem is only the last <code>file_put_contents</code> is working. For example, now only the third one is working. And if I remove the third one, there are two left, then the second one is working only. And if I remove the second and the third one, there is one left, then the first one is working only.</p>
<p>There is no error, sorry for the long story because I want to make it in detail. May I know why only the last <code>file_put_contents</code> is working in this case?</p>
| [
{
"answer_id": 74376348,
"author": "leighboz",
"author_id": 1807307,
"author_profile": "https://Stackoverflow.com/users/1807307",
"pm_score": 0,
"selected": false,
"text": "FILE_APPEND"
},
{
"answer_id": 74376460,
"author": "IMSoP",
"author_id": 157957,
"author_profile": "https://Stackoverflow.com/users/157957",
"pm_score": 1,
"selected": true,
"text": "$dir = 'path/to/file';\n$file_content = file_get_contents ( $dir );\n\nfile_put_contents ( $dir, preg_replace ( $find_first_data, $replace_first_data, $file_content ) );\nfile_put_contents ( $dir, preg_replace ( $find_second_data, $replace_second_data, $file_content ) );\nfile_put_contents ( $dir, preg_replace ( $find_third_data, $replace_third_data, $file_content ) );\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20454874/"
] |
74,376,254 | <p>In my XML file [studentinfo.xml] some tags have namespace prefixes, is there a way to loop through the xml file and parse tag content [all sibling and child tags] without defining the URI/URL for namespace?</p>
<p>If you have another way of parsing the xml file not using pandas I am open to any and all solutions.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<stu:StudentBreakdown>
<stu:Studentdata>
<stu:StudentScreening>
<st:name>Sam Davies</st:name>
<st:age>15</st:age>
<st:hair>Black</st:hair>
<st:eyes>Blue</st:eyes>
<st:grade>10</st:grade>
<st:teacher>Draco Malfoy</st:teacher>
<st:dorm>Innovation Hall</st:dorm>
</stu:StudentScreening>
<stu:StudentScreening>
<st:name>Cassie Stone</st:name>
<st:age>14</st:age>
<st:hair>Science</st:hair>
<st:grade>9</st:grade>
<st:teacher>Luna Lovegood</st:teacher>
</stu:StudentScreening>
<stu:StudentScreening>
<st:name>Derek Brandon</st:name>
<st:age>17</st:age>
<st:eyes>green</st:eyes>
<st:teacher>Ron Weasley</st:teacher>
<st:dorm>Hogtie Manor</st:dorm>
</stu:StudentScreening>
</stu:Studentdata>
</stu:StudentBreakdown>
</code></pre>
<p>below is my code:</p>
<pre><code>import pandas as pd
from bs4 import BeautifulSoup
with open('studentinfo.xml', 'r') as f:
file = f.read()
def parse_xml(file):
soup = BeautifulSoup(file, 'xml')
df1 = pd.DataFrame(columns=['StudentName', 'Age', 'Hair', 'Eyes', 'Grade', 'Teacher', 'Dorm'])
all_items = soup.find_all('info')
items_length = len(all_items)
for index, info in enumerate(all_items):
StudentName = info.find('<st:name>').text
Age = info.find('<st:age>').text
Hair = info.find('<st:hair>').text
Eyes = info.find('<st:eyes>').text
Grade = info.find('<st:grade>').text
Teacher = info.find('<st:teacher>').text
Dorm = info.find('<st:dorm>').text
row = {
'StudentName': StudentName,
'Age': Age,
'Hair': Hair,
'Eyes': Eyes,
'Grade': Grade,
'Teacher': Teacher,
'Dorm': Dorm
}
df1 = df1.append(row, ingore_index=True)
print(f'Appending row %s of %s' %(index+1, items_length))
return df1
</code></pre>
<p>Desired Output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;"></th>
<th style="text-align: left;">Name</th>
<th style="text-align: left;">age</th>
<th style="text-align: left;">hair</th>
<th style="text-align: left;">eyes</th>
<th style="text-align: left;">grade</th>
<th style="text-align: left;">teacher</th>
<th style="text-align: left;">dorm</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">0</td>
<td style="text-align: left;">Sam Davies</td>
<td style="text-align: left;">15</td>
<td style="text-align: left;">Black</td>
<td style="text-align: left;">Blue</td>
<td style="text-align: left;">10</td>
<td style="text-align: left;">Draco Malfoy</td>
<td style="text-align: left;">Innovation Hall</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">Cassie Stone</td>
<td style="text-align: left;">14</td>
<td style="text-align: left;">Science</td>
<td style="text-align: left;">N/A</td>
<td style="text-align: left;">9</td>
<td style="text-align: left;">Luna Lovegood</td>
<td style="text-align: left;">N/A</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Derek Brandon</td>
<td style="text-align: left;">17</td>
<td style="text-align: left;">N/A</td>
<td style="text-align: left;">green</td>
<td style="text-align: left;">N/A</td>
<td style="text-align: left;">Ron Weasley</td>
<td style="text-align: left;">Hogtie Manor</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74376348,
"author": "leighboz",
"author_id": 1807307,
"author_profile": "https://Stackoverflow.com/users/1807307",
"pm_score": 0,
"selected": false,
"text": "FILE_APPEND"
},
{
"answer_id": 74376460,
"author": "IMSoP",
"author_id": 157957,
"author_profile": "https://Stackoverflow.com/users/157957",
"pm_score": 1,
"selected": true,
"text": "$dir = 'path/to/file';\n$file_content = file_get_contents ( $dir );\n\nfile_put_contents ( $dir, preg_replace ( $find_first_data, $replace_first_data, $file_content ) );\nfile_put_contents ( $dir, preg_replace ( $find_second_data, $replace_second_data, $file_content ) );\nfile_put_contents ( $dir, preg_replace ( $find_third_data, $replace_third_data, $file_content ) );\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18696224/"
] |
74,376,271 | <p>I am trying to create a circle css and add some more changes to it,</p>
<p>Here is my code for circles</p>
<pre><code>.container {
display: flex;
flex-wrap: nowrap;
width: 200px;
height: 50px;
}
.holder {
margin-right: 5px;
width: 30px;
height: 30px;
border-radius: 50%;
}
.h1 {
background: blue;
}
.h2 {
background: red;
}
.h3 {
background: green;
}
.h4 {
background: grey;
}
</code></pre>
<p>and the html code</p>
<pre><code><div class="container">
<div class="holder h1"></div>
<div class="holder h2"></div>
<div class="holder h3"></div>
<div class="holder h4"></div>
</div>
</code></pre>
<p>works well for the circles, but my end goal is to do this</p>
<p><a href="https://prnt.sc/KCA2zWq435oK" rel="nofollow noreferrer">https://prnt.sc/KCA2zWq435oK</a></p>
<p>how can i do this, any help will be much appreciated</p>
<p>regards</p>
| [
{
"answer_id": 74376630,
"author": "Farbod Shabani",
"author_id": 14712252,
"author_profile": "https://Stackoverflow.com/users/14712252",
"pm_score": 2,
"selected": true,
"text": ".container {\n display: flex;\n flex-wrap: nowrap;\n width: 200px;\n height: 50px;\n}\n\n.holder {\n margin-right: 5px;\n width: 30px;\n height: 30px;\n border-radius: 50%;\n}\n\n.h1 {\n background: blue;\n}\n\n.h2 {\n background: red;\n}\n\n.h3 {\n background: green;\n}\n\n.h4 {\n background: grey;\n}\n\nth {\n writing-mode: vertical-rl;\n min-width: 30px;\n transform: rotate(180deg);\n text-transform: capitalize;\n}\n\ntd {\n min-width: 30px;\n height: 30px;\n}"
},
{
"answer_id": 74379277,
"author": "A Haworth",
"author_id": 10867454,
"author_profile": "https://Stackoverflow.com/users/10867454",
"pm_score": 0,
"selected": false,
"text": "thead>tr>th {\n writing-mode: vertical-lr;\n transform: rotate(180deg);\n text-align: left;\n}\n\ntbody>tr>td {\n width: 50px;\n height: 50px;\n --bg: gray;\n background-image: radial-gradient(circle, var(--bg) 0 70%, transparent 70% 100%);\n background-size: 70% 70%;\n background-repeat: no-repeat;\n background-position: center center;\n}\n\ntbody>tr>td:last-child {\n width: 400px;\n --bg: transparent;\n}\n\n.gold {\n --bg: gold;\n}\n\n.green {\n --bg: green;\n}\n\n.red {\n --bg: red;\n}"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19958310/"
] |
74,376,312 | <p>I'm getting this error when trying to build a React native App (npm run android)</p>
<p>error: package com.facebook.react.modules.storage does not exist
import com.facebook.react.modules.storage.ReactDatabaseSupplier;</p>
<p>error: package com.facebook.react.modules.storage does not exist
com.facebook.react.modules.storage.ReactDatabaseSupplier.getInstance(getApplicationContext()).setMaximumSize(size);</p>
<p>React Native 63</p>
<p>I've already tried to remove node_modules and install everything again but nothing works at the moment</p>
| [
{
"answer_id": 74462077,
"author": "amirhosein",
"author_id": 7858922,
"author_profile": "https://Stackoverflow.com/users/7858922",
"pm_score": 0,
"selected": false,
"text": "android/build.gradle"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14914588/"
] |
74,376,313 | <p>this is what I have:</p>
<p><code>"de-de": "This is a description for Process\r\nHere is no line break"</code></p>
<p>I want to replace the \r\n with an <code><br></code> tag</p>
<p>This is what I am trying:</p>
<pre><code><p
v-if="process.description"
class="description"
v-html="process.description.replace('\r\n', '<br >')"
>
</p>
</code></pre>
<p>This works, but if I use <code>v-html</code> , there are security warnings in case of XSS vulnerabilities. So v-html isn't the solution ether.</p>
<p>Someone an idea?</p>
| [
{
"answer_id": 74376466,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre>"
},
{
"answer_id": 74378141,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "description"
},
{
"answer_id": 74378186,
"author": "Yogi",
"author_id": 943435,
"author_profile": "https://Stackoverflow.com/users/943435",
"pm_score": 1,
"selected": false,
"text": "v-for"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18456799/"
] |
74,376,338 | <p>I am a Beginner in Python and i made this login system with number of tries. I think it can be simplified Can anyone help?</p>
<pre><code>a=int(input("Enter the Password: "))
i=5
if a==1234:
print("ACCESS GRANTED")
while not a==1234:
print(f"INVALID PASSWORD ( {i} times left)")
a=int(input("Enter the Password: "))
i-=1
if a==1234:
print("ACCESS GRANTED")
if i==0:
print("Console has been locked")
break
</code></pre>
<p>I tried it to change the number of print("ACCESS GRANTED") but I dont get how to without doing it wrong.</p>
| [
{
"answer_id": 74376466,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre>"
},
{
"answer_id": 74378141,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 1,
"selected": false,
"text": "description"
},
{
"answer_id": 74378186,
"author": "Yogi",
"author_id": 943435,
"author_profile": "https://Stackoverflow.com/users/943435",
"pm_score": 1,
"selected": false,
"text": "v-for"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459835/"
] |
74,376,357 | <p>I'm new to these wanderings, sorry if it's a stupid question. but can they enlighten me what what's doing there?</p>
<pre><code>char *ft_strchr(char *s, int c)
{
int i;
i = 0;
if (!s)
return (0);
if (c == '\0')
return ((char *)&s[ft_strlen(s)]); // THIS LINE
while (s[i] != '\0')
{
if (s[i] == (char) c)
return ((char *)&s[i]); // THIS LINE
i++;
}
return (0);
}
</code></pre>
<p>I know this is being performed a cast to that variable but I had not yet come apart with this & there in the middle. and to test this function if I take it out of there... it crash.</p>
<p>Someone help me please???</p>
<p>the function is working properly it finds the first occurrence of c in the string and returns the pointer with its position. I just wanted to understand this application better.</p>
| [
{
"answer_id": 74376472,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "&"
},
{
"answer_id": 74376866,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 1,
"selected": true,
"text": "strchr"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19766668/"
] |
74,376,397 | <p>I am having an issue returning a component depending on a value. So firstly I have created state called activeIndex defaulted to 1, I then have 3 buttons that when clicked will change this state to either 1, 2 or 3 this works fine. Then the buttons also run a function called showTab() this checks the value of activeIndex and depending on what value that is equal to will return a different component. I then render this by putting { showTab } but when clicking the different buttons it does not show the different components.</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 Forcast = () => {
// Create state to change tabs and return an index
const [activeIndex, setActiveIndex] = useState(1);
const handleClick = (index) => setActiveIndex(index);
const checkActive = (index, className) =>
activeIndex === index ? className : "";
// Create function to return a component depending on activeIndex value
const showTab = (activeIndex) => {
if (activeIndex === 1) {
return <Today />
} else if (activeIndex === 2) {
return <Tomorrow />
} else {
return <SevenDays />
}
}
return (
<div>
<div className="tabs">
<button
className={`tab ${checkActive(1, "active")}`}
onClick={() => {handleClick(1); showTab();}}
>
Product Info
</button>
<button
className={`tab ${checkActive(2, "active")}`}
onClick={() => {handleClick(2); showTab();}}
>
Customer Reviews
</button>
<button
className={`tab ${checkActive(3, "active")}`}
onClick={() => {handleClick(3); showTab();}}
>
Delivery &amp; Returns
</button>
{
showTab
}
</div>
</div>
);
};</code></pre>
</div>
</div>
I am receiving this error which is telling me that it happens when I return a Component instead of from render.</p>
<blockquote>
<p>Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.</p>
</blockquote>
| [
{
"answer_id": 74376472,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "&"
},
{
"answer_id": 74376866,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 1,
"selected": true,
"text": "strchr"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13821506/"
] |
74,376,401 | <p>I have Raw query running as</p>
<pre><code>select meeting.id, GROUP_CONCAT(users.name separator " | ") AS present_user_id from `meeting` left join `users` on JSON_CONTAINS(meeting.present_user_id, JSON_ARRAY(users.id), '$') group by `meeting`.`id`
</code></pre>
<p>Which provide proper result, I tried to convert same in Laravel 8 like this</p>
<pre><code>DB::table('meeting')
->selectRaw(' meeting.id, GROUP_CONCAT(users.name separator " | ") AS present_user_id')
->leftJoin('users', DB::raw("JSON_CONTAINS(meeting.present_user_id, JSON_ARRAY(users.id), '$')", DB::raw(' '), DB::raw(' ')))
->groupBy('meeting.id')
->get();
</code></pre>
<p>This create query as</p>
<pre><code>select meeting.id, GROUP_CONCAT(users.name separator " | ") AS present_user_id from `meeting` left join `users` on JSON_CONTAINS(meeting.present_user_id, JSON_ARRAY(users.id), '$') = `` group by `meeting`.`id`
</code></pre>
<p>So Laravel add ( = `` ) at the end of join which I don't want and want to remove let me know how can I achieve it. I do want to use QueryBuilder only.</p>
| [
{
"answer_id": 74376506,
"author": "Techno",
"author_id": 2595985,
"author_profile": "https://Stackoverflow.com/users/2595985",
"pm_score": 1,
"selected": false,
"text": "$result = DB::select('\n select \n meeting.id, \n GROUP_CONCAT(users.name separator \" | \") AS present_user_id \n from `meeting` \n left join `users` on JSON_CONTAINS(meeting.present_user_id, JSON_ARRAY(users.id), \\'$\\') \n group by `meeting`.`id`\n');\n"
},
{
"answer_id": 74376726,
"author": "dvicemuse",
"author_id": 1155184,
"author_profile": "https://Stackoverflow.com/users/1155184",
"pm_score": 0,
"selected": false,
"text": "composer require itul/sql-to-laravel\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293790/"
] |
74,376,412 | <p>Why does C# not allow to concat methods with <code>?.</code> in chain?</p>
<pre class="lang-cs prettyprint-override"><code>class X {
public static Timestamp ToTimestamp(this System.DateTime dateTime);
public void Demo()
{
System.DateTime? dateTime = GetFromSomewhere();
Timestamp? good = (dateTime?.ToUniversalTime())?.ToTimestamp();
Timestamp? bad = dateTime?.ToUniversalTime()?.ToTimestamp();
}
}
</code></pre>
<p>I was very surprised that the line with bad gives a compilation error:</p>
<pre><code>error CS0023: Operator '?' cannot be applied to operand of type 'DateTime'
</code></pre>
<p>How adding of braces can change the type here?</p>
| [
{
"answer_id": 74376605,
"author": "sommmen",
"author_id": 4122889,
"author_profile": "https://Stackoverflow.com/users/4122889",
"pm_score": 0,
"selected": false,
"text": "Timestamp? bad = dateTime?.ToUniversalTime()?.ToTimestamp();\n"
},
{
"answer_id": 74376672,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 1,
"selected": false,
"text": "Timestamp? good = (dateTime?.ToUniversalTime())?.ToTimestamp();\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892278/"
] |
74,376,416 | <p>Based on this result from an API</p>
<pre><code>"name": {
"common": "Italy",
"official": "Italian Republic",
"nativeName": {
"ita": {
"official": "Repubblica italiana",
"common": "Italia"
}
}
},
</code></pre>
<p>Let's suppose i always want the "common" name but, depending on the country the "key" will vary (now it's "ita" but it could be anything)</p>
<p>What is the cleanest way to always get the "common" value independently of the key name above? (so a dynamic function that always get the common value)</p>
| [
{
"answer_id": 74376519,
"author": "RiggsFolly",
"author_id": 2310830,
"author_profile": "https://Stackoverflow.com/users/2310830",
"pm_score": 0,
"selected": false,
"text": "common"
},
{
"answer_id": 74376647,
"author": "Simone Rossaini",
"author_id": 12402732,
"author_profile": "https://Stackoverflow.com/users/12402732",
"pm_score": 0,
"selected": false,
"text": "get_mangled_object_vars()"
},
{
"answer_id": 74379119,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 1,
"selected": false,
"text": "$arr = json_decode('{\"name\": {\n \"common\": \"Italy\",\n \"official\": \"Italian Republic\",\n \"nativeName\": {\n \"ita\": {\n \"official\": \"Repubblica italiana\",\n \"common\": \"Italia\"\n }\n }\n}}',true);\n\n$country = key($arr['name']['nativeName']); //ita\n$common = $arr['name']['nativeName'][$country]['common']; //Italia\n\necho '$country = '.$country.', $common = '.$common;\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299372/"
] |
74,376,432 | <p>I'm trying to put a 'mask' over a div that contains scrollable content using CSS <code>position: sticky</code>. I want the mask to overlay the content but <em>not</em> the scrollbar. In addition, the container height needs to be defined using <code>max-height</code> instead of <code>height</code>. I've almost got it to do what I want, except for the fact that it pushes the content beneath down, whereas I want the content to start at the top of the container, where it would if the sticky were not there. I've read that this should be possible but I can't seem to get it to work right. What am I doing wrong?</p>
<p><a href="https://codepen.io/jez9999/pen/ZERLoYv" rel="nofollow noreferrer">Here's the Codepen.</a></p>
<p>The code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
border: 0;
padding: 0;
margin: 0;
}
#stickyMask {
position: sticky;
top: 0;
background-color: #2ecc71;
text-align: center;
width: 100%;
height: 100%;
opacity: 0.5;
font-size: x-large;
font-weight: bold;
}
.container {
max-height: 250px;
overflow: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Below is some masked scrollable content:</h2>
<div class="container">
<div id="stickyMask">
Green mask using sticky positioning inside a container
</div>
<h3>
Content which overflows and scrolls
</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74376519,
"author": "RiggsFolly",
"author_id": 2310830,
"author_profile": "https://Stackoverflow.com/users/2310830",
"pm_score": 0,
"selected": false,
"text": "common"
},
{
"answer_id": 74376647,
"author": "Simone Rossaini",
"author_id": 12402732,
"author_profile": "https://Stackoverflow.com/users/12402732",
"pm_score": 0,
"selected": false,
"text": "get_mangled_object_vars()"
},
{
"answer_id": 74379119,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 1,
"selected": false,
"text": "$arr = json_decode('{\"name\": {\n \"common\": \"Italy\",\n \"official\": \"Italian Republic\",\n \"nativeName\": {\n \"ita\": {\n \"official\": \"Repubblica italiana\",\n \"common\": \"Italia\"\n }\n }\n}}',true);\n\n$country = key($arr['name']['nativeName']); //ita\n$common = $arr['name']['nativeName'][$country]['common']; //Italia\n\necho '$country = '.$country.', $common = '.$common;\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178757/"
] |
74,376,442 | <p>I am struggling to make the two numbers i put in the text field multiply and show me the answer to the multiplication. Here is how it should look like when i click the multiply numbers button:(<a href="https://i.stack.imgur.com/WXEkm.png" rel="nofollow noreferrer">https://i.stack.imgur.com/WXEkm.png</a>)](<a href="https://i.stack.imgur.com/WXEkm.png" rel="nofollow noreferrer">https://i.stack.imgur.com/WXEkm.png</a>)</p>
<p>So i have tried what is shown here:</p>
<pre><code><script>
var userInput1 = document.getElementById("user-input-1");
var userInput2 = document.getElementById("user-input-2");
var numbersBtn = document.getElementById("numbers-btn");
var outputDiv = document.getElementById("output-div");
numbersBtn.onclick = getMultiplication;
var number1 = userInput1.value;
var number2 = userInput2.value;
function getMultiplication(number1, number2) {
var result = number1 * number2;
return result;
}
outputDiv.innerHTML = getMultiplication(number1, number2);
</script>
</code></pre>
<p>It looks like this on the webpage:(<a href="https://i.stack.imgur.com/HxMCT.png" rel="nofollow noreferrer">https://i.stack.imgur.com/HxMCT.png</a>)](<a href="https://i.stack.imgur.com/HxMCT.png" rel="nofollow noreferrer">https://i.stack.imgur.com/HxMCT.png</a>)</p>
<p>The when i type numbers in the boxes and click the button, nothing happens and no error in the console log.</p>
<p>I have also tried without .value behind the userInputs, but then it displays NaN. I have also tried som other orders of the code, still no luck.</p>
<p>(Im very new to JS and parameters is one of my biggest weaknesses).</p>
| [
{
"answer_id": 74376586,
"author": "XCS",
"author_id": 407650,
"author_profile": "https://Stackoverflow.com/users/407650",
"pm_score": 0,
"selected": false,
"text": " var number1 = userInput1.value;\n var number2 = userInput2.value;\n\n function getMultiplication(number1, number2) {\n var result = number1 * number2;\n return result;\n }\n outputDiv.innerHTML = getMultiplication(number1, number2);\n"
},
{
"answer_id": 74376751,
"author": "mmh4all",
"author_id": 18461576,
"author_profile": "https://Stackoverflow.com/users/18461576",
"pm_score": 2,
"selected": true,
"text": "var userInput1 = document.getElementById(\"user-input-1\");\nvar userInput2 = document.getElementById(\"user-input-2\");\nvar numbersBtn = document.getElementById(\"numbers-btn\");\nvar outputDiv = document.getElementById(\"output-div\");\n\nnumbersBtn.onclick = ()=> {\n var number1 = userInput1.value;\n var number2 = userInput2.value; \n outputDiv.innerHTML = getMultiplication(number1, number2);\n}\n\nfunction getMultiplication(number1, number2) {\n var result = number1 * number2;\n return result;\n}"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20055080/"
] |
74,376,447 | <p>I have a csv file. The columns are ['A' 'B' 'C'], and there are 1000 rows of original data.
A B C
1 0 1
-1 2 0
.
.
.
1 0 0.
So I need 40% of these data in one csv_file, 60 % in the other. But first, the rows must be shuffled randomly. Hopefully using the pandas module in python.</p>
<p>I tried</p>
<pre class="lang-py prettyprint-override"><code>Import pandas as pd
df=pd.read_csv('filename.csv')
np.random.permutation(df)
df[0:400].to_csv('filename1.csv')
df[401:].to_csv('filename2.csv')
</code></pre>
<p>but np.random.permutation(df) returns only arrays.</p>
| [
{
"answer_id": 74376659,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\nimport pandas as pd\n\n\nper = 40\nmask =int(len(df))\n\nperdf=df.head(int((mask*(per/100))))\n\nperdf =perdf.iloc[np.random.permutation(len(perdf))]\nperdf.to_csv('40perdf.csv')\n\n\nperdf60=df[:mask]\nperdf60 =perdf60.iloc[np.random.permutation(len(perdf60))]\nperdf60.to_csv('60perdf.csv')\n"
},
{
"answer_id": 74376727,
"author": "EM77",
"author_id": 13100760,
"author_profile": "https://Stackoverflow.com/users/13100760",
"pm_score": 0,
"selected": false,
"text": "pandas.DataFrame.sample"
},
{
"answer_id": 74376851,
"author": "Deiv_vieD",
"author_id": 17613745,
"author_profile": "https://Stackoverflow.com/users/17613745",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf = pd.read_csv(r\"C:\\temp\\test1.csv\", sep=',')\n# source file like this\n# A,B,C\n# 0,1,1\n# 0,0,0\n# 1,1,0\n# 0,0,0\n# 0,0,1\n# 2,0,0\n\ndf = pd.DataFrame( np.random.permutation(df))\ndf = df.rename(columns={0: 'A',1:'B',2:'C'})\n\nsplit_place = int(df.shape[0]*0.4)\ndf[0:split_place].to_csv(r'c:\\temp\\filename1.csv', index=False, columns=None, sep=',')\n# in file get somthing like\n# A,B,C\n# 0,0,1\n# 0,0,0\n\ndf[split_place:].to_csv(r'c:\\temp\\filename2.csv',index=False, sep=',')\n# if don't need header, can use header=False,\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459857/"
] |
74,376,454 | <p>please help me solve the problem.
The table:</p>
<p>id_client, values</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>IDs</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0,46</td>
</tr>
<tr>
<td>2</td>
<td>25%</td>
</tr>
<tr>
<td>3</td>
<td>No information</td>
</tr>
<tr>
<td>4</td>
<td>Twenty two</td>
</tr>
<tr>
<td>5</td>
<td>12.2</td>
</tr>
<tr>
<td>6</td>
<td>365%</td>
</tr>
<tr>
<td>7</td>
<td>54</td>
</tr>
</tbody>
</table>
</div>
<p>I need get numbers from string as percantages</p>
<p>Need next result of quarry</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>IDs</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0,46</td>
</tr>
<tr>
<td>2</td>
<td>25</td>
</tr>
<tr>
<td>3</td>
<td>null</td>
</tr>
<tr>
<td>4</td>
<td>null</td>
</tr>
<tr>
<td>5</td>
<td>12,2</td>
</tr>
<tr>
<td>6</td>
<td>365</td>
</tr>
<tr>
<td>7</td>
<td>54</td>
</tr>
</tbody>
</table>
</div>
<p>Tryied some regexp that i have found here but it works wrong</p>
| [
{
"answer_id": 74376554,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "SELECT\n id_client,\n REGEXP_SUBSTR(values, '[0-9]+([,.][0-9]+)?') AS values\nFROM yourTable;\n"
},
{
"answer_id": 74377487,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "%"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13277319/"
] |
74,376,469 | <p>Is there a way to simplify these methods? They are the same except for a different method being called.</p>
<pre><code>private async Task ChangePresence(bool args, int voteId)
{
if (GeneralMeetingState.GeneralMeeting != null)
{
_spinnerVisible = true;
await AgendaItemsDetailState.ChangePresence(args, GeneralMeetingState.GeneralMeeting.ID,
AgendaItemId, voteId);
await AgendaState.GetAgendaItem(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
await AgendaItemsDetailState.GetVotesList(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
_spinnerVisible = false;
}
}
private async Task VoteFor(bool args, int voteId)
{
if (GeneralMeetingState.GeneralMeeting != null)
{
_spinnerVisible = true;
await AgendaItemsDetailState.ChangeVoteFor(args, GeneralMeetingState.GeneralMeeting.ID,
AgendaItemId, voteId, GeneralMeetingState.IsUserOwner);
await AgendaState.GetAgendaItem(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
await AgendaItemsDetailState.GetVotesList(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
_spinnerVisible = false;
}
}
private async Task VoteAgainst(bool args, int voteId)
{
if (GeneralMeetingState.GeneralMeeting != null)
{
_spinnerVisible = true;
await AgendaItemsDetailState.ChangeVoteAgainst(args, GeneralMeetingState.GeneralMeeting.ID,
AgendaItemId, voteId, GeneralMeetingState.IsUserOwner);
await AgendaState.GetAgendaItem(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
await AgendaItemsDetailState.GetVotesList(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
_spinnerVisible = false;
}
}
private async Task ChangeVoteAbstinence(bool args, int voteId)
{
if (GeneralMeetingState.GeneralMeeting != null)
{
_spinnerVisible = true;
await AgendaItemsDetailState.ChangeVoteAbstinence(args, GeneralMeetingState.GeneralMeeting.ID,
AgendaItemId, voteId, GeneralMeetingState.IsUserOwner);
await AgendaState.GetAgendaItem(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
await AgendaItemsDetailState.GetVotesList(GeneralMeetingState.GeneralMeeting.ID, AgendaItemId);
_spinnerVisible = false;
}
}
</code></pre>
<p>I was looking into passing a method as a parameter and using Action<bool, int> but i couldn't figure it out. Any help is much appreciated</p>
| [
{
"answer_id": 74376554,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "SELECT\n id_client,\n REGEXP_SUBSTR(values, '[0-9]+([,.][0-9]+)?') AS values\nFROM yourTable;\n"
},
{
"answer_id": 74377487,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "%"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17421581/"
] |
74,376,489 | <p>I'm doing some Chinese zodiac assignment for my programming course in C, and I'm not sure if there's a way I can write this doe in much less lines:</p>
<pre><code>int main() {
int year;
printf("Enter your year of birth: \n");
scanf_s("%i", &year);
if (year % 12 == 0) {
return 0;
} else if (year % 12 == 1) {
return 1;
} else if (year % 12 == 2) {
return 2;
} else if (year % 12 == 3) {
return 3;
} else if (year % 12 == 4) {
return 4;
} else if (year % 12 == 5) {
return 5;
} else if (year % 12 == 6) {
return 6;
} else if (year % 12 == 7) {
return 7;
} else if (year % 12 == 8) {
return 8;
} else if (year % 12 == 9) {
return 9;
} else if (year % 12 == 10) {
return 10;
} else if (year % 12 == 11) {
return 11;
}
</code></pre>
<p>I want to know if there's any way to optimize this code.</p>
| [
{
"answer_id": 74376554,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "SELECT\n id_client,\n REGEXP_SUBSTR(values, '[0-9]+([,.][0-9]+)?') AS values\nFROM yourTable;\n"
},
{
"answer_id": 74377487,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "%"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459895/"
] |
74,376,512 | <p>Suppose I have a data frame that has the following elements say:</p>
<p><code> Element</code></p>
<p><code>0 a_1</code></p>
<p><code>1 a_2</code></p>
<p><code>2 b_1</code></p>
<p><code>3 a_3</code></p>
<p><code>4 b_2</code></p>
<p><code>.....</code></p>
<p>and so on.</p>
<p>Now suppose I have two categories <code>A</code> and <code>B</code>. Every element falls into one of these categories, and let's say I have lists <code>As = [a_1, a_2, ...]</code> and <code>Bs = [b_1, b_2, ...]</code></p>
<p>What I want to do is add a column <code>Category</code> to df:</p>
<p><code> Element Category</code></p>
<p><code>0 a_1 A </code></p>
<p><code>1 a_2 A </code></p>
<p><code>2 b_1 B </code></p>
<p><code>3 a_3 A </code></p>
<p><code>4 b_2 B </code></p>
<p><code>.....</code></p>
<p>That is, we will query each row of the df, check if element is in one of these lists and the value of the new column will be the list it's in. Each element will be in one of these lists.</p>
<p>How would I go about doing this?</p>
<p>I've considered making via for loops a new array for the new column by checking each row but I feel like there should be a sleeker more pythonic way to do this.</p>
| [
{
"answer_id": 74376598,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "map"
},
{
"answer_id": 74376914,
"author": "DarrylG",
"author_id": 3066077,
"author_profile": "https://Stackoverflow.com/users/3066077",
"pm_score": 0,
"selected": false,
"text": "# Add column Category by Assigning 'A' if the element in list A else assign 'B'\ndf['Category'] = np.where(np.in1d(df['Element'], A), 'A', 'B')\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459948/"
] |
74,376,531 | <p>I am following a tutorial on Udemy to learn Angular, the instructor provided the code, but each lesson is a new project in a new folder. I would like to merge all the folders into a single repository, so that each folder is a commit. How could I do that?.</p>
<p>This is a screenshot of a section of the course. As I said, I would like each of those folders to be a commit, because the content of each one is almost the same. And it would be easier for me to hit "git checkout" every time I go to a new lesson, than to open each folder, install the dependencies and start a new server.</p>
<p><a href="https://i.stack.imgur.com/EyQwT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EyQwT.png" alt="enter image description here" /></a></p>
<p>The only solution I've come up with so far is to go to the beginning of the project, hit commit, then delete all the files and paste the contents of the next lesson, hit commit again, and so on, but it would be very time consuming.</p>
| [
{
"answer_id": 74376629,
"author": "Branson Smith",
"author_id": 11329158,
"author_profile": "https://Stackoverflow.com/users/11329158",
"pm_score": 0,
"selected": false,
"text": "git init"
},
{
"answer_id": 74376645,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 2,
"selected": false,
"text": "git init todo-junto # I know he speaks spanish so it's fine ;-)\ncd todo-junto\nfor i in 15 17 18 19 20 21; do # all the separate projects\n git remote add tarea$i ../$i # tarea15 for 15, tarea17 for 17\n git fetch tarea$i # get to see the branches in that repo.... we will _copy_ main\n git branch tarea_$i tarea$i/main # create local branch tarea_15 for remote tarea15/main and so on\n # now we can remove the remote as we have the local branch\n git remote remove tarea$i\ndone\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13463660/"
] |
74,376,571 | <p>I can graph it using matplotlib:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
</code></pre>
<p>credit: <a href="https://www.w3schools.com/python/matplotlib_scatter.asp" rel="nofollow noreferrer">https://www.w3schools.com/python/matplotlib_scatter.asp</a></p>
<p>How can I adjust my code to work with the CanvasXpress Library?</p>
| [
{
"answer_id": 74376629,
"author": "Branson Smith",
"author_id": 11329158,
"author_profile": "https://Stackoverflow.com/users/11329158",
"pm_score": 0,
"selected": false,
"text": "git init"
},
{
"answer_id": 74376645,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 2,
"selected": false,
"text": "git init todo-junto # I know he speaks spanish so it's fine ;-)\ncd todo-junto\nfor i in 15 17 18 19 20 21; do # all the separate projects\n git remote add tarea$i ../$i # tarea15 for 15, tarea17 for 17\n git fetch tarea$i # get to see the branches in that repo.... we will _copy_ main\n git branch tarea_$i tarea$i/main # create local branch tarea_15 for remote tarea15/main and so on\n # now we can remove the remote as we have the local branch\n git remote remove tarea$i\ndone\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459994/"
] |
74,376,572 | <p>I have one dataframe (X) that looks like</p>
<pre><code>label1 label2
1 2
1 3
1 4
2 1
2 3
2 4
</code></pre>
<p>And another (Y) that looks like</p>
<pre><code>label COLONY
1 5
2 5
3 5
4 6
</code></pre>
<p>I have compared the labels in dataframe X to Y if they are in the same colony listed in dataframe Y and made a new dataframe with this line:</p>
<pre><code>Z <- transform(X, SAME.COLONY = Y$COLONY[match(X$label1, Y$label)] == Y$COLONY[match(X$label2, Y$label)])
</code></pre>
<pre><code>label1 label2 SAME.COLONY
1 2 TRUE
1 3 TRUE
1 4 FALSE
2 1 TRUE
2 3 TRUE
2 4 FALSE
3 4 FALSE
</code></pre>
<p>Now I am looking to import a new column from dataframe Y into Z with the group value only if Z$SAME.COLONY==T and the one of the label numbers match, but this isn't working for me:</p>
<pre><code>Z$COLONY<- ifelse(Z$SAME.COLONY == T && Z$label1 == Y$label, Y$COLONY, NA)
</code></pre>
<p>I get this warning message:</p>
<pre><code>Warning message:
In Z$label1 == Y$label :
longer object length is not a multiple of shorter object length
</code></pre>
<p>This may be becuase label values are repeated multiple time in Z$label1 and Z$label2 but I'm not sure how to account for this?</p>
<p>Reproduce data:</p>
<pre><code>X=data.frame(label1=c(1,1,1,2,2,2,3), label2=c(2,3,4,1,3,4,4))
Y=data.frame(label=c(1,2,3,4), COLONY=c(5,5,5,6))
Z <- transform(X,
SAME.COLONY =
Y$COLONY[match(X$label1, Y$label)] ==
Y$COLONY[match(X$label2, Y$label)]
)
</code></pre>
| [
{
"answer_id": 74377323,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\n# 7 don't exist in Y$label\nX=data.frame(label1=c(7,1,1,2,2,2,3), label2=c(2,3,4,1,3,4,4))\nY=data.frame(label=c(1,2,3,4), COLONY=c(5,5,5,6))\n\n\nZ=X%>%\n rowwise()%>%\n # check if COLONY of label1 is the same of COLONY of label2\n mutate(SAME.COLONY = ifelse(label1%in% Y$label && label2%in%Y$label,\n (Y[Y$label == label1, ]$COLONY == Y[Y$label == label2, ]$COLONY),\n NA\n )\n )%>%\n # get COLONY if True\n mutate(COLONY=ifelse(SAME.COLONY==T,Y[Y$label==label1,]$COLONY,NA))\n\nZ\n# > Z\n# A tibble: 7 x 4\n# Rowwise: \n# label1 label2 SAME.COLONY COLONY\n# <dbl> <dbl> <lgl> <dbl>\n# 7 2 NA NA\n# 1 3 TRUE 5\n# 1 4 FALSE NA\n# 2 1 TRUE 5\n# 2 3 TRUE 5\n# 2 4 FALSE NA\n# 3 4 FALSE NA\n\n"
},
{
"answer_id": 74378518,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nZ <- left_join(Z, Y, by = c(\"label1\" = \"label\")) %>%\n mutate(COLONY = case_when(SAME.COLONY~ COLONY))\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11697741/"
] |
74,376,574 | <p>I have generated answer buttons and when I click the answer button color is not changing. Can you help me to sort this out. Here all I want is to change the color when ever I click a button. Please help me out since I'm very new to flutter. Thank you very much.</p>
<pre><code>import 'package:flutter/material.dart';
import 'show_question_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class ShowQuestions extends StatefulWidget {
final String subid;
const ShowQuestions({super.key, required this.subid});
@override
State<ShowQuestions> createState() => _ShowQuestionsState(subid);
}
class _ShowQuestionsState extends State<ShowQuestions> {
String subid;
_ShowQuestionsState(this.subid);
List<Question> questionList = [];
int currentQuestionIndex = 0;
int score = 0;
late final Future myFuture;
void initState() {
super.initState();
myFuture = getQuestionData(subid);
}
Future getQuestionData(String subid) async {
var response = await http.get(
Uri.http("www.ananmanan.lk", "app/getQuestionList.php", {'id': subid}));
var jsonData = jsonDecode(response.body);
List<Question> questions = [];
for (var u in jsonData) {
Question question = Question(
u['ques'],
u['ans1'],
u['ans2'],
u['ans3'],
u['ans4'],
u['correct_ans'].toString(),
);
questions.add(question);
}
return questions;
}
//Answer? selectedAnswer;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Question Paper'),
centerTitle: true,
),
body: Container(
child: FutureBuilder(
future: myFuture,
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text('Loading...'),
),
);
} else {
questionList = snapshot.data;
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_questionWidget(),
_answerList(),
_nextButton(),
],
),
);
}
},
)),
);
}
_questionWidget() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Question ${currentQuestionIndex + 1}/5}',
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w600,
),
),
const SizedBox(
height: 20.0,
),
Container(
width: double.infinity,
alignment: Alignment.center,
padding: const EdgeInsets.all(32.0),
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(16)),
child: Text(
questionList[currentQuestionIndex].ques,
style: const TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.w600,
),
),
),
],
);
}
_answerList() {
bool isCorrectAns = false;
bool isAns1 = false;
bool isAns2 = false;
bool isAns3 = false;
bool isAns4 = false;
//bool isSelected = answer == selectedAnswer;
// ignore: unrelated_type_equality_checks
// if (questionList[currentQuestionIndex].correctanswer == 1) {
// isCorrectAns = true;
// } else {
// isCorrectAns = false;
// }
if (questionList[currentQuestionIndex].correct_ans == '1') {
isAns1 = true;
} else if (questionList[currentQuestionIndex].correct_ans == '2') {
isAns2 = true;
} else if (questionList[currentQuestionIndex].correct_ans == '3') {
isAns3 = true;
} else if (questionList[currentQuestionIndex].correct_ans == '4') {
isAns4 = true;
}
return Container(
// width: double.infinity,
// margin: const EdgeInsets.symmetric(vertical: 2),
// height: 48,
child: Column(children: [
_answerButton(questionList[currentQuestionIndex].ans1, isAns1),
_answerButton(questionList[currentQuestionIndex].ans2, isAns2),
_answerButton(questionList[currentQuestionIndex].ans3, isAns3),
_answerButton(questionList[currentQuestionIndex].ans4, isAns4),
]),
);
}
Widget _answerButton(String ansText, bool correctans) {
//bool isSelected = answer == selectedAnswer;
bool click = false;
if (ansText != '') {
return Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 2),
height: 48,
child: ElevatedButton(
child: Text(ansText),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: click == true ? Colors.orangeAccent : Colors.white,
onPrimary: click == true ? Colors.white : Colors.black,
),
onPressed: () {
if (correctans) {
score++;
}
},
),
);
} else {
return SizedBox.shrink();
}
}
_nextButton() {
bool isLastQuestion = false;
if (currentQuestionIndex == questionList.length - 1) {
isLastQuestion = true;
}
return Container(
width: MediaQuery.of(context).size.width * 0.5,
height: 48,
child: ElevatedButton(
child: Text(isLastQuestion ? 'Submit' : 'Next'),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: Colors.blueAccent,
onPrimary: Colors.white,
),
onPressed: () {
if (isLastQuestion) {
showDialog(context: context, builder: (_) => _showScoreDialog());
} else {
setState(() {
//selectedAnswer = null;
currentQuestionIndex++;
});
}
},
),
);
}
_showScoreDialog() {
bool isPassed = false;
if (score >= questionList.length * 0.6) {
isPassed = true;
}
String title = isPassed ? 'Passed' : 'Failed';
return AlertDialog(
title: Text(
title + ' | Score is $score',
style: TextStyle(color: isPassed ? Colors.green : Colors.redAccent),
),
content: ElevatedButton(
child: const Text('Restart'),
onPressed: () {
Navigator.pop(context);
setState(() {
currentQuestionIndex = 0;
score = 0;
//selectedAnswer = null;
});
},
),
);
}
}
</code></pre>
<p>Change the button color of the above code</p>
| [
{
"answer_id": 74377323,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\n# 7 don't exist in Y$label\nX=data.frame(label1=c(7,1,1,2,2,2,3), label2=c(2,3,4,1,3,4,4))\nY=data.frame(label=c(1,2,3,4), COLONY=c(5,5,5,6))\n\n\nZ=X%>%\n rowwise()%>%\n # check if COLONY of label1 is the same of COLONY of label2\n mutate(SAME.COLONY = ifelse(label1%in% Y$label && label2%in%Y$label,\n (Y[Y$label == label1, ]$COLONY == Y[Y$label == label2, ]$COLONY),\n NA\n )\n )%>%\n # get COLONY if True\n mutate(COLONY=ifelse(SAME.COLONY==T,Y[Y$label==label1,]$COLONY,NA))\n\nZ\n# > Z\n# A tibble: 7 x 4\n# Rowwise: \n# label1 label2 SAME.COLONY COLONY\n# <dbl> <dbl> <lgl> <dbl>\n# 7 2 NA NA\n# 1 3 TRUE 5\n# 1 4 FALSE NA\n# 2 1 TRUE 5\n# 2 3 TRUE 5\n# 2 4 FALSE NA\n# 3 4 FALSE NA\n\n"
},
{
"answer_id": 74378518,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nZ <- left_join(Z, Y, by = c(\"label1\" = \"label\")) %>%\n mutate(COLONY = case_when(SAME.COLONY~ COLONY))\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20455262/"
] |
74,376,580 | <p>I need to create a new column %age that returns the value by taking the value in the Subject column of that row to find the value in the column name that matches the value in the subject column.</p>
<p><a href="https://i.stack.imgur.com/e9Ufw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9Ufw.png" alt="enter image description here" /></a></p>
<p>For example,</p>
<p>K1 = =HLOOKUP([@Subject], E:H,2,0), but it's wrong as in column L</p>
<p><a href="https://i.stack.imgur.com/vG0dG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vG0dG.png" alt="enter image description here" /></a>.</p>
<p>How to get the formula to return that row values as in column K?</p>
<p>Regards,
NewB</p>
| [
{
"answer_id": 74377323,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\n\n# 7 don't exist in Y$label\nX=data.frame(label1=c(7,1,1,2,2,2,3), label2=c(2,3,4,1,3,4,4))\nY=data.frame(label=c(1,2,3,4), COLONY=c(5,5,5,6))\n\n\nZ=X%>%\n rowwise()%>%\n # check if COLONY of label1 is the same of COLONY of label2\n mutate(SAME.COLONY = ifelse(label1%in% Y$label && label2%in%Y$label,\n (Y[Y$label == label1, ]$COLONY == Y[Y$label == label2, ]$COLONY),\n NA\n )\n )%>%\n # get COLONY if True\n mutate(COLONY=ifelse(SAME.COLONY==T,Y[Y$label==label1,]$COLONY,NA))\n\nZ\n# > Z\n# A tibble: 7 x 4\n# Rowwise: \n# label1 label2 SAME.COLONY COLONY\n# <dbl> <dbl> <lgl> <dbl>\n# 7 2 NA NA\n# 1 3 TRUE 5\n# 1 4 FALSE NA\n# 2 1 TRUE 5\n# 2 3 TRUE 5\n# 2 4 FALSE NA\n# 3 4 FALSE NA\n\n"
},
{
"answer_id": 74378518,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nZ <- left_join(Z, Y, by = c(\"label1\" = \"label\")) %>%\n mutate(COLONY = case_when(SAME.COLONY~ COLONY))\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3094480/"
] |
74,376,589 | <p>I am looking to calculate the vote share for a candidate in a particular district for a particular election.</p>
<p>I've got a dataset that gives me the party of the candidate, the district that they ran in, and the year of the election.</p>
<p>However, I have their competitors as well and want to calculate the vote share for one of the candidates, say the Democratic candidate. How would I then place that vote share value in the rows for all of those in that particular race?</p>
<p>Here's an example of a pandas dataframe that I have:</p>
<pre><code> year state district candidate party candidatevotes totalvotes
0 1976 alabama 1 BILL DAVENPORT DEMOCRAT 58906 157170
1 1976 alabama 1 JACK EDWARDS REPUBLICAN 98257 157170
2 1976 alabama 1 WRITEIN NaN 7 157170
3 1976 alabama 2 J CAROLE KEAHEY DEMOCRAT 66288 156362
4 1976 alabama 2 WILLIAM L "BILL" DICKINSON REPUBLICAN 90069 156362
</code></pre>
<p>What I want to be able to do is have a column that would take the vote share of the democratic candidate for that particular district and year. But that vote share value be there for all of the candidates in that particular race:</p>
<pre><code> year state district candidate party candidatevotes totalvotes Dem_vote_share
0 1976 alabama 1 BILL DAVENPORT DEMOCRAT 58906 157170 0.374
1 1976 alabama 1 JACK EDWARDS REPUBLICAN 98257 157170 0.374
2 1976 alabama 1 WRITEIN NaN 7 157170 0.374
3 1976 alabama 2 J CAROLE KEAHEY DEMOCRAT 66288 156362 0.424
4 1976 alabama 2 WILLIAM L "BILL" DICKINSON REPUBLICAN 90069 156362 0.424
</code></pre>
<p>If helpful: a full dataset can be found here: <a href="https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/IG0UN2" rel="nofollow noreferrer">https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/IG0UN2</a></p>
<p>EDIT:</p>
<p>For the full dataset, this is what ended up working:</p>
<pre><code>df['Unique_District'] = df[['state', 'district']].apply(lambda x: '-'.join(x.astype(str)), axis=1) #to make a unique district column
mapping_vals = (
df[df['party'].eq('DEMOCRAT')]
.set_index(['year', 'Unique_District'])
.apply(lambda x: x['candidatevotes']/x['totalvotes'],axis=1)
.groupby(level=[0,1]).sum()
)
df['Dem_vote_share'] = df.set_index(['year', 'Unique_District']).index.map(mapping_vals)
</code></pre>
| [
{
"answer_id": 74376735,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 0,
"selected": false,
"text": "transform()"
},
{
"answer_id": 74376799,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 2,
"selected": true,
"text": "Dem_votes_share"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12394134/"
] |
74,376,592 | <p>I have a data</p>
<pre><code>const Data = [
{
id: '1',
title: 'Blablab<b>labl</b>abla',
},
{
id: '2',
title: '2Blablab<b>labl</b>abla',
},
];
</code></pre>
<p><code><p>{Data.title}</p></code></p>
<pre><code>Output : Blablab<b>labl</b>abla
tag <b></b> not render
</code></pre>
<p>the output i want is bold</p>
<p>The code above is just an example, for the data in my project I use the API and in the API the data type is string. inside the string contains the html tag but the html is not readable in the display</p>
| [
{
"answer_id": 74376735,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 0,
"selected": false,
"text": "transform()"
},
{
"answer_id": 74376799,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 2,
"selected": true,
"text": "Dem_votes_share"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20066668/"
] |
74,376,613 | <p>I am trying to created a weighted average for each week, across multiple columns. My data looks like this:</p>
<pre><code>week <- c(1,1,1,2,2,3)
col_a <- c(1,2,2,4,2,7)
col_b <- c(4,2,3,1,2,5)
col_c <- c(4,2,3,2,2,4)
dfreprex <- data.frame(week,col_a,col_b,col_c)
</code></pre>
<pre><code> week col_a col_b col_c
1 1 1 4 4
2 1 2 2 2
3 1 2 3 3
4 2 4 1 2
5 2 2 2 2
6 3 7 5 4
</code></pre>
<pre><code>weightsreprex <- data.frame(county = c("col_a", "col_b", "col_c")
, weights = c(.3721, .3794, .2485))
</code></pre>
<p>How do I weight each column and then get the mean? Is there a simpler way than just multiplying each column by its weight in a new column (col_a_weighted) and then taking the rowmean of the weighted columns only?</p>
<p>Tried weighted.means, rowmeans, group_by and summarise</p>
| [
{
"answer_id": 74376775,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "stats::weighted.mean()"
},
{
"answer_id": 74376831,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 2,
"selected": false,
"text": "*"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20200358/"
] |
74,376,634 | <p>So I was trying to make a function that is required to access the template argument of that class and I don't want to put that function in the class itself.<br />
Here is a example:</p>
<pre><code> template <class Type>
class Node
{
public:
Type Value;
Type* ptr_next;
};
void element_output(Node< /*template argument of the class*/> * head)
{
while(head!=NULL)
{
std::cout << head->Value << "\n";
head = head->ptr_next;
}
}
</code></pre>
<p>I tried using a template for that function but that didn't work.
i was thinking of just overloading the Node template argument in the function parameter with all the types.But i knew there was bound to be a error had to be a error that will occur.</p>
<p>So what I think could work is like a getter and setter for the template parameters similar with constructors and private memebers.</p>
| [
{
"answer_id": 74376657,
"author": "Jarod42",
"author_id": 2684539,
"author_profile": "https://Stackoverflow.com/users/2684539",
"pm_score": 3,
"selected": false,
"text": "template <typename T>\nvoid element_output(Node<T>* head)\n{\n while (head != nullptr)\n {\n std::cout << head->Value << \"\\n\";\n head = head->ptr_next;\n }\n}\n"
},
{
"answer_id": 74376762,
"author": "Yves Daoust",
"author_id": 1196549,
"author_profile": "https://Stackoverflow.com/users/1196549",
"pm_score": 1,
"selected": false,
"text": "void element_output(Node<int>* head) { while ... }\n\nvoid element_output(Node<double>* head) { while ... }\n\nvoid element_output(Node<MyType>* head) { while ... }\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459932/"
] |
74,376,674 | <p>I have data as follows:</p>
<pre><code>library(data.table)
datA <- fread("A B C
1 1 1
2 2 2")
datB <- fread("A B C
1 1 1
2 2 2
3 3 3")
</code></pre>
<p>I want to figure out which rows are unique (which is the one with <code>3 3 3</code>, because all others occur more often).</p>
<p>I tried:</p>
<pre><code>dat <- rbind(datA, datB)
unique(dat)
!duplicated(dat)
</code></pre>
<p>I also tried</p>
<pre><code>setDT(dat)[,if(.N ==1) .SD,]
</code></pre>
<p>But that is <code>NULL</code>.</p>
<p>How should I do this?</p>
| [
{
"answer_id": 74376725,
"author": "B. Christian Kamgang",
"author_id": 10848898,
"author_profile": "https://Stackoverflow.com/users/10848898",
"pm_score": 2,
"selected": false,
"text": "library(data.table)\n\ndatB[!datA, on=c(\"A\", \"B\", \"C\")]\n\n A B C\n <int> <int> <int>\n1: 3 3 3\n"
},
{
"answer_id": 74376759,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "fsetdiff"
},
{
"answer_id": 74376925,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071608/"
] |
74,376,692 | <p>I'm trying to create a google sheets function where I use a array function [like UNIQUE() or FILTER()]but the array is returned into one cell and I can specify the location of the value I'm trying to obtain.</p>
<p>I think its analogous to a List in R where you have a list full of a number of string characters and you can return the one you want by specifying where it falls in the list.</p>
<p>Below is a sample of the problem I'm trying to solve.<a href="https://i.stack.imgur.com/v1EGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v1EGm.png" alt="data" /></a></p>
<p>Functions are as follows:
In cell B1: =UNIQUE(A1:A12)
In cell E1: =CHOOSE(C1, $B$1, $B$2, $B$3, $B$4)</p>
<p>I'd like all of this to happen in one cell. Is that possible? I was thinking maybe Lambda functions would be helpful here but I couldn't understand it well enough to use it in this scenario.</p>
<p>I have tried without success a bunch of combinations of the following functions: Lambda functions, Index(), Choose()</p>
<p>Thanks a ton!</p>
| [
{
"answer_id": 74376725,
"author": "B. Christian Kamgang",
"author_id": 10848898,
"author_profile": "https://Stackoverflow.com/users/10848898",
"pm_score": 2,
"selected": false,
"text": "library(data.table)\n\ndatB[!datA, on=c(\"A\", \"B\", \"C\")]\n\n A B C\n <int> <int> <int>\n1: 3 3 3\n"
},
{
"answer_id": 74376759,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "fsetdiff"
},
{
"answer_id": 74376925,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459995/"
] |
74,376,704 | <p>im creating a table for my Power Apps Project and i need a foundation so i can add the entries later on.</p>
<p>I want to create a excel-like table with entries. I am using a template from work loking like the first picture<a href="https://i.stack.imgur.com/UF8dt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UF8dt.png" alt="Excel Template" /></a></p>
<p>With the help of a friend i got a solid html code looking like this:<a href="https://i.stack.imgur.com/TdtsN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TdtsN.png" alt="HTML Progress" /></a></p>
<p>When comparing the pictures, you can see a space between each table. How can i archieve that?</p>
<p>Here is my code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html> <!--Information für den Browser um welches Dokument es sich handelt-->
<html lang="de"> <!--//zuordnung der Sprache-->
<head>
<meta charset="utf-8"> <!--ä, ü, ö möglich-->
<title>Überschrift</title> <!--Tab-Überschrift-->
<meta name="viewport" content="width=device-width, initial-scale=1"> <!--responsive-->
<style type="text/css">
* {
font-family: Arial, Helvetica, sans-serif;
}
table, tr, td {
border: 1px solid #054F9D;
border-collapse: collapse;
}
td {
padding: 0.5rem;
max-width: 12rem;
min-width: 12rem;
word-wrap: break-word;
}
.grey {
background-color: lightgrey;
min-width: 5rem;
max-width: 5rem;
}
p {
font-weight: bold;
padding-top: 2rem;
}
@media print {
.pagebreak {page-break-before: always;} /*Seitenumbruch*/
}
</style>
</head>
<body>
<h1>Überschrift</h1>
<!--Kundendaten-->
<div><p>Bereich</p>
<table>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
</table>
</div>
<!--Fahrzeugdaten-->
<div><p>Bereich2</p>
<table>
<tr>
<td class="grey">Inhalt</td>
<td>fevjvjjvjvjdfvjfvjfvjfjvjfdvjfdjvjfdjvfd</td>
<td class="grey">Inhalt</td>
<td>vfdjvjvjfjvfjvjvjfdvjfdjvfjdvjfdvjfdjvdj</td>
</tr>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
<tr>
<td class="grey">Inhalt</td>
<td>...</td>
<td class="grey">Inhalt</td>
<td>...</td>
</tr>
</table>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>i tried a new html with display; inline-block. However it only created a small space and i want them to be a bit larger. Didnt know how to achieve this</p>
| [
{
"answer_id": 74376871,
"author": "Maharkus",
"author_id": 3956676,
"author_profile": "https://Stackoverflow.com/users/3956676",
"pm_score": 2,
"selected": true,
"text": "* {\n font-family: Arial, Helvetica, sans-serif;\n}\n\ntable,\ntr,\ntd {\n border: 1px solid #054F9D;\n border-collapse: collapse;\n}\n\ntd {\n padding: 0.5rem;\n max-width: 12rem;\n min-width: 12rem;\n word-wrap: break-word;\n}\n\n.grey {\n background-color: lightgrey;\n min-width: 5rem;\n max-width: 5rem;\n}\n\np {\n font-weight: bold;\n padding-top: 2rem;\n}\n\n@media print {\n .pagebreak {\n page-break-before: always;\n }\n /*Seitenumbruch*/\n}\n\ndiv {\n display: flex;\n gap: 100px;\n}"
},
{
"answer_id": 74376901,
"author": "Armin Ayari",
"author_id": 8863489,
"author_profile": "https://Stackoverflow.com/users/8863489",
"pm_score": 0,
"selected": false,
"text": ".separator {\n border: none;\n border-top-style : hidden;\n border-bottom-style : hidden;\n}"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20440825/"
] |
74,376,707 | <p>I'm trying to delete some users which are related to a group.</p>
<p>Here is the schema:</p>
<pre><code>model User {
id String @id @default(cuid())
username String
email String @unique
password String?
group GroupUser[]
}
model Group {
id String @id @default(cuid())
name String
user GroupUser[]
}
model GroupUser{
userId String
user User @relation(fields: [userId],references: [id],onDelete: Cascade,onUpdate:Cascade)
groupId String
group Group @relation(fields: [groupId],references: [id],onDelete: Cascade,onUpdate: Cascade)
@@id([userId,groupId])
}
</code></pre>
<p>The code to delete the users:</p>
<pre><code>async deleteUsersFromGroup(id: string, userData: UpdateGroupDto): Promise<number> {
const deletedUsers = await prisma.group.update({
where: {
id: id,
},
data: {
user: { disconnect: /* trying to put the array of users id here */ },
},
});
return deletedUsers.length;
</code></pre>
<p>}</p>
<p>The problem is that I want to give the userID inside of the disconnect but it is asking me for userId_groupId which is the relational key.</p>
| [
{
"answer_id": 74386351,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 1,
"selected": false,
"text": "GroupUser"
},
{
"answer_id": 74389366,
"author": "Jose Bernardo",
"author_id": 17090572,
"author_profile": "https://Stackoverflow.com/users/17090572",
"pm_score": 1,
"selected": true,
"text": "async deleteUsersFromGroup(id: string, userData: DeleteGroupDto): Promise<any> {\n \n \n const response = await prisma.groupUser.deleteMany({\n where: {\n groupId: id,\n userId: { in: userData.users.map(user => user.userId) },\n },\n });\n \n return response.count\n }\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17090572/"
] |
74,376,755 | <p>I am using PrimeFaces File Upload with mode="advanced" and multiple="true" just like the demo shows here <a href="https://www.primefaces.org/showcase/ui/file/upload/multiple.xhtml?jfwid=50dd6" rel="nofollow noreferrer">https://www.primefaces.org/showcase/ui/file/upload/multiple.xhtml?jfwid=50dd6</a></p>
<p>In this case, the user uploads multiple files and is shown the files to edit the list. The user must then click "upload" to upload the files. If they fail to click upload and submit the form on the page, the files don't get uploaded. I know about the auto="true" option, but we want to keep the ability to edit the list.</p>
<p>How can I prevent form submission if the user has pending file uploads?</p>
| [
{
"answer_id": 74421031,
"author": "Melloware",
"author_id": 502366,
"author_profile": "https://Stackoverflow.com/users/502366",
"pm_score": 0,
"selected": false,
"text": "onAdd"
},
{
"answer_id": 74450550,
"author": "Jasper de Vries",
"author_id": 880619,
"author_profile": "https://Stackoverflow.com/users/880619",
"pm_score": 3,
"selected": true,
"text": "onclick"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4816848/"
] |
74,376,768 | <p>I've been learning Java for one week now and I came across this solution for my homework, but I just can't understand how it calculates the sum of numbers.</p>
<p>I've tried to understand it for 1 hour now and I feel so dumb right now.</p>
<p>I pretty much understand that <code>for</code> add to <code>x + 1</code> every time when the length of the entered number is lower than <code>x</code> which is <code>0</code>. But I just can't get what the code inside <code>for</code> does.</p>
<pre class="lang-java prettyprint-override"><code>sum += Integer.parseInt(String.valueOf(a.charAt(x)));
</code></pre>
<p>Here is the full code</p>
<pre class="lang-java prettyprint-override"><code>public class Loader {
public static void main(String[] args) {
System.out.println(sum(8313));
}
public static Integer sum(Integer number){
String a = Integer.toString(number);
Integer sum = 0;
for(int x = 0; x < a.length(); x++) {
sum += Integer.parseInt(String.valueOf(a.charAt(x)));
}
return sum;
}
}
</code></pre>
| [
{
"answer_id": 74421031,
"author": "Melloware",
"author_id": 502366,
"author_profile": "https://Stackoverflow.com/users/502366",
"pm_score": 0,
"selected": false,
"text": "onAdd"
},
{
"answer_id": 74450550,
"author": "Jasper de Vries",
"author_id": 880619,
"author_profile": "https://Stackoverflow.com/users/880619",
"pm_score": 3,
"selected": true,
"text": "onclick"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459874/"
] |
74,376,779 | <p>I was trying to implement a <code>E lower(E e)</code> method to a BST (Binary Search Tree) data structure. It should work like this - (return the greatest element in this set strictly less than the given element, or null if there is no such element). I am stuck at this problem. Any tips?</p>
<p>For example, if I have a binary tree like: calling method lower(6), should return 5</p>
<p>5
/ <br />
1 6</p>
<p>My code example (Java)</p>
<pre class="lang-java prettyprint-override"><code>public E lower(E e)
{
if (e== null) {
throw new IllegalArgumentException("Element is null in lower(E element)");
}
BstNode<E> node = root;
BstNode<E> parent = null;
BstNode<E> ch = null;
int cmp = c.compare(e, root.element);
while(node != null)
{
if (cmp > 0)
{
if(node.right != null)
{
node = node.right;
}
else
return node.element;
}
else
{
if(node.left != null)
{
node = node.left;
}
else
///DONT KNOW WHAT TO DO HERE
}
}
return null;
}
</code></pre>
| [
{
"answer_id": 74377122,
"author": "Omar Ahmed",
"author_id": 20192533,
"author_profile": "https://Stackoverflow.com/users/20192533",
"pm_score": 1,
"selected": false,
"text": " 5\n / \\\n 3 8\n / \\ /\n 2 4 6\n \\\n 7\n"
},
{
"answer_id": 74377897,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 0,
"selected": false,
"text": "e"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19915802/"
] |
74,376,797 | <p>Trying to type check this code (which works perfectly fine):</p>
<pre><code>x = list(range(10))
for func in min, max, len:
print(func(x))
</code></pre>
<p>results in the following error:</p>
<blockquote>
<p>main.py:3: error: Cannot call function of unknown type</p>
</blockquote>
<p>How should this be handled?</p>
| [
{
"answer_id": 74377122,
"author": "Omar Ahmed",
"author_id": 20192533,
"author_profile": "https://Stackoverflow.com/users/20192533",
"pm_score": 1,
"selected": false,
"text": " 5\n / \\\n 3 8\n / \\ /\n 2 4 6\n \\\n 7\n"
},
{
"answer_id": 74377897,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 0,
"selected": false,
"text": "e"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5218354/"
] |
74,376,811 | <p>I have a state, that I only want to change when a certain funcitonal component is initialised. So I intend to do somethin like this:</p>
<pre class="lang-js prettyprint-override"><code>export default function SalesFeedPage(){
const {salesFeed} = useSelector((state) => state.feedReducer);
const dispatch = useDispatch();
// i want to do sth like this
// useEffect(() => dispatch(loadSalesFeed()), []);
// or
// dispatch(loadSalesFeed());
return (
<div>
hello
{salesFeed}
</div>
)
}
</code></pre>
<p>This doesn't work since it infinitely re-renders the SalesFeedPage.</p>
<p>Is there a way to achieve what I want in a funcitonal component?</p>
| [
{
"answer_id": 74377122,
"author": "Omar Ahmed",
"author_id": 20192533,
"author_profile": "https://Stackoverflow.com/users/20192533",
"pm_score": 1,
"selected": false,
"text": " 5\n / \\\n 3 8\n / \\ /\n 2 4 6\n \\\n 7\n"
},
{
"answer_id": 74377897,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 0,
"selected": false,
"text": "e"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266336/"
] |
74,376,815 | <p>I'm trying to learn Kivy and I can't figure why the add_key() function work with the Checkbox but not with the Spinner ?</p>
<p>I got : AttributeError: 'NoneType' object has no attribute 'add_key' ?</p>
<p>Both custom widget's structure seems identical, the add_key function must be stored in the "MainWidget".
Curiously it work with the checkbox but not with the spinner ?!</p>
<p>Minimal code corresponding to my problem :</p>
<pre><code>from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
selection = {}
pizza = ["margarita", "vegetarian", "american", "3 cheeses"]
KV="""
<Selection@BoxLayout>:
orientation: "horizontal"
label_txt: ""
key_name: ""
Label:
text: root.label_txt
Spinner:
id: spin_id
text: ""
on_text: app.root.add_key(root.key_name, self.text)
<Radio_op@BoxLayout>:
orientation: "horizontal"
op: ""
label_op: ""
Label:
text: root.label_op
CheckBox:
group:"topping"
on_active: app.root.add_key("topping", root.op)
<MainScreen>:
BoxLayout:
orientation: "vertical"
Selection:
id: pizza_sel
label_txt: "pizza"
key_name: "pizza"
Label:
text: "Choose topping:"
BoxLayout:
orientation: "horizontal"
Radio_op:
label_op:"cream"
op: "cream"
Radio_op:
label_op:"cheese"
op: "cheese"
Radio_op:
label_op:"tomatoes"
op: "tomatoes"
BoxLayout:
Label:
id: pizza_lbl
Label:
id: topping_lbl
"""
class MainScreen(Screen):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.ids.pizza_sel.ids.spin_id.text = pizza[0]
self.ids.pizza_sel.ids.spin_id.values = pizza
def add_key(self, name, text):
selection[name] = text
#self.ids.pizza_lbl.text = selection["pizza"]
self.ids.topping_lbl.text = selection["topping"]
Builder.load_string(KV)
class MyApp(App):
def build(self):
return MainScreen()
if __name__ == '__main__':
MyApp().run()`
</code></pre>
<p>Error code :</p>
<pre><code> File "c:\Users\florian\Desktop\Local\Scripts python\Utilitaire de puissance V3\help.py", line 76, in <module>
MyApp().run()
File "C:\Users\florian\Anaconda3\lib\site-packages\kivy\app.py", line 954, in run
self._run_prepare()
File "C:\Users\florian\Anaconda3\lib\site-packages\kivy\app.py", line 924, in _run_prepare
root = self.build()
File "c:\Users\florian\Desktop\Local\Scripts python\Utilitaire de puissance V3\help.py", line 73, in build
return MainScreen()
File "c:\Users\florian\Desktop\Local\Scripts python\Utilitaire de puissance V3\help.py", line 61, in __init__
self.ids.pizza_sel.ids.spin_id.text = pizza[0]
File "kivy\weakproxy.pyx", line 35, in kivy.weakproxy.WeakProxy.__setattr__
File "kivy\properties.pyx", line 520, in kivy.properties.Property.__set__
File "kivy\properties.pyx", line 567, in kivy.properties.Property.set
File "kivy\properties.pyx", line 606, in kivy.properties.Property._dispatch
File "kivy\_event.pyx", line 1307, in kivy._event.EventObservers.dispatch
File "kivy\_event.pyx", line 1189, in kivy._event.EventObservers._dispatch
File "C:\Users\florian\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 55, in custom_callback
exec(__kvlang__.co_value, idmap)
File "<string>", line 11, in <module>
AttributeError: 'NoneType' object has no attribute 'add_key'
</code></pre>
<p>When I comment the Spinner on_text attribute, the checkbox is working fine :
<a href="https://i.stack.imgur.com/mgA0q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mgA0q.png" alt="enter image description here" /></a></p>
<p>Please, can anyone explain me why ? Thank you.</p>
| [
{
"answer_id": 74377122,
"author": "Omar Ahmed",
"author_id": 20192533,
"author_profile": "https://Stackoverflow.com/users/20192533",
"pm_score": 1,
"selected": false,
"text": " 5\n / \\\n 3 8\n / \\ /\n 2 4 6\n \\\n 7\n"
},
{
"answer_id": 74377897,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 0,
"selected": false,
"text": "e"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20061618/"
] |
74,376,824 | <p>I have a sequence <code>s</code> where I expect each proceeding value to be either the same as the previous one or +1.</p>
<pre><code>s = c(1,1,1,1,2,2,2,-2,3,3,4,8,8,8,9,5,5,12,6)
</code></pre>
<p>What I want:</p>
<pre><code>1,1,1,1,2,2,2,3,3,4,5,5,6
</code></pre>
<p>I've solved this with the following code:</p>
<pre><code>counter = 2
repeat{
if(s[counter] == s[counter-1] | s[counter] == s[counter-1]+1){
counter = counter+1
} else{
s = s[-counter]
}
if(counter >= length(s)) break
}
</code></pre>
<p>which however appears quite 'dirty' and inefficient. Is there a computationally less time-consuming solution?</p>
| [
{
"answer_id": 74376982,
"author": "MrFlick",
"author_id": 2372064,
"author_profile": "https://Stackoverflow.com/users/2372064",
"pm_score": 5,
"selected": true,
"text": "s = c(1,1,1,1,2,2,2,-2,3,3,4,8,8,8,9,5,5,12,6)\nincreasing_seq <- function(x) {\n keep <- logical(length(x))\n current <- x[1]\n for (i in seq_along(x)) {\n if (x[i] == current) {\n keep[i] <- TRUE\n } else if (x[i] == current + 1) {\n current <- current + 1\n keep[i] <- TRUE\n }\n }\n x[keep]\n}\nincreasing_seq(s)\n# [1] 1 1 1 1 2 2 2 3 3 4 5 5 6\n"
},
{
"answer_id": 74377013,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 4,
"selected": false,
"text": "Reduce"
},
{
"answer_id": 74377047,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 3,
"selected": false,
"text": "Rcpp::cppFunction('LogicalVector foo(NumericVector s) {\n int n = s.size();\n Rcpp::LogicalVector keep(n);\n keep[0] = 1;\n int last = 0;\n for (int i = 1; i < n; i++) {\n if (s[i] - s[last] == 0) {\n keep[i] = 1;\n } else if (s[i] - s[last] == 1) {\n keep[i] = 1;\n last = i;\n } \n }\n return keep;\n}')\n\n\ns[foo(s)]\n# [1] 1 1 1 1 2 2 2 3 3 4 5 5 6\n"
},
{
"answer_id": 74397685,
"author": "Anastasiya-Romanova 秀",
"author_id": 3397819,
"author_profile": "https://Stackoverflow.com/users/3397819",
"pm_score": 1,
"selected": false,
"text": "s"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11738400/"
] |
74,376,835 | <p>I am finding the difference between 2 dates in years, but when I select the <strong>31st</strong> date it shows an invalid date so the difference is <code>NaN</code>.</p>
<p>When I use other dates it shows the correct result.</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 selectedValue = moment('31-8-2022');
const today = moment();
const yearDiff = today.diff(selectedValue, "year");
console.log(yearDiff);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74377041,
"author": "Brhaka",
"author_id": 11578778,
"author_profile": "https://Stackoverflow.com/users/11578778",
"pm_score": 1,
"selected": false,
"text": "const selectValue = moment('2022-08-31'); // 2022-08-31 instead of 31-8-2022\nconst today = moment();\nconst yearDiff = today.diff(selectValue, \"year\");\nconsole.log(yearDiff);\n"
},
{
"answer_id": 74383222,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "'DD-MM-YYYY'"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460020/"
] |
74,376,841 | <h3>The data</h3>
<p>I have JSON data that I want to use in a PDF-report. The PDF-report is created from HTML.</p>
<pre class="lang-json prettyprint-override"><code>[
{
"title": "Chapter 1",
"text": "Some large text"
},
{
"title": "Chapter 2",
"text": "Some large text"
}
]
</code></pre>
<h3>Format of the report page</h3>
<p>All pages has the following format.</p>
<p><a href="https://i.stack.imgur.com/Nfi5W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nfi5W.png" alt="Sizes of page" /></a></p>
<h3>What I need</h3>
<p>I need to add the text within the content of the page. But when the text is exceeding it has to jump to the next page and keeps the same format. Does anyone have an idea how to accomplish this?</p>
| [
{
"answer_id": 74409477,
"author": "Yang",
"author_id": 20335592,
"author_profile": "https://Stackoverflow.com/users/20335592",
"pm_score": 0,
"selected": false,
"text": "<body style=\"background:rgba(100,100,100,0.5);\">\n<button style=\"position:fixed; width:20; height:20; left:80%; top:10%\" onclick=\"Ms()\">\n X\n </button>\n<p style=\"position:fixed; width:60%; height:80%; left:20%; top:10% ;overflow:scroll; background:rgba(100,100,100,0.8)\" id=\"p1\">\ntest-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>test-overflow1234567890-=-0987654321234567890-=-0987654321<br><br>\n</p>\n \n<!--script language=\"javascript\">\n function close()\n {\n document.getElementById(\"p1\").display: none;\n }\n</script-->\n<script language=\"javascript\">\nfunction Ms() //声明标识符\n{\n//document.getElementById(\"p1\").visibility=hidden;\ndocument.getElementById(\"p1\").innerHTML=\"I do not know why it can not be hidden.\";\n}\n"
},
{
"answer_id": 74453397,
"author": "pkExec",
"author_id": 1543677,
"author_profile": "https://Stackoverflow.com/users/1543677",
"pm_score": 2,
"selected": false,
"text": "<div id=\"content\">\n\n</div>\n<div id=\"container\">\n\n</div>\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9401138/"
] |
74,376,855 | <p>friends. I want a function, when I give it arrays, that function will seperate positive and negative numbers from those arrays and push them to negativeNumbers or positiveNumbers.</p>
<p>But as you see below, I can do it for arrayOne. If I want do it with arrayTwo, I have to copy all codes again. Is there any way, I create one function, and use that function for all arrays?</p>
<p>For example, checkValue(arrayOne), checkValue(arrayTwo), etc.</p>
<p>Thank you in advance!</p>
<pre><code>const negativeNumbers = []
const positiveNumbers = []
const arrayOne = [-2, 5, -3, 6]
const arrayTwo = [-12, 15, -13, 16]
const checkValue = arrayOne.forEach((element) => {
if (element<0){
negativeNumbers.push(element)
}
if (element>=0) {
positiveNumbers.push(element)
}
})
console.log(positiveNumbers)
console.log(negativeNumbers)
</code></pre>
| [
{
"answer_id": 74376938,
"author": "IT goldman",
"author_id": 3807365,
"author_profile": "https://Stackoverflow.com/users/3807365",
"pm_score": 2,
"selected": true,
"text": "[array, array]"
},
{
"answer_id": 74377162,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 0,
"selected": false,
"text": "function splitNegativePositive(array){\n return {\n positives: array.filter(n => n >= 0),\n negatives: array.filter(n => n < 0),\n }\n}\n\nconst input1 = [-1, 5, 9, 0, -3];\nconst input2 = [-10, -5, 7, 0, 3];\n\nconsole.log({\n input1,\n input1Output: splitNegativePositive(input1),\n input2,\n input2Output: splitNegativePositive(input2),\n})"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17694846/"
] |
74,376,885 | <p>I have a two inputs in my child component, I would like to pass the event of the inputs to my parent component. In the parent component I have a function which will handle the submission. I have the two useState in the parent component, just in case I need to use it in the future in other condition to ensure the user is logged in. I am wondering how to achieve this ? or am I taking the wrong approach with having the usestates in my parent component ?</p>
<pre><code>import { useState } from "react";
import Child from './Child'
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
const loginhandler = ()=>{
if (!login && !password){
console.log("alert error")
} else {
console.log('you are logged in')
}
}
return (
<>
<Child/>
</>
);
}
</code></pre>
<pre><code>import { useState } from "react";
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
return (
<>
<input
placeholder="Id"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
<input
placeholder="Password"
value={password}
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
</>
);
}
</code></pre>
| [
{
"answer_id": 74376938,
"author": "IT goldman",
"author_id": 3807365,
"author_profile": "https://Stackoverflow.com/users/3807365",
"pm_score": 2,
"selected": true,
"text": "[array, array]"
},
{
"answer_id": 74377162,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 0,
"selected": false,
"text": "function splitNegativePositive(array){\n return {\n positives: array.filter(n => n >= 0),\n negatives: array.filter(n => n < 0),\n }\n}\n\nconst input1 = [-1, 5, 9, 0, -3];\nconst input2 = [-10, -5, 7, 0, 3];\n\nconsole.log({\n input1,\n input1Output: splitNegativePositive(input1),\n input2,\n input2Output: splitNegativePositive(input2),\n})"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19400358/"
] |
74,376,903 | <p>My use case is to convert text to speech using Azure and then play it into a virtual microphone.<br></p>
<h1>option 1 - with an intermediate .wav file</h1>
<p>I tried both steps manually on a Jupiter notebook. <br>
The problem is, the output .wav file of Azure cannot be played directly on the python
"error: No file 'file.wav' found in working directory". When I restart the python kernal, audio can be played.<br></p>
<h3>text-to-speech</h3>
<pre><code>audio_config = speechsdk.audio.AudioOutputConfig(filename="file.wav")
...
speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
</code></pre>
<h3>audio play</h3>
<pre><code>mixer.init(devicename = 'Line 1 (Virtual Audio Cable)')
mixer.music.load("file.wav")
mixer.music.play()
</code></pre>
<h1>option 2 - direct stream to audio device</h1>
<p>I tried to configure the audio output device of azure SDK.
this method worked for output devices. but when I add an ID of the virtual microphone, it won't play any sound.</p>
<pre><code>audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=False,device_name="{0.0.0.00000000}.{9D30BDBF-1418-4AFC-A709-CD4C431833E2}")
</code></pre>
<h3>Also it will be much better if there is any other method that can direct the audio to a virtual microphone instead of the speaker.</h3>
| [
{
"answer_id": 74376938,
"author": "IT goldman",
"author_id": 3807365,
"author_profile": "https://Stackoverflow.com/users/3807365",
"pm_score": 2,
"selected": true,
"text": "[array, array]"
},
{
"answer_id": 74377162,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 0,
"selected": false,
"text": "function splitNegativePositive(array){\n return {\n positives: array.filter(n => n >= 0),\n negatives: array.filter(n => n < 0),\n }\n}\n\nconst input1 = [-1, 5, 9, 0, -3];\nconst input2 = [-10, -5, 7, 0, 3];\n\nconsole.log({\n input1,\n input1Output: splitNegativePositive(input1),\n input2,\n input2Output: splitNegativePositive(input2),\n})"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12261081/"
] |
74,376,921 | <p>I've alreaedy looked for a similar question to mine but I couldn't found it.
Whenever you find one, let me know.</p>
<p>I have a df that looks like (in reality this df has three columns and more than 1000 rows):</p>
<pre><code>
Name, Value
Markus, 2
Markus, 4
Markus, 1
Caesar, 77
Caesar, 70
Brutus, 3
Nero, 4
Nero, 9
Nero, 10
Nero, 19
</code></pre>
<p>How can I create for each match (depending on Name) an own csv file?
I don't know how to approach this.</p>
<p>In this case the end result should be four csv files with the name form the Name column:</p>
<pre><code>Markus.csv
Caesar.csv
Brutus.csv
Nero.csv
</code></pre>
<p>I'm thankful for any advice.</p>
| [
{
"answer_id": 74377001,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74377158,
"author": "chemdork123",
"author_id": 9664796,
"author_profile": "https://Stackoverflow.com/users/9664796",
"pm_score": 0,
"selected": false,
"text": "dplyr"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16371833/"
] |
74,376,956 | <p><strong>Minimal reproducible code:</strong></p>
<pre class="lang-dart prettyprint-override"><code>enum Foo {
a,
b;
String get name {
switch (this) {
case Foo.a: return 'A';
case Foo.b: return 'B';
}
}
}
void main() {
printEnum<Foo>(Foo.values);
}
void printEnum<T extends Enum>(List<T> list) {
for (var e in list) {
print(e.name);
}
}
</code></pre>
<p>The <code>for</code> loop prints</p>
<pre><code>a
b
</code></pre>
<p>But I wanted it to print</p>
<pre><code>A
B
</code></pre>
<p>So, how do I override the <code>name</code> property in the enum?</p>
<hr />
<h4>Note:</h4>
<p>Using <code>(e as Foo).name</code> will solve the issue, but I have many enums in my project, so I can't cast them like this.</p>
<p>Also, please don't post answers like, use <code>toUpperCase()</code>, etc, because I just provided a simple example, but in real world, things are quite different.</p>
| [
{
"answer_id": 74377485,
"author": "AryaveerSR",
"author_id": 20459167,
"author_profile": "https://Stackoverflow.com/users/20459167",
"pm_score": 1,
"selected": false,
"text": "e"
},
{
"answer_id": 74377964,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 3,
"selected": true,
"text": "name"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12483095/"
] |
74,376,972 | <p>If I have below table</p>
<pre><code>+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
| a| b| id|m2000|m2001|m2002|m2003|m2004|m2005
+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
|a |world| 1| 0| 0| 1| 0| 0| 1|
+-----+-----+---+-----+-----+-----+-----+-----+-----+-----+
</code></pre>
<p>How do I create a new dataframe like below that checks cols m2000 to m2014 and sees if any these fields are 1. It then creates the below table where 10/10 is static. 2002 and 2005 is used as it is only 2 columns between m2000 and m2014 where 1 is in above table.</p>
<pre><code>|id | year | yearend |
|1 | 10/10/2002| 12/12/2005|
|1 | 10/10/2002| 12/12/2005|
</code></pre>
<p>code to create first dataframe</p>
<pre><code>from pyspark.shell import spark
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
data2 = [("a", "world", "1", 0, 0, 1,0,0,1),
]
schema = StructType([ \
StructField("a", StringType(), True), \
StructField("b", StringType(), True), \
StructField("id", StringType(), True), \
StructField("m2000", IntegerType(), True), \
StructField("m2001", IntegerType(), True), \
StructField("m2002", IntegerType(), True), \
StructField("m2003", IntegerType(), True), \
StructField("m2004", IntegerType(), True), \
StructField("m2005", IntegerType(), True), \
])
df = spark.createDataFrame(data=data2, schema=schema)
df.printSchema()
df.show(truncate=False)
</code></pre>
| [
{
"answer_id": 74377485,
"author": "AryaveerSR",
"author_id": 20459167,
"author_profile": "https://Stackoverflow.com/users/20459167",
"pm_score": 1,
"selected": false,
"text": "e"
},
{
"answer_id": 74377964,
"author": "lrn",
"author_id": 2156621,
"author_profile": "https://Stackoverflow.com/users/2156621",
"pm_score": 3,
"selected": true,
"text": "name"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9390633/"
] |
74,376,985 | <p>`</p>
<pre><code>namespace Program
{
class Program
{
static void Main(string[] args)
{
Console.Write("s: ");
string s = Console.ReadLine();
int count = 0;
string[] sp = s.Split(new Char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s1 in sp)
{
if (s[s.Length-1] == 'А')
count++;
}
Console.WriteLine(count);
}
}
}
</code></pre>
<p>`</p>
<p>My code works, but only if the first character is "A" I need it to work even if the first character is not A. Help</p>
| [
{
"answer_id": 74377048,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "string[] arr = new string[] { \"Abc\", \"axy\", \"Abd\"};\nint count = 0;\nforeach (string s1 in arr)\n{\n if (s1.Contains('A'))\n count++;\n}\n"
},
{
"answer_id": 74377093,
"author": "YungDeiza",
"author_id": 19214431,
"author_profile": "https://Stackoverflow.com/users/19214431",
"pm_score": 1,
"selected": false,
"text": "ToUpper()"
},
{
"answer_id": 74377095,
"author": "Shinva",
"author_id": 1055144,
"author_profile": "https://Stackoverflow.com/users/1055144",
"pm_score": 2,
"selected": false,
"text": "string s = Console.ReadLine();\nvar count = s.Split(' ').Count(c=>c.Contains('A'));\nConsole.WriteLine(count); \n"
},
{
"answer_id": 74377408,
"author": "Jan_V",
"author_id": 352640,
"author_profile": "https://Stackoverflow.com/users/352640",
"pm_score": 0,
"selected": false,
"text": "numberOfMatches"
},
{
"answer_id": 74377456,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 0,
"selected": false,
"text": "Count"
},
{
"answer_id": 74378817,
"author": "lidqy",
"author_id": 5739443,
"author_profile": "https://Stackoverflow.com/users/5739443",
"pm_score": 0,
"selected": false,
"text": "// 1 2 3 4 5 6 7\nvar str = \"That fat fox started to accumulate marias fancy cheddar\";\nchar f = 'A';\nvar cnt = 0;\nvar srch = f;\n\nforeach (var c in str) {\n if (char.ToUpperInvariant(c) == char.ToUpperInvariant(srch)) {\n if (srch == f) {\n cnt++;\n srch = ' ';\n }\n else {\n srch = f;\n }\n }\n}\nConsole.WriteLine(\"{0} words containing '{1}' in '{2}' (ignoring casing)\", cnt, f, str);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74376985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460210/"
] |
74,377,007 | <p>I face a so strange problem that occurs below on the remote tomcat server but works well on the local.</p>
<pre><code>org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.apache.doris.analysis.SqlParser.getSymbolFactory()Ljava_cup/runtime/SymbolFactory;
</code></pre>
<p>I know most related topics about this issue are package duplicate、dependency conflict、 etc.
But actually, I've tried to eliminate these factors. The war is identical on both local and remote. I also decompile the jar which includes SqlParser class, and It's truly existed and includes the getSymbolFactory function.</p>
<p>The most strange thing is when I copy that to local for running it's ok. At first, I suspected it was about the version of tomcat. But after using the same version of the Tomcat on the remote, the error still exists.</p>
<p>By the way, the jar includes warning class that is imported by the system jar type. The jars are placed the resource/lib/* . It's related to this?</p>
<p>Maven config for import system jar</p>
<pre><code><dependency>
<groupId>net.sourceforge.czt.dev</groupId>
<artifactId>java-cup</artifactId>
<version>0.11-a-czt02-cdh</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/java-cup-runtime-0.11-a-czt01-cdh.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.doris</groupId>
<artifactId>fe-core</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/fe-core-1.0-SNAPSHOT.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.doris</groupId>
<artifactId>fe-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/fe-common-1.0-SNAPSHOT.jar</systemPath>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>ftl</nonFilteredFileExtension>
</nonFilteredFileExtensions>
<outputDirectory>target</outputDirectory>
<webResources>
<resource>
<filtering>true</filtering>
<directory>src/main/webapp/WEB-INF</directory>
<includes>
<include>**/*.xml</include>
</includes>
<targetPath>/WEB-INF</targetPath>
</resource>
<resource>
<directory>src/main/resources/lib</directory>
<targetPath>WEB-INF/lib</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
</code></pre>
<p>For now, the most relevant thread I found is this:
<a href="https://stackoverflow.com/questions/8168052/java-lang-nosuchmethoderror-when-the-method-definitely-exists">java.lang.NoSuchMethodError when the method definitely exists</a>
I have no clue how to troubleshoot this, anyone can help me?</p>
| [
{
"answer_id": 74377048,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "string[] arr = new string[] { \"Abc\", \"axy\", \"Abd\"};\nint count = 0;\nforeach (string s1 in arr)\n{\n if (s1.Contains('A'))\n count++;\n}\n"
},
{
"answer_id": 74377093,
"author": "YungDeiza",
"author_id": 19214431,
"author_profile": "https://Stackoverflow.com/users/19214431",
"pm_score": 1,
"selected": false,
"text": "ToUpper()"
},
{
"answer_id": 74377095,
"author": "Shinva",
"author_id": 1055144,
"author_profile": "https://Stackoverflow.com/users/1055144",
"pm_score": 2,
"selected": false,
"text": "string s = Console.ReadLine();\nvar count = s.Split(' ').Count(c=>c.Contains('A'));\nConsole.WriteLine(count); \n"
},
{
"answer_id": 74377408,
"author": "Jan_V",
"author_id": 352640,
"author_profile": "https://Stackoverflow.com/users/352640",
"pm_score": 0,
"selected": false,
"text": "numberOfMatches"
},
{
"answer_id": 74377456,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 0,
"selected": false,
"text": "Count"
},
{
"answer_id": 74378817,
"author": "lidqy",
"author_id": 5739443,
"author_profile": "https://Stackoverflow.com/users/5739443",
"pm_score": 0,
"selected": false,
"text": "// 1 2 3 4 5 6 7\nvar str = \"That fat fox started to accumulate marias fancy cheddar\";\nchar f = 'A';\nvar cnt = 0;\nvar srch = f;\n\nforeach (var c in str) {\n if (char.ToUpperInvariant(c) == char.ToUpperInvariant(srch)) {\n if (srch == f) {\n cnt++;\n srch = ' ';\n }\n else {\n srch = f;\n }\n }\n}\nConsole.WriteLine(\"{0} words containing '{1}' in '{2}' (ignoring casing)\", cnt, f, str);\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8034193/"
] |
74,377,016 | <p>I'm trying to create an interface that other classes in MATLAB will inherit. This interface has a property that holds a function_handle value. The problem I'm running into is that, upon instantiating a concrete class that inherits from this class, I get the message: <code>Error defining property 'MyFuncHandle' of class 'IMyInterfaceClass'. Unable to construct default object of class function_handle.</code></p>
<p>The interface class looks something like this:</p>
<pre><code>classdef (Abstract) IMyInterfaceClass < handle
properties (Abstract)
MyFuncHandle(1,1) function_handle
end
methods (Abstract, Access = public)
% Some abstract methods declared here
end
end
</code></pre>
<p>With another class inheriting the interface like this:</p>
<pre><code>classdef (Abstract) MyClassThatInheritsTheInterface < IMyInterfaceClass & SomeOtherAbstractClass
properties
MyFuncHandle
end
methods (Abstract)
% Some abstract methods declared here
end
methods
function this = MyClassThatInheritsTheInterface()
this@SomeOtherAbstractClass();
end
% Some concrete methods declared here
end
end
</code></pre>
<p>And, ultimately, a concrete subclass that inherits from <code>MyClassThatInheritsTheInterface</code>.</p>
<p>I've tried changing the property declaration in <code>IMyInterfaceClass</code> to:</p>
<pre><code> properties (Abstract)
MyFuncHandle(1,1) function_handle = function_handle.empty
end
</code></pre>
<p>But, that doesn't work. I've also tried just setting it to a default value like this:</p>
<pre><code> properties (Abstract)
MyFuncHandle(1,1) function_handle = @ode15s
end
</code></pre>
<p>That doesn't work either.</p>
<p>Is there any way to get this to work, while keeping the type-checking on <code>MyFuncHandle</code> in <code>IMyInterfaceClass</code>? Obviously, getting rid of the type check and leaving it as a duck-typed property would eliminate the error but would not ensure that the value in the property is a function_handle.</p>
| [
{
"answer_id": 74377500,
"author": "Wolfie",
"author_id": 3978545,
"author_profile": "https://Stackoverflow.com/users/3978545",
"pm_score": 3,
"selected": true,
"text": "classdef (Abstract) IMyInterfaceClass < handle\n properties \n MyFuncHandle(1,1) function_handle = @(varargin) disp([])\n end\n methods (Abstract, Access = public)\n % Some abstract methods declared here\n end\nend\n"
},
{
"answer_id": 74378461,
"author": "Edric",
"author_id": 88076,
"author_profile": "https://Stackoverflow.com/users/88076",
"pm_score": 2,
"selected": false,
"text": "properties\n SomeFcn {mustBeA(SomeFcn, \"function_handle\")}\nend\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610638/"
] |
74,377,046 | <p>I had to generate random password for temporary entry/login purpose in C#. Now I need to only send 6 digits but no more characters, or special characters. New to the C# world. Hence, I am providing what I have so far.</p>
<p>helper.cs</p>
<pre><code>public static string GenerateRandomPassword()
{
int numsLength = 6;
const string nums = "0123456789";
StringBuilder sb = new StringBuilder();
Random rnd = new Random();
for (int i = 0; i < charLength; i++)
{
int index = rnd.Next(chars.Length);
sb.Append(chars[index]);
}
int numindex = rnd.Next(nums.Length);
sb.Append(nums[numindex]);
return sb.ToString();
}
</code></pre>
<p>I think my logic is still not right. I know that I should not use String Builder since I only want to send digits. Can anyone help me and figure out my mistake by editing the above codes?</p>
| [
{
"answer_id": 74377177,
"author": "Denis Schaf",
"author_id": 8463053,
"author_profile": "https://Stackoverflow.com/users/8463053",
"pm_score": 2,
"selected": false,
"text": "Random rnd = new Random();\n\npublic static string GenerateRandomPassword()\n{\n int numsLength = 6;\n string sixDigitString = \"\";\n for (int i = 0; i < charLength; i++)\n {\n //this takes the existing string and adds a random number to it. Do this as many times as you need to\n sixDigitString += rnd.Next(0,9).ToString();\n }\n return sixDigitString;\n}\n"
},
{
"answer_id": 74377231,
"author": "freifede",
"author_id": 646283,
"author_profile": "https://Stackoverflow.com/users/646283",
"pm_score": 1,
"selected": true,
"text": "public static string GenerateRandomPassword()\n{\n int numsLength = 6;\n\n const string nums = \"0123456789\";\n string tempPass = string.Empty;\n Random rnd = new Random();\n\n for (int i = 1; i <= numsLength; i++)\n {\n int index = rnd.Next(nums.Length);\n tempPass += nums[index];\n }\n\n return tempPass;\n}\n"
},
{
"answer_id": 74377306,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 0,
"selected": false,
"text": " Random rnd = new Random();\n String passSixDigit = rnd.Next(0, 999999).ToString(\"000000\");\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20168338/"
] |
74,377,060 | <p>I developed an Outlook Add-in with a Taskpane and a Command Add-in, using the Yo Office Tool with a Web Add-in and Javascript as Code base. So far everything works like we wanted it except for the Command Add-in where we would like to visually tell the user the actual state of the command. Like with either a changed Icon and Text combination (aka a Toggle Button like the Outlook Dark Mode Add-in) or a Border around the Add-in Command Button. Just like it, right now, works for embedded outlook Add-ins and COM Add-ins too. See this screenshot: <a href="https://i.stack.imgur.com/boPr2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/boPr2.png" alt="Outlook Add-ins with Toggle function or Button Border" /></a></p>
<p>I am searching the Web for days now for an answer or a hint. Also, I have gone through the Add-in samples but could not find something which would lead me into the right direction. I've read on a post here <a href="https://stackoverflow.com/questions/71329066/outlook-add-in-dynamic-control-button-highlight-on-click">Outlook Add-in - Dynamic Control Button Highlight On Click</a> that for Web Add-ins this function is not implemented yet, same as Callback functionality. But my Web based Add-in do have and use Callbacks, and they work. So my Question is: Is there a way how I can use Button Toggle or Button Border with a Web Add-in, or does this only work with COM Add-ins?</p>
| [
{
"answer_id": 74377177,
"author": "Denis Schaf",
"author_id": 8463053,
"author_profile": "https://Stackoverflow.com/users/8463053",
"pm_score": 2,
"selected": false,
"text": "Random rnd = new Random();\n\npublic static string GenerateRandomPassword()\n{\n int numsLength = 6;\n string sixDigitString = \"\";\n for (int i = 0; i < charLength; i++)\n {\n //this takes the existing string and adds a random number to it. Do this as many times as you need to\n sixDigitString += rnd.Next(0,9).ToString();\n }\n return sixDigitString;\n}\n"
},
{
"answer_id": 74377231,
"author": "freifede",
"author_id": 646283,
"author_profile": "https://Stackoverflow.com/users/646283",
"pm_score": 1,
"selected": true,
"text": "public static string GenerateRandomPassword()\n{\n int numsLength = 6;\n\n const string nums = \"0123456789\";\n string tempPass = string.Empty;\n Random rnd = new Random();\n\n for (int i = 1; i <= numsLength; i++)\n {\n int index = rnd.Next(nums.Length);\n tempPass += nums[index];\n }\n\n return tempPass;\n}\n"
},
{
"answer_id": 74377306,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 0,
"selected": false,
"text": " Random rnd = new Random();\n String passSixDigit = rnd.Next(0, 999999).ToString(\"000000\");\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459834/"
] |
74,377,138 | <p>I feel at the outset I should mention that this is a purely personal project.</p>
<p>I am looking to scrape car data from a well known car website. Their website for each car "product card" is structured as follows:</p>
<pre><code><section class="product-card-details">
<h3 class="product-card-details__title">
Mercedes-Benz A-Class
</h3>
<p class="product-card-details__subtitle">
1.3 A 200 AMG LINE 5d 161 BHP | 14-DAYS MONEY BACK GUARANTEE*
</p>
<p class="product-card-details__attention-grabber">
***FREE 3 MONTHS WARRANTY***
</p>
<ul class="listing-key-specs">
<li class="atc-type-picanto--medium">2018 (68 reg)</li>
<li class="atc-type-picanto--medium">Hatchback</li>
<li class="atc-type-picanto--medium">39,009 miles</li>
<li class="atc-type-picanto--medium">1.3L</li>
<li class="atc-type-picanto--medium">161BHP</li>
<li class="atc-type-picanto--medium">Automatic</li>
<li class="atc-type-picanto--medium">Petrol</li>
<li class="atc-type-picanto--medium">1 owner</li>
<li class="atc-type-picanto--medium">ULEZ</li>
</ul>
</section>
</code></pre>
<p>I am able to extract the title and the subtitle in a loop quite easily as follows:</p>
<pre><code>#Find Elements by Class Name. Create array of all cards
car_list = driver.find_elements(By.CLASS_NAME, "product-card-details")
titles = []
subtitles = []
for car in car_list:
title = car.find_element(By.CLASS_NAME, "product-card-details__title").text
subtitle = car.find_element(By.CLASS_NAME, "product-card-details__subtitle").text
</code></pre>
<p>However, i am having real difficulty accessing the list elements, I call them the "specs" for each vehicle. I have attempted the following:</p>
<pre><code>specs = car.find_elements(By.XPATH,"//li[contains(@class, 'atc-type-picanto--medium')]")
for spec in specs:
print(spec.get_attribute('innerHTML'))
</code></pre>
<p>However, this outputs <strong>all</strong> specs for <strong>all</strong> cars on each loop. (Why?)</p>
<p>I have also tried the following:</p>
<pre><code>specs = car.find_element(By.CLASS_NAME, "listing-key-specs").get_attribute('innerHTML')
print(specs)
</code></pre>
<p>Which outputs:</p>
<pre><code> <li class="atc-type-picanto--medium">2018 (68 reg)</li>
<li class="atc-type-picanto--medium">Hatchback</li>
<li class="atc-type-picanto--medium">39,009 miles</li>
<li class="atc-type-picanto--medium">1.3L</li>
<li class="atc-type-picanto--medium">161BHP</li>
<li class="atc-type-picanto--medium">Automatic</li>
<li class="atc-type-picanto--medium">Petrol</li>
<li class="atc-type-picanto--medium">1 owner</li>
<li class="atc-type-picanto--medium">ULEZ</li>
</code></pre>
<p>And i cannot seem to extract each element, it only extracts as a block.</p>
<p>Ideally i'd like to create a list of lists:</p>
<pre><code>all_specs = [[car1spec1, car1spec2, ...], [car2spec1, car2spec2, ...]]
</code></pre>
<p>And so on. Any help would be much appreciated as I have spent a few days trying to figure this out.</p>
| [
{
"answer_id": 74378575,
"author": "Eugeny Okulik",
"author_id": 12023661,
"author_profile": "https://Stackoverflow.com/users/12023661",
"pm_score": 1,
"selected": false,
"text": "<html>\n<body>\n<section class=\"product-card-details\">\n <h3 class=\"product-card-details__title\">\nMercedes-Benz A-Class\n </h3>\n\n <p class=\"product-card-details__subtitle\">\n1.3 A 200 AMG LINE 5d 161 BHP | 14-DAYS MONEY BACK GUARANTEE*\n </p>\n\n <p class=\"product-card-details__attention-grabber\">\n***FREE 3 MONTHS WARRANTY***\n </p>\n\n <ul class=\"listing-key-specs\">\n\n <li class=\"atc-type-picanto--medium\">2018 (68 reg)</li>\n\n <li class=\"atc-type-picanto--medium\">Hatchback</li>\n\n <li class=\"atc-type-picanto--medium\">39,009 miles</li>\n\n <li class=\"atc-type-picanto--medium\">1.3L</li>\n\n <li class=\"atc-type-picanto--medium\">161BHP</li>\n\n <li class=\"atc-type-picanto--medium\">Automatic</li>\n\n <li class=\"atc-type-picanto--medium\">Petrol</li>\n\n <li class=\"atc-type-picanto--medium\">1 owner</li>\n\n <li class=\"atc-type-picanto--medium\">ULEZ</li>\n\n\n </ul>\n</section>\n</body>\n</html>\n"
},
{
"answer_id": 74384238,
"author": "Arundeep Chohan",
"author_id": 9901261,
"author_profile": "https://Stackoverflow.com/users/9901261",
"pm_score": 0,
"selected": false,
"text": "specs = car.find_elements(By.XPATH,\".//li[contains(@class, 'atc-type-picanto--medium')]\")\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6562240/"
] |
74,377,139 | <p>Hello I am new to JavaScript I am trying to get season name when user enters a month name. What am I doing wrong?</p>
<pre class="lang-js prettyprint-override"><code>const takeInput = prompt("Enter the Season Name : ");
let seasons = {
summer: ["may", "june", "july"],
winter: ["november", "december", "january"],
};
takeInput.toLowerCase();
switch (takeInput) {
case "summer":
if (takeInput === seasons.summer) {
console.log("summer");
}
break;
}
</code></pre>
| [
{
"answer_id": 74377640,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "takeInput === seasons.summer\n"
},
{
"answer_id": 74377945,
"author": "Abdullah Manafikhi",
"author_id": 16616472,
"author_profile": "https://Stackoverflow.com/users/16616472",
"pm_score": 0,
"selected": false,
"text": "//instead of \n if (takeInput === seasons.summer) {\n console.log(\"summer\");\n }\n //do this:\n if(seasons.summer.find(season => season === takeInput)){\n console.log(\"summer\")\n }\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460367/"
] |
74,377,203 | <p>I'm currently working on a button, which has 3 elements: An icon (with a fixed size), a title (f.e Buy Now!) and the price of the item.
The price which should be displayed is adaptive, this could be €2,00 or €2000,00. The title is supposed to be centered, based on the Button itself, rather than the area it can occupy.</p>
<p>The price of object has the priority within the button, and should always be fully displayed with a set style. Due to this, the size of this object is variable, and can not be determined beforehand.</p>
<p>When the length of the price object increases, naturally the available space of the title decreases. However, when attempting to center the text, I could only get it to center based on the available space, which resulted in the text being off-center.
<a href="https://i.stack.imgur.com/1UaYM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1UaYM.png" alt="Rough wireframes" /></a></p>
<p>How could one approach this issue, allowing for the text to be centered based on the parent (button), rather than the available text size?</p>
| [
{
"answer_id": 74377640,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "takeInput === seasons.summer\n"
},
{
"answer_id": 74377945,
"author": "Abdullah Manafikhi",
"author_id": 16616472,
"author_profile": "https://Stackoverflow.com/users/16616472",
"pm_score": 0,
"selected": false,
"text": "//instead of \n if (takeInput === seasons.summer) {\n console.log(\"summer\");\n }\n //do this:\n if(seasons.summer.find(season => season === takeInput)){\n console.log(\"summer\")\n }\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460334/"
] |
74,377,204 | <p>I have printed out a list of numbers, but I want to make the output 'cleaner'</p>
<pre><code>a,b=3,4
while (b<=1000000):
if b>= 100 and b<=1000000:
print(b, end = ' ')
a,b = b,a+b
</code></pre>
<p>output:</p>
<pre><code>123 199 322 521 843 1364 2207 3571 5778 9349 15127 24476 39603 64079 103682 167761 271443 439204 710647
</code></pre>
<p>What I want to do with it is, add a line break after every 5 numbers, so:</p>
<pre><code>123 199 322 521 843
1364 2207 3571 5778 9349
...
</code></pre>
<p>and so forth.</p>
<p>I've done some googling and searching and I stumbled upon this (an example):</p>
<pre><code>i = 1
while i < 30:
print(i, end = '\n' if i % 5 == 0 else " ")
i += 1
</code></pre>
<p>but when i try to add it to my code:</p>
<pre><code>while (b<=1000000):
if b>= 100 and b<=1000000:
print(b, end = '\n' if b % 5 == 0 else " ")
a,b = b,a+b
</code></pre>
<p>the output is still the same, all in one line:</p>
<pre><code>123 199 322 521... 167761 271443 439204 710647
</code></pre>
<p>any ideas?</p>
| [
{
"answer_id": 74377640,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "takeInput === seasons.summer\n"
},
{
"answer_id": 74377945,
"author": "Abdullah Manafikhi",
"author_id": 16616472,
"author_profile": "https://Stackoverflow.com/users/16616472",
"pm_score": 0,
"selected": false,
"text": "//instead of \n if (takeInput === seasons.summer) {\n console.log(\"summer\");\n }\n //do this:\n if(seasons.summer.find(season => season === takeInput)){\n console.log(\"summer\")\n }\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460022/"
] |
74,377,218 | <p>I want to sum a bars' varible <code>propVolume</code> back since the one which <code>bar_index</code> I specify via input settings. It works just fine unless I give it <code>bar_index</code> of a bar, which is farer than 103 bars back. In documentation they say that that may be due to shortage of default buffer for <code>time</code> built-in variable, which is used my <code>bar_index</code> internally, they advise to call <code>max_bars_back</code> function to extend that buffer for <code>time</code> built-in, I did that, but it didn't help. Same problem persist - no more than 103 bars back in the history. Here is the snippet. Any ideas on overcoming 103 limit for history are much appreciated. Thank you!</p>
<pre><code>//@version=5
// Declaration Statement
int MAX_BARS = 1000
indicator("Volume by Rang1e", "Volume by Range1", format = format.volume, overlay = false , max_labels_count = 500, max_bars_back = MAX_BARS)
enter code here
// Inputs
int anchorInput = input.int(20000, "Anchor", 1, 100000, 1, "Anchor tooltip")
max_bars_back(time, MAX_BARS)
int n_bars = nz(ta.barssince(bar_index[1] == anchorInput) + 1, 1)
float propVolume = volume / 2 //Whatever...
float totalPropVolume = math.sum(propVolume[1], n_bars)
plot(totalPropVolume, color = color.green, style = plot.style_columns)
</code></pre>
| [
{
"answer_id": 74377640,
"author": "RenaudC5",
"author_id": 11260991,
"author_profile": "https://Stackoverflow.com/users/11260991",
"pm_score": 1,
"selected": false,
"text": "takeInput === seasons.summer\n"
},
{
"answer_id": 74377945,
"author": "Abdullah Manafikhi",
"author_id": 16616472,
"author_profile": "https://Stackoverflow.com/users/16616472",
"pm_score": 0,
"selected": false,
"text": "//instead of \n if (takeInput === seasons.summer) {\n console.log(\"summer\");\n }\n //do this:\n if(seasons.summer.find(season => season === takeInput)){\n console.log(\"summer\")\n }\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12491450/"
] |
74,377,223 | <pre><code>while True:
#SOME CODE...
ch = input("\nWould you like to try again? Y/N: ").upper()
if ch == 'Y':
continue # continue the whole program
elif:
print("Thanks for using the program.")
break # stops the program
else:
# repeats the Y or N question only; and prints 'Please input Y or N only'
</code></pre>
<p>I tried using continue statement on the else part but it loops back to the whole program and that's not what I want the program to do. Just only want the Y or N question to be looped if none of the conditions is met</p>
| [
{
"answer_id": 74377296,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "while True:\n # do something\n\n while True:\n ch = input(\"Try again\").upper()\n if ch in ['YES', 'NO']:\n break\n print(\"Please enter yes or no\")\n\n if ch == \"NO\":\n print(\"Thanks for using the program.\")\n break\n"
},
{
"answer_id": 74377304,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "while True:\n\n#SOME CODE...\n\n ch = input(\"\\nWould you like to try again? Y/N: \").upper()\n\n if ch not in ['Y', 'N', 'YES', 'yes', 'no', 'NO']:\n pass\n else:\n print(\"Thanks for using the program.\")\n break\n"
}
] | 2022/11/09 | [
"https://Stackoverflow.com/questions/74377223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17442579/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.