qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,468,962
|
<p>I'm a beginner in C language, and I was wondering what will happen if I write something like this:</p>
<pre><code> int *p;
int b = 4;
int a = 3;
p = &a;
printf("%d", p[1])
</code></pre>
<p>I was expecting the result is "4", however, I got an unexpected result(which is a random number)</p>
<p>I also make experiment below:
<a href="https://i.stack.imgur.com/o8pta.png" rel="nofollow noreferrer">EXP1</a>
<a href="https://i.stack.imgur.com/IiRZi.png" rel="nofollow noreferrer">EXP2</a></p>
<p>It makes me more confused. I would like some explantions, thanks.</p>
|
[
{
"answer_id": 74468977,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 2,
"selected": false,
"text": "p[1]"
},
{
"answer_id": 74469008,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 1,
"selected": false,
"text": "b"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74468962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525099/"
] |
74,468,979
|
<p>If I have a table like below, how do I create a dictionary of <code>dynamic</code> type from the 2 columns? E.g. <code>{"a":"1", "b":"2", etc}</code></p>
<pre><code>let test = datatable (
keys: string,
vals: string
) [
"a,b,c,d", "1,2,3,4"
];
</code></pre>
<p>There is the <code>split()</code> and <code>zip()</code> function but they create array of arrays and that doesn't work with <code>todynamic()</code></p>
|
[
{
"answer_id": 74468977,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 2,
"selected": false,
"text": "p[1]"
},
{
"answer_id": 74469008,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 1,
"selected": false,
"text": "b"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74468979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4092412/"
] |
74,469,005
|
<p>I have a problem. I want to pull specific data from two different arrays in my Angular application and put it into a new array. Unfortunately I lack the experience how to do this exactly. Under this <a href="https://angular-ivy-z7n2w1.stackblitz.io" rel="nofollow noreferrer">Stackblitz link</a> you can see an example of my application. There you can see that I pass 2 arrays: importData1 and importData2. The field 'description' should be written into a row in my array 'Test' using the AnalyticId. My array has 6 columns of which the first 4 columns should come from the array importData1 and the last two columns from importData2.</p>
<p>Here on the picture you can see the desired output:</p>
<p><a href="https://i.stack.imgur.com/NSohD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NSohD.png" alt="enter image description here" /></a></p>
<p>Here is my interface:</p>
<pre><code>export interface TestInterface {
id: any;
name: any;
price: any;
stored: any;
costPerPound: any;
mixture: any;
}
</code></pre>
<p>Using the interface, I create an empty array:</p>
<pre><code>test: TestInterface[] = [];
</code></pre>
<pre><code> fillArray(importData1 = [], importData2 = []) {
for (let i = 0; i < this.importData1.length; i++) {
if (this.importData1[i].analyticDescriptionTypeId == 1) {
this.test[i].id == importData1[i].descrition;
}
if (this.importData1[i].analyticDescriptionTypeId == 2) {
this.test[i].name == importData1[i].descrition;
}
if (this.importData1[i].analyticDescriptionTypeId == 3) {
this.test[i].price == importData1[i].descrition;
}
if (this.importData1[i].analyticDescriptionTypeId == 4) {
this.test[i].stored == importData1[i].descrition;
}
}
for (let j = 0; j < this.importData1.length; j++) {
if (this.importData2[j].analyticDescriptionTypeId == 1) {
this.test[j].costPerPound == importData2[j].descrition;
}
if (this.importData2[j].analyticDescriptionTypeId == 2) {
this.test[j].mixture == importData2[j].descrition;
}
}
console.log(this.test);
}
</code></pre>
<p>And in the method fillArray I tried to map both arrays with each other so that all analyticId and measureId with the same value are written in a row into the test array. But without success.</p>
<p>Question 1) How do I manage to write two arrays depending on a certain value ( analyticId/measureId) into one array?</p>
|
[
{
"answer_id": 74468977,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 2,
"selected": false,
"text": "p[1]"
},
{
"answer_id": 74469008,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 1,
"selected": false,
"text": "b"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12440701/"
] |
74,469,039
|
<p>Say I instantiated a random generator with</p>
<pre><code>import numpy as np
rng = np.random.default_rng(seed=42)
</code></pre>
<p>and I want to change its seed. Is it possible to update the seed of the generator instead of instantiating a new generator with the new seed?</p>
<p>I managed to find that you can see the state of the generator with <code>rng.__getstate__()</code>, for example in this case it is</p>
<pre><code>{'bit_generator': 'PCG64',
'state': {'state': 274674114334540486603088602300644985544,
'inc': 332724090758049132448979897138935081983},
'has_uint32': 0,
'uinteger': 0}
</code></pre>
<p>and you can change it with <code>rng.__setstate__</code> with arguments as printed above, but it is not clear to me how to set those arguments so that to have the initial state of the rng given a different seed. Is it possible to do so or instantiating a new generator is the only way?</p>
|
[
{
"answer_id": 74469126,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\n\nseed = 12345\n\nrng = np.random.default_rng(seed)\nx1 = rng.normal(size=10)\n\nrng.__setstate__(np.random.default_rng(seed).__getstate__())\nx2 = rng.normal(size=10)\n\nnp.testing.assert_array_equal(x1, x2)\n"
},
{
"answer_id": 74474377,
"author": "Sam Mason",
"author_id": 1358308,
"author_profile": "https://Stackoverflow.com/users/1358308",
"pm_score": 2,
"selected": false,
"text": "default_rng()"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10842351/"
] |
74,469,073
|
<p>My datatable is below.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>menu_nm</th>
<th>dtl</th>
<th>rcp</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>sandwich</td>
<td>amazing sandwich!!!</td>
<td>bread 10g</td>
</tr>
<tr>
<td>1</td>
<td>hamburger</td>
<td>bread 20g, vegetable 10g</td>
<td>???</td>
</tr>
<tr>
<td>2</td>
<td>salad</td>
<td>fresh salad!!!</td>
<td>apple sauce 10g, banana 40g, cucumber 5g</td>
</tr>
<tr>
<td>3</td>
<td>juice</td>
<td>sweet juice!!</td>
<td>orange 50g, water 100ml</td>
</tr>
<tr>
<td>4</td>
<td>fruits</td>
<td>strawberry 10g, grape 20g, melon 10g</td>
<td>???</td>
</tr>
</tbody>
</table>
</div>
<p>and I want to get this datatable</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>menu_nm</th>
<th>dtl</th>
<th>rcp</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>sandwich</td>
<td>amazing sandwich!!!</td>
<td>bread 10g</td>
</tr>
<tr>
<td>1</td>
<td>hamburger</td>
<td></td>
<td>bread 20g, vegetable 10g</td>
</tr>
<tr>
<td>2</td>
<td>salad</td>
<td>fresh salad!!!</td>
<td>apple sauce 10g, banana 40g, cucumber 5g</td>
</tr>
<tr>
<td>3</td>
<td>juice</td>
<td>sweet juice!!</td>
<td>orange 50g, water 100ml</td>
</tr>
<tr>
<td>4</td>
<td>fruits</td>
<td></td>
<td>strawberry 10g, grape 20g, melon 10g</td>
</tr>
</tbody>
</table>
</div>
<p>I want to shift row 1, 4 to rcp column, but I can't find method or logic that I try.
I just know that shifting all row and all column, I don't know how I can shift certain row and column.</p>
<p>If you know hint or answer, please tell me. thanks.</p>
|
[
{
"answer_id": 74469123,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 1,
"selected": false,
"text": "# create a filter where value under rcp is \"???\"\nm=df['rcp'].eq('???')\n\n# using loc, shift the values\n\ndf.loc[m, 'rcp'] = df['dtl']\ndf.loc[m, 'dtl'] = \"\"\ndf\n"
},
{
"answer_id": 74469147,
"author": "hknjj",
"author_id": 1925445,
"author_profile": "https://Stackoverflow.com/users/1925445",
"pm_score": 1,
"selected": true,
"text": ">>> df=pd.DataFrame({\"COLA\":[1,2,3,4], \"COLB\":[100,200,300,400], \"COLC\":[1000,2000,3000,4000]})\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200 2000\n2 3 300 3000\n3 4 400 4000\n>>> df['COLC'].iloc[1]=df['COLB'].iloc[1]\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200 200\n2 3 300 3000\n3 4 400 4000\n>>> df['COLB'].iloc[1]=''\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200\n2 3 300 3000\n3 4 400 4000\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20505690/"
] |
74,469,109
|
<p>I have a redis cluster created with master slave mode. I want to create a redisson client to access the cluster but I want to specify separate endpoints for reads and writes. Writes should go to master and reads should happen from the slaves. There is a config <em><strong>readMode</strong></em> that can I set to SLAVE to read only from slave nodes but how do I restrict writes to master only?</p>
|
[
{
"answer_id": 74469123,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 1,
"selected": false,
"text": "# create a filter where value under rcp is \"???\"\nm=df['rcp'].eq('???')\n\n# using loc, shift the values\n\ndf.loc[m, 'rcp'] = df['dtl']\ndf.loc[m, 'dtl'] = \"\"\ndf\n"
},
{
"answer_id": 74469147,
"author": "hknjj",
"author_id": 1925445,
"author_profile": "https://Stackoverflow.com/users/1925445",
"pm_score": 1,
"selected": true,
"text": ">>> df=pd.DataFrame({\"COLA\":[1,2,3,4], \"COLB\":[100,200,300,400], \"COLC\":[1000,2000,3000,4000]})\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200 2000\n2 3 300 3000\n3 4 400 4000\n>>> df['COLC'].iloc[1]=df['COLB'].iloc[1]\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200 200\n2 3 300 3000\n3 4 400 4000\n>>> df['COLB'].iloc[1]=''\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200\n2 3 300 3000\n3 4 400 4000\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3484844/"
] |
74,469,142
|
<p>I need to automatically calculate a <strong>Start Date (aka QRT_START)</strong> which is 5 years of Quarters back. A Quarter is 3 months. For example, there are 4 Quarters in a Year: March 31st, June 30th, September 30th and December 31st.
</p>
<p>Since we are currently in November 16th 2022, the Start Date would be December 31st 2017. So depending on whatever the current date is, the Start Date needs to go back 5 years worth of Quarters.</p>
<p>I also need to automatically calculate the most recent <strong>End Date (aka QRT_END)</strong>. So since, we are in November 16th 2022, the End Date would be the previous quarter end before today which is September 30th 2022. I have the VBA code written below, please help me fix.</p>
<pre><code>Private Function getQRT_END() As String
Dim endmonth As Variant
Dim endyear As Variant
Dim Day As Variant
endmonth = Month(Date) - 1
If endmonth = 0 Then
endyear = Year(Date) - 1
endmonth = 12
day = 31
Else
endyear = Year(Date)
If endmonth = 3 Then
day = 31
Else
day = 30
End if
endmonth = “0” & endmonth
End If
getQRT_END = endyear & endmonth & day
End Function
Private Function getQRT_START() As String
Dim startmonth As Variant
Dim startyear As Variant
Dim Day As Variant
startyear = Year(Date) - 5
startmonth = Month(Date) + 2
If startmonth <10 Then
If startmonth = 3 Then
day = 31
Else
day = 30
End if
startmonth = “0” & startmonth
Else
day = 30
End If
getQRT_START = startyear & startmonth & day
End Function
</code></pre>
|
[
{
"answer_id": 74469123,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 1,
"selected": false,
"text": "# create a filter where value under rcp is \"???\"\nm=df['rcp'].eq('???')\n\n# using loc, shift the values\n\ndf.loc[m, 'rcp'] = df['dtl']\ndf.loc[m, 'dtl'] = \"\"\ndf\n"
},
{
"answer_id": 74469147,
"author": "hknjj",
"author_id": 1925445,
"author_profile": "https://Stackoverflow.com/users/1925445",
"pm_score": 1,
"selected": true,
"text": ">>> df=pd.DataFrame({\"COLA\":[1,2,3,4], \"COLB\":[100,200,300,400], \"COLC\":[1000,2000,3000,4000]})\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200 2000\n2 3 300 3000\n3 4 400 4000\n>>> df['COLC'].iloc[1]=df['COLB'].iloc[1]\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200 200\n2 3 300 3000\n3 4 400 4000\n>>> df['COLB'].iloc[1]=''\n>>> df\n COLA COLB COLC\n0 1 100 1000\n1 2 200\n2 3 300 3000\n3 4 400 4000\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13794066/"
] |
74,469,149
|
<p>I've always maintained the practice of checking if a value is undefined using</p>
<pre><code>if (typeof x === 'undefined')
</code></pre>
<p>However, a colleague is suggesting that using <code>if (x) {</code> is better.</p>
<p>Is there any difference between these two methods from a computational point of view?</p>
|
[
{
"answer_id": 74469236,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 3,
"selected": true,
"text": "if(x)"
},
{
"answer_id": 74469928,
"author": "OFRBG",
"author_id": 1231844,
"author_profile": "https://Stackoverflow.com/users/1231844",
"pm_score": -1,
"selected": false,
"text": "undefined"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1224963/"
] |
74,469,164
|
<p>i need your help on this please</p>
<p>I have an enormous directory with millions and millions of files and im trying to group those by year and month using the find command and then tar it to save some space.</p>
<p>I have created a bash script like the following</p>
<pre><code>#!/bin/bash
DIR=/data/historical
/usr/bin/cd /data/backupfile
sleep 2
[ -e "$DIR" ] || mkdir "$DIR"
sleep 2
for year in 2019 2020 2021 2022
do
for month in jan feb mar apr may jun jul aug sept oct nov dec
do
mkdir -p /data/historical/"$year"/"$month"
done
for prev feb mar apr may jun jul aug sept oct nov dec jan
do
/usr/bin/find ! -newermt "$prev 31 $year" -newermt "$month 1 $year" -exec mv {} /data/historical/"$month" \;
done
done
</code></pre>
<h1>Also tried this way</h1>
<pre><code>years=2019,2020,2021,2022
months=01,02,03,04,05,06,07,08,09,10,11,12
#months=`date '+%b'`
#after=`date -d '1 month' '+%b'`
for year in $(echo ${years})
do
for month in "${months[@]}"
do
/usr/bin/find ! -newermt "$year-$month-31" -newermt "$year-$month-01" -exec mv {} /data/historical/"$month" \;
done
done
</code></pre>
<p>So, this what i really need. I need to iterate through every year (2019 2020 2021 2022) starting with 2019 and every month ( 01,02,03,04,05,06,07,08,09,10,11,12) starting with 01 ... 12, get the files grouped by month-year and then tar it and them keep iterating through the other year ie 2020.</p>
<p>For example:</p>
<p>/usr/bin/find ! -newermt "feb 29 2019" -newermt "jan 1 2019" -exec mv {} /data/historical/2019 ; && /usr/bin/tar -czf /data/historical/file.tar.gz /data/historical/2019</p>
<p>I have tried change the variables, playing with the iteration and for loops, nested for loops. The directories 2019/{jan...dec} are created but the files i want to search for and grouped by month and year are not there.</p>
<p>#EDIT</p>
<p>To help you understand better:</p>
<p>My enormous file is /data/backupfile</p>
<p>It contains files from 2019-2022</p>
<p>I want to group those files by year/month that's why Im trying to create directories 2019/Jan and get those jan-2019, feb-2019, etc files from /data/backupfile.</p>
<p>I've been trying to do that using nested loops. Maybe there's a better solution?</p>
|
[
{
"answer_id": 74469236,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 3,
"selected": true,
"text": "if(x)"
},
{
"answer_id": 74469928,
"author": "OFRBG",
"author_id": 1231844,
"author_profile": "https://Stackoverflow.com/users/1231844",
"pm_score": -1,
"selected": false,
"text": "undefined"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525173/"
] |
74,469,207
|
<p>Hy guys this is my first time here.I am a beginner and i wantend to check how can i from a given string
(which is: string="5,93,14,2,33" ) make a list, after that to get the square of each number from the list and than to return that list (with a squared values) in to string?</p>
<p>input should to be:
string = "5,93,14,2,33"</p>
<p>output:
string = "25,8649,196,4,1089"</p>
<p>i tried to make new list with .split() and than to do square of each element, but i understand that i didnt convert the string with int().I just cant put all that together so i hope that you guys can help.Thanks and sorry if this question was stupid, i just started learning</p>
|
[
{
"answer_id": 74469236,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 3,
"selected": true,
"text": "if(x)"
},
{
"answer_id": 74469928,
"author": "OFRBG",
"author_id": 1231844,
"author_profile": "https://Stackoverflow.com/users/1231844",
"pm_score": -1,
"selected": false,
"text": "undefined"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525326/"
] |
74,469,243
|
<p>I want to call the data from API using horizontal_data_table on flutter. this is the code where it gets the error</p>
<pre><code> Container(
width: 200,
height: 52,
padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
alignment: Alignment.centerLeft,
child: Text(widget.leavelistmodel.response[index].paidLeaveEmployeeNip),
),
</code></pre>
<p>and the data model from the result looks like this:</p>
<pre><code>class LeaveListResult {
int? paidLeaveId;
String? paidLeaveEmployeeNip;
String? paidLeaveEmployeeFullName;
}
</code></pre>
<p>I'm already changing it into? and ! it still got an error, how can I fix the error?</p>
|
[
{
"answer_id": 74469301,
"author": "Jungwon",
"author_id": 15134376,
"author_profile": "https://Stackoverflow.com/users/15134376",
"pm_score": 1,
"selected": false,
"text": "nullSafty"
},
{
"answer_id": 74469302,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 1,
"selected": false,
"text": "Text"
},
{
"answer_id": 74469934,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 0,
"selected": false,
"text": "response"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13497264/"
] |
74,469,309
|
<p>Spark Masters!</p>
<p>Does anyone has some tips on which is better or faster on pyspark to create a column with the max number of another column.</p>
<p>Option A:</p>
<pre><code>max_num = df.agg({"number": "max"}).collect()[0][0]
df = df.withColumn("max", f.lit(max_num))
</code></pre>
<p>Option B:</p>
<pre><code>max_num = df2.select(f.max(f.col("number")).alias("max"))
df2 = df2.crossJoin(max_num)
</code></pre>
<p>Please feel free, to add any other comments, even not directly related, is more for learning purpose.</p>
<p>Please, feel free to add an option C, D …</p>
<p>On thread is a testable code I made (also any comments on the code are welcome)</p>
<p>Testing code:</p>
<pre><code>import time
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
# --------------------------------------------------------------------------------------
# 01 - Data creation
spark = SparkSession.builder.getOrCreate()
data = []
for i in range(10000):
data.append(
{
"1": "adsadasd",
"number": 1323,
"3": "andfja"
}
)
data.append(
{
"1": "afasdf",
"number": 8908,
"3": "fdssfv"
}
)
df = spark.createDataFrame(data)
df2 = spark.createDataFrame(data)
df.count()
df2.count()
print(df.rdd.getNumPartitions())
print(df2.rdd.getNumPartitions())
# --------------------------------------------------------------------------------------
# 02 - Tests
# B) Crossjoin
start_time = time.time()
max_num = df2.select(f.max(f.col("number")).alias("max"))
df2 = df2.crossJoin(max_num)
print(df2.count())
print("Collect time: ", time.time() - start_time)
# A) Collect
start_time = time.time()
max_num = df.agg({"number": "max"}).collect()[0][0]
df = df.withColumn("max", f.lit(max_num))
print(df.count())
print("Collect time: ", time.time() - start_time)
df2.show()
df.show()
</code></pre>
<p>Measure the performance of collect and crossjoin on pyspark.</p>
|
[
{
"answer_id": 74475347,
"author": "Ric S",
"author_id": 7465462,
"author_profile": "https://Stackoverflow.com/users/7465462",
"pm_score": 1,
"selected": false,
"text": "Window"
},
{
"answer_id": 74479642,
"author": "Matheus Ribeiro",
"author_id": 14188259,
"author_profile": "https://Stackoverflow.com/users/14188259",
"pm_score": 0,
"selected": false,
"text": "import time\nimport numpy as np\nimport pandas as pd\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\nfrom pyspark.sql.window import Window\n\n# --------------------------------------------------------------------------------------\n# 01 - Data creation\nspark = SparkSession.builder.getOrCreate()\n\ndata = pd.DataFrame({\n 'aaa': '1',\n 'number': np.random.randint(0, 100, size=1000000)\n})\ndf = spark.createDataFrame(data)\ndf2 = spark.createDataFrame(data)\ndf3 = spark.createDataFrame(data)\n\ndf.count()\ndf2.count()\ndf3.count()\n# --------------------------------------------------------------------------------------\n# 02 - Tests\n\n# A) Collect\nmethod = 'A'\nstart_time = time.time()\nmax_num = df.agg({\"number\": \"max\"}).collect()[0][0]\ndf = df.withColumn(\"max\", F.lit(max_num))\ndf.count()\nprint(f\"Collect time method {method}: \", time.time() - start_time)\n\n# B) Crossjoin\nmethod = 'B'\nstart_time = time.time()\nmax_num = df2.select(F.max(F.col(\"number\")).alias(\"max\"))\ndf2 = df2.crossJoin(max_num)\ndf2.count()\nprint(f\"Collect time method {method}: \", time.time() - start_time)\n\n# C) Window\nmethod = 'C'\nstart_time = time.time()\ndf3 = df3.withColumn(\"max\", F.max(\"number\").over(Window.partitionBy()))\ndf3.count()\nprint(f\"Collect time method {method}: \", time.time() - start_time)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188259/"
] |
74,469,310
|
<p>I'm trying to implement a text that says "Try again" to appear when the player guesses incorrectly. This is an extremely bare bones "game" but I started coding yesterday and I'm trying to learn all the basic functions and methods. This is the code:</p>
<pre><code>secret_number = 9
guess_limit = 3
guess_count = 0
while guess_count < guess_limit:
guess = int(input("Guess:"))
guess_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("You lost!")
</code></pre>
<p>I tried using another "else" function and another "if" function but I couldn't figure it out.</p>
|
[
{
"answer_id": 74469337,
"author": "GabrielBoehme",
"author_id": 11949273,
"author_profile": "https://Stackoverflow.com/users/11949273",
"pm_score": 2,
"selected": false,
"text": "secret_number = 9\nguess_limit = 3\nguess_count = 0\nwhile guess_count < guess_limit:\n won = False\n guess = int(input(\"Guess:\"))\n guess_count += 1\n\n if guess == secret_number:\n print(\"You won!\")\n won = True\n break\n\n # If wrong, goes in here.\n else:\n # Just prints, and continues the loop\n print('Try again')\n\n# After the loop, if not won, prints lost.\nif not won:\n print(\"You lost!\")\n"
},
{
"answer_id": 74469399,
"author": "mister-sir",
"author_id": 8353687,
"author_profile": "https://Stackoverflow.com/users/8353687",
"pm_score": 0,
"selected": false,
"text": "secret_number = 9\nguess_limit = 3\nguess_count = 0\nwhile guess_count < guess_limit: # this could also just be `while True:` since the `if` will always break out\n guess = int(input(\"Guess:\"))\n guess_count += 1\n if guess == secret_number:\n print(\"You won!\")\n break\n else:\n if guess_count == guess_limit:\n print(\"You lost!\")\n break\n else:\n print(\"Try again!\")\n"
},
{
"answer_id": 74469515,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "'Try again'"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513809/"
] |
74,469,333
|
<p>so i have document for users with this structure in JSON format:</p>
<pre><code>[
{
"_id": {
"$oid": "6369aeb83ce0f8168520f42f"
},
"fullname": "Jokona",
"password": "$2b$10$MUAe7XIc/xtJTGVh/y1DeuShCARbwxCSejUbHaqIPZfjekNrn0.Yy",
"NIK": "MT220047",
"status": "active",
"department": "Logistic",
"position": "Management Trainee",
"Group_Shift": "Non Shift",
"role": "admin",
"createdAt": 1667870392,
"updatedAt": 1668564835,
"__v": 0
},
{
"_id": {
"$oid": "6369b17b11e02557349d8de5"
},
"fullname": "Warana",
"password": "$2b$10$0xaqz5V8bar/osWmsCiofet5bY10.ORn8Vme3QC7Dh0HwLHwYOm3a",
"NIK": "17000691",
"status": "active",
"department": "Production",
"position": "Foreman",
"Group_Shift": "R1",
"role": "user",
"__v": 0,
"createdAt": 1667871099,
"updatedAt": 1668496775
},
]
</code></pre>
<p>it try to lookitup using mongodb $lookup to get the fullname by joining using the NIK as the foreignnkey,here is what i have try:</p>
<pre><code>const dataAnaylitics = await Answer.aggregate([
// $match stage
{
$group: {
_id: {
username: "$username",
title: "$title",
date: "$date",
},
count: {
$sum: 1,
},
position: {
$first: "$position",
},
department: {
$first: "$department",
},
},
},
{
$lookup: {
from: "users",
localField: "username",
foreignField: "NIK",
as: "fullname",
pipeline: [{ $project: { fullname: 0 } }],
},
},
{
$group: {
_id: {
username: "$_id.username",
title: "$_id.title",
},
dates: {
$push: {
k: "$_id.date",
v: "$count",
},
},
position: {
$first: "$position",
},
department: {
$first: "$department",
},
},
},
{
$project: {
_id: 0,
username: "$_id.username",
title: "$_id.title",
position: 1,
department: 1,
dates: 1,
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
{
$arrayToObject: "$dates",
},
],
},
},
},
{
$unset: "dates",
},
]);
</code></pre>
<p>but the result doesnt returning the fullname field, is there is something wrong with my code? i seek for documentation and already follow the step</p>
|
[
{
"answer_id": 74469459,
"author": "Noel",
"author_id": 646591,
"author_profile": "https://Stackoverflow.com/users/646591",
"pm_score": 2,
"selected": true,
"text": "_id.username"
},
{
"answer_id": 74471074,
"author": "JS24",
"author_id": 16136595,
"author_profile": "https://Stackoverflow.com/users/16136595",
"pm_score": 0,
"selected": false,
"text": "const dataAnaylitics = await Answer.aggregate([\n // $match stage\n {\n $group: {\n _id: {\n username: \"$username\",\n title: \"$title\",\n date: \"$date\",\n },\n count: {\n $sum: 1,\n },\n position: {\n $first: \"$position\",\n },\n department: {\n $first: \"$department\",\n },\n },\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"_id.username\",\n foreignField: \"NIK\",\n as: \"fullname\",\n pipeline: [{ $project: { _id: 0, fullname: 1 } }],\n },\n },\n {\n $group: {\n _id: {\n username: \"$_id.username\",\n title: \"$_id.title\",\n },\n dates: {\n $push: {\n k: \"$_id.date\",\n v: \"$count\",\n },\n },\n position: {\n $first: \"$position\",\n },\n department: {\n $first: \"$department\",\n },\n fullname: {\n $first: { $arrayElemAt: [\"$fullname.fullname\", 0] },\n },\n },\n },\n {\n $project: {\n _id: 0,\n username: \"$_id.username\",\n title: \"$_id.title\",\n position: 1,\n department: 1,\n dates: 1,\n fullname: 1,\n },\n },\n {\n $replaceRoot: {\n newRoot: {\n $mergeObjects: [\n \"$$ROOT\",\n {\n $arrayToObject: \"$dates\",\n },\n ],\n },\n },\n },\n {\n $unset: \"dates\",\n },\n ]);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16136595/"
] |
74,469,342
|
<p>I have a set of actions [0,1,2,3] and a policy which is a series of probabilities for each action like [[0.5, 0.4, 0.05, 0.05]...].</p>
<p>How would it be possible to use np.random.choice (or something similar) which chooses from my actions array for each probability distribution and returns the list of choices?</p>
<p>For a concrete example:</p>
<pre><code>actions = [0, 1, 2, 3]
probs = [[0.5, 0.4, 0.05, 0.05], [0.05, 0.05, 0.1, 0.8]]
*magic*
output = [0, 3]
</code></pre>
<p>Edit: Sorry I wasnt clear before, I am looking for a way to do this which is efficient without a loop if possible. My current code uses a loop and it makes generating many episodes at a time extremely slow.</p>
|
[
{
"answer_id": 74469459,
"author": "Noel",
"author_id": 646591,
"author_profile": "https://Stackoverflow.com/users/646591",
"pm_score": 2,
"selected": true,
"text": "_id.username"
},
{
"answer_id": 74471074,
"author": "JS24",
"author_id": 16136595,
"author_profile": "https://Stackoverflow.com/users/16136595",
"pm_score": 0,
"selected": false,
"text": "const dataAnaylitics = await Answer.aggregate([\n // $match stage\n {\n $group: {\n _id: {\n username: \"$username\",\n title: \"$title\",\n date: \"$date\",\n },\n count: {\n $sum: 1,\n },\n position: {\n $first: \"$position\",\n },\n department: {\n $first: \"$department\",\n },\n },\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"_id.username\",\n foreignField: \"NIK\",\n as: \"fullname\",\n pipeline: [{ $project: { _id: 0, fullname: 1 } }],\n },\n },\n {\n $group: {\n _id: {\n username: \"$_id.username\",\n title: \"$_id.title\",\n },\n dates: {\n $push: {\n k: \"$_id.date\",\n v: \"$count\",\n },\n },\n position: {\n $first: \"$position\",\n },\n department: {\n $first: \"$department\",\n },\n fullname: {\n $first: { $arrayElemAt: [\"$fullname.fullname\", 0] },\n },\n },\n },\n {\n $project: {\n _id: 0,\n username: \"$_id.username\",\n title: \"$_id.title\",\n position: 1,\n department: 1,\n dates: 1,\n fullname: 1,\n },\n },\n {\n $replaceRoot: {\n newRoot: {\n $mergeObjects: [\n \"$$ROOT\",\n {\n $arrayToObject: \"$dates\",\n },\n ],\n },\n },\n },\n {\n $unset: \"dates\",\n },\n ]);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15048596/"
] |
74,469,343
|
<p>I have a <code>StatefulWidget</code> post_view that creates a <code>DataTable</code>. The data used to fill up the <code>DataTable</code> is from a static method in another class named Post:</p>
<p>`</p>
<pre><code>static generateData(){
List<Post> postList= [];
postList.add(Post(title: "Coolest Post", numDownVotes: 6, numUpVotes: 9));
postList.add(Post(title: "Covid-19 vaccine found!", numDownVotes: 3, numUpVotes: 67));
postList.add(Post(title: "Unreal ending to basketball game", numDownVotes: 2, numUpVotes: 23));
postList.add(Post(title: "Sample Post", numDownVotes: 2, numUpVotes: 6));
postList.add(Post(title: "What A Save!", numDownVotes: 5, numUpVotes: 34));
return postList;
}
</code></pre>
<p>`</p>
<p>I have the <code>DataCells</code> in the table such that the number of up/down votes are in a row widget within the data cell along with an icon button to change or increase/decrease the number of up/down votes respectively. So, I have a variable '_posts' declared inside post_view that calls <code>generateData()</code> and displays the data, but I want to be able to manipulate this data and pass it to another widget <code>BarGraph</code>, which will generate a bar chart of the dynamic data.</p>
<p>Here's my <code>BarGraph</code> widget:</p>
<p>`</p>
<pre><code>class BarGraph extends StatefulWidget {
BarGraph({Key? key, required this.tableData}) : super(key: key);
List<Post>? tableData;
@override
State<BarGraph> createState() => _BarGraphState();
}
</code></pre>
<p>`</p>
<p>The issue here is that <code>TabelData</code> is not accessible at all but I want to be able to get the titles, numupvotes, and numdownvotes to be able to display them in a chart. I tried using a getter but the null check operator doesn't work with that. I'm completely stuck, any help would be appreciated!</p>
|
[
{
"answer_id": 74469643,
"author": "Duy Tran",
"author_id": 19851394,
"author_profile": "https://Stackoverflow.com/users/19851394",
"pm_score": 0,
"selected": false,
"text": "class ManagePost extends Cubit<List<Post>> {\n List<Post> postList = [];\n void addPost(Post post) {\n postList.add(Post);\n emit(postList);\n }\n\n void deletePost() {}\n void updateVote() {}\n void getAllPost() {}\n}\n"
},
{
"answer_id": 74469932,
"author": "QuintessentialGamer",
"author_id": 18648904,
"author_profile": "https://Stackoverflow.com/users/18648904",
"pm_score": 1,
"selected": false,
"text": "widget.tableData"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18648904/"
] |
74,469,388
|
<p>How do I combine those highlighted cells in one column? The highlighted cell is based one rule condition that contains a slash.</p>
<p><a href="https://i.stack.imgur.com/hZmaj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hZmaj.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74469468,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(TRIM(FLATTEN(QUERY(TRANSPOSE(IF(REGEXMATCH(B:F; \"\\/\"); B:F; ));;9^9))))\n"
},
{
"answer_id": 74469502,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 3,
"selected": true,
"text": "=BYROW(B1:INDEX(F:F,INDEX(MAX((IF(B:F<>\"\",ROW(B:F),0))))),LAMBDA(x,JOIN(\", \",FILTER(x,INDEX(ISNUMBER(SEARCH(\"/\",x)))))))\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5344804/"
] |
74,469,404
|
<p>I have the following code that should work. I am simply trying to get all the "img" elements from a page into a list in AS so that I can work on that list.</p>
<pre><code>tell application "Safari"
set theWindow to front window
set theTab to current tab of theWindow
set theURL to URL of theTab
set asImages to (do JavaScript "theSearch = document.getElementsByTagName(\"img\");
theImages = [].slice.call(theSearch);
theImages" in theTab)
end tell
</code></pre>
<p>If I enter in</p>
<pre><code>theSearch = document.getElementsByTagName("img");
theImages = [].slice.call(theSearch);
theImages
</code></pre>
<p>into the console on Safari it works. But when I run the same code as above from within the "do javascript" command in Safari, I get nothing back at all, the variable asImages is not created at all.
I have tried everything that I can think of, to no avail. I am hoping someone with a fresh pair of eyes can spot what I am doing wrong rather quickly. TIA</p>
|
[
{
"answer_id": 74469468,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(TRIM(FLATTEN(QUERY(TRANSPOSE(IF(REGEXMATCH(B:F; \"\\/\"); B:F; ));;9^9))))\n"
},
{
"answer_id": 74469502,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 3,
"selected": true,
"text": "=BYROW(B1:INDEX(F:F,INDEX(MAX((IF(B:F<>\"\",ROW(B:F),0))))),LAMBDA(x,JOIN(\", \",FILTER(x,INDEX(ISNUMBER(SEARCH(\"/\",x)))))))\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2359796/"
] |
74,469,413
|
<p>I need loop thought two array and return another array with different values.</p>
<p>Example of two arrays:</p>
<pre><code>let arr1 = ['one' , 'two' , 'three'];
let arr2 = ['four' , 'one' , 'two'];
</code></pre>
<p>What do I need?</p>
<p>Loop thought both array and return the same value, I expect new array like:</p>
<pre><code>let res = [
{ name : 'one' , isSame: true },
{ name : 'two' , isSame: true },
{ name : 'three' },
{ name : 'four' }
];
</code></pre>
<p>I am removed the duplicate items and add <code>isSame</code> value to true on duplicated values.</p>
<p>One and two are duplicated ( twice ).</p>
<p>What I have tried</p>
<pre><code> let arr3 = arr1.map((item, i) =>
Object.assign({}, item, arr2[i])
);
</code></pre>
<p>But I got a splitted array and it's removed duplicated</p>
|
[
{
"answer_id": 74469487,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "reduce()"
},
{
"answer_id": 74469494,
"author": "Robby Cornelissen",
"author_id": 3558960,
"author_profile": "https://Stackoverflow.com/users/3558960",
"pm_score": 2,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n\nconst result = Object.entries([...arr1, ...arr2].reduce(\n (a, v) => ({ ...a, [v]: v in a }),\n {}\n)).map(([name, isSame]) => ({ name, isSame }));\n\nconsole.log(result);"
},
{
"answer_id": 74469509,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 0,
"selected": false,
"text": "let arr1 = ['one', 'two', 'three'];\nlet arr2 = ['four', 'one', 'two'];\n\nconsole.log(merge(arr1, arr2));\n\nfunction merge(a, b) {\n const merged = a.concat(b); // combine arrays\n const result = [];\n \n let stop = merged.length; // create a variable for when to stop\n for(let i = 0; i < stop; i++) {\n const current = merged[i];\n let same = false;\n \n // look through the rest of the array for indexes\n for(let t = i + 1; t < stop; t++) {\n if(current === merged[t]) {\n same = true;\n merged.splice(t, 1); // remove duplicate elements from the array so we don't come across it again\n stop--; // we've removed an element from the array, so we have to stop 1 earlier\n // we don't break this loop because there may be more than 2 occurences\n }\n }\n const out = { name: current };\n if(same) out.isSame = true;\n \n result.push(out);\n }\n return result;\n}"
},
{
"answer_id": 74469525,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 0,
"selected": false,
"text": "map()"
},
{
"answer_id": 74469634,
"author": "Sanusi hassan",
"author_id": 10944954,
"author_profile": "https://Stackoverflow.com/users/10944954",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n// returns the duplicate values in the two arrays\nconst findDuplicates = (arr) => {\n let sorted_arr = arr.slice().sort();\n let results = [];\n for (let i = 0; i < sorted_arr.length - 1; i++) {\n if (sorted_arr[i + 1] == sorted_arr[i]) {\n results.push(sorted_arr[i]);\n }\n }\n return results;\n}\n\nlet values = ([...new Set([...arr1, ...arr2])]);\nlet duplicates = findDuplicates(values);\n\nlet retval = [];\n\nfor(let i = 0; i < values.length; i++) {\n let isSame = duplicates.includes(values[i]);\n retval.push({name: values[i], isSame: isSame})\n}\n"
},
{
"answer_id": 74469684,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one', 'two', 'three'];\nconst arr2 = ['four', 'one', 'two'];\n\nconst result = Array.from(new Set(arr1.concat(arr2))).reduce((p, c) => {\n const obj = { name: c };\n if (arr1.concat(arr2).join(\"\").split(c).length - 1 > 1) obj.isSame = true;\n p.push(obj)\n return p;\n}, []);\n\nconsole.log(result);"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20448930/"
] |
74,469,414
|
<p>I have a list of Dicts as follows</p>
<p><code>[{"Sender":"bob","Receiver":"alice","Amount":50},{"Sender":"bob","Receiver":"alice","Amount":60},{"Sender":"bob","Receiver":"alice","Amount":70},{"Sender":"joe","Receiver":"bob","Amount":50},{"Sender":"joe","Receiver":"bob","Amount":150},{"Sender":"alice","Receiver":"bob","Amount":100},{"Sender":"bob","Receiver":"kyle","Amount":260}]</code></p>
<p>What i need is to sum up the totals per each unique sender/receiver pair, as well as how many total "transactions" there were per pair, as shown below in my desired output</p>
<p><code>[{"Sender":"bob","Receiver":"alice","Total":180,"Count":3},{"Sender":"joe","Receiver":"bob","Total":"200","Count":2},{"Sender":"alice","Receiver":"bob","Total":"100","Count":1}, {"Sender":"bob","Receiver":"kyle","Total":260,"Count":1}]</code></p>
<p>What i'm currently doing to get the "total" is</p>
<p><code>total = sum(a['Amount'] for a in transactions). </code></p>
<p>But this simply sums up all of the amounts across all pairs, i need the total for each unique pair of sender/receiver i would't know where to begin getting the "count" numbers, either.</p>
|
[
{
"answer_id": 74469487,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "reduce()"
},
{
"answer_id": 74469494,
"author": "Robby Cornelissen",
"author_id": 3558960,
"author_profile": "https://Stackoverflow.com/users/3558960",
"pm_score": 2,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n\nconst result = Object.entries([...arr1, ...arr2].reduce(\n (a, v) => ({ ...a, [v]: v in a }),\n {}\n)).map(([name, isSame]) => ({ name, isSame }));\n\nconsole.log(result);"
},
{
"answer_id": 74469509,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 0,
"selected": false,
"text": "let arr1 = ['one', 'two', 'three'];\nlet arr2 = ['four', 'one', 'two'];\n\nconsole.log(merge(arr1, arr2));\n\nfunction merge(a, b) {\n const merged = a.concat(b); // combine arrays\n const result = [];\n \n let stop = merged.length; // create a variable for when to stop\n for(let i = 0; i < stop; i++) {\n const current = merged[i];\n let same = false;\n \n // look through the rest of the array for indexes\n for(let t = i + 1; t < stop; t++) {\n if(current === merged[t]) {\n same = true;\n merged.splice(t, 1); // remove duplicate elements from the array so we don't come across it again\n stop--; // we've removed an element from the array, so we have to stop 1 earlier\n // we don't break this loop because there may be more than 2 occurences\n }\n }\n const out = { name: current };\n if(same) out.isSame = true;\n \n result.push(out);\n }\n return result;\n}"
},
{
"answer_id": 74469525,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 0,
"selected": false,
"text": "map()"
},
{
"answer_id": 74469634,
"author": "Sanusi hassan",
"author_id": 10944954,
"author_profile": "https://Stackoverflow.com/users/10944954",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n// returns the duplicate values in the two arrays\nconst findDuplicates = (arr) => {\n let sorted_arr = arr.slice().sort();\n let results = [];\n for (let i = 0; i < sorted_arr.length - 1; i++) {\n if (sorted_arr[i + 1] == sorted_arr[i]) {\n results.push(sorted_arr[i]);\n }\n }\n return results;\n}\n\nlet values = ([...new Set([...arr1, ...arr2])]);\nlet duplicates = findDuplicates(values);\n\nlet retval = [];\n\nfor(let i = 0; i < values.length; i++) {\n let isSame = duplicates.includes(values[i]);\n retval.push({name: values[i], isSame: isSame})\n}\n"
},
{
"answer_id": 74469684,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one', 'two', 'three'];\nconst arr2 = ['four', 'one', 'two'];\n\nconst result = Array.from(new Set(arr1.concat(arr2))).reduce((p, c) => {\n const obj = { name: c };\n if (arr1.concat(arr2).join(\"\").split(c).length - 1 > 1) obj.isSame = true;\n p.push(obj)\n return p;\n}, []);\n\nconsole.log(result);"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525628/"
] |
74,469,423
|
<p>I'm trying to write a program for an <code>__add__</code> method where you have to make each index in 2 lists correspond to each other in order to add them to one another, but I'm a little unsure about how to execute that.</p>
<p>For example, if I had the lists:</p>
<pre class="lang-py prettyprint-override"><code>a = List([1.0, 1.0, 1.0])
b = List([2.0, 3.0, 4.0])
</code></pre>
<p>and had to add these two objects together like:</p>
<pre class="lang-py prettyprint-override"><code>c = a + b
</code></pre>
<p>Then the output would be:</p>
<pre class="lang-py prettyprint-override"><code>List([3.0, 4.0, 5.0])
</code></pre>
<p>Here is my code so far:</p>
<pre class="lang-py prettyprint-override"><code>def __add__(self, rhs: Union[float, Simpy]) -> Simpy:
result: Simpy = ([])
if isinstance(rhs, Simpy):
assert len(self.values) == len(rhs.values)
for i in rhs.values:
</code></pre>
<p>For the <code>for</code> loop, I want to write something that will make index 0 of the first list correspond with index 0 of the second list, index 1 correspond with index 1, and so on. Thanks for your help!</p>
<p>edit: I forgot to mention that I can't use functions like zip() or map() in this code. I edited my code a bit and this is what I came up with:</p>
<pre><code>def __add__(self, rhs: Union[float, Simpy]) -> Simpy:
result: Simpy = ([])
if isinstance(rhs, Simpy):
assert len(self.values) == len(rhs.values)
for i in range(len(rhs.values)):
result.values.append(self.values[i] + rhs.values[i])
</code></pre>
<p>I'm still getting an error though and am not sure what I'm getting wrong. Thank you again for your help :)</p>
|
[
{
"answer_id": 74469487,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "reduce()"
},
{
"answer_id": 74469494,
"author": "Robby Cornelissen",
"author_id": 3558960,
"author_profile": "https://Stackoverflow.com/users/3558960",
"pm_score": 2,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n\nconst result = Object.entries([...arr1, ...arr2].reduce(\n (a, v) => ({ ...a, [v]: v in a }),\n {}\n)).map(([name, isSame]) => ({ name, isSame }));\n\nconsole.log(result);"
},
{
"answer_id": 74469509,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 0,
"selected": false,
"text": "let arr1 = ['one', 'two', 'three'];\nlet arr2 = ['four', 'one', 'two'];\n\nconsole.log(merge(arr1, arr2));\n\nfunction merge(a, b) {\n const merged = a.concat(b); // combine arrays\n const result = [];\n \n let stop = merged.length; // create a variable for when to stop\n for(let i = 0; i < stop; i++) {\n const current = merged[i];\n let same = false;\n \n // look through the rest of the array for indexes\n for(let t = i + 1; t < stop; t++) {\n if(current === merged[t]) {\n same = true;\n merged.splice(t, 1); // remove duplicate elements from the array so we don't come across it again\n stop--; // we've removed an element from the array, so we have to stop 1 earlier\n // we don't break this loop because there may be more than 2 occurences\n }\n }\n const out = { name: current };\n if(same) out.isSame = true;\n \n result.push(out);\n }\n return result;\n}"
},
{
"answer_id": 74469525,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 0,
"selected": false,
"text": "map()"
},
{
"answer_id": 74469634,
"author": "Sanusi hassan",
"author_id": 10944954,
"author_profile": "https://Stackoverflow.com/users/10944954",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n// returns the duplicate values in the two arrays\nconst findDuplicates = (arr) => {\n let sorted_arr = arr.slice().sort();\n let results = [];\n for (let i = 0; i < sorted_arr.length - 1; i++) {\n if (sorted_arr[i + 1] == sorted_arr[i]) {\n results.push(sorted_arr[i]);\n }\n }\n return results;\n}\n\nlet values = ([...new Set([...arr1, ...arr2])]);\nlet duplicates = findDuplicates(values);\n\nlet retval = [];\n\nfor(let i = 0; i < values.length; i++) {\n let isSame = duplicates.includes(values[i]);\n retval.push({name: values[i], isSame: isSame})\n}\n"
},
{
"answer_id": 74469684,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one', 'two', 'three'];\nconst arr2 = ['four', 'one', 'two'];\n\nconst result = Array.from(new Set(arr1.concat(arr2))).reduce((p, c) => {\n const obj = { name: c };\n if (arr1.concat(arr2).join(\"\").split(c).length - 1 > 1) obj.isSame = true;\n p.push(obj)\n return p;\n}, []);\n\nconsole.log(result);"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20083473/"
] |
74,469,437
|
<p>I am working through the Odin Project and am stuck on the first lesson where we must build a webapp using webpack. I followed the <a href="https://webpack.js.org/guides/asset-management/" rel="nofollow noreferrer">tutorials here</a> <a href="https://webpack.js.org/guides/asset-management/" rel="nofollow noreferrer">and here</a>on webpack's website, and I was able to get them to work. However, when I try to set up my own files to build my own project, <strong>I can't get CSS to load or a function in my index.js file.</strong></p>
<p>I have the same directory style set up, and have even tried using the exact same index.js file they use in the tutorial.</p>
<p><strong>I expect to get:</strong> a webpage to load that says "hello webpack" in red text.</p>
<p><strong>Instead, I get this error</strong>: when I run $npx webpack, it says:</p>
<pre><code>ERROR in ./src/style.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .hello{
| color: red;
| }
@ ./src/index.js 1:0-21
</code></pre>
<p>Upon googling the error, I found a stack overflow article and I tried renaming my rules array to 'loaders' in my .config file as this article suggests, but I still get the same error.
<a href="https://stackoverflow.com/questions/37934147/you-may-need-an-appropriate-loader-to-handle-this-file-type-with-webpack-and-c">“You may need an appropriate loader to handle this file type” with Webpack and CSS</a></p>
<p>Also weird is the fact that <strong>some of the code in my index.js file works, and some does not</strong>. To elaborate, my <code>console.log</code> and <code>alert</code> works just fine after I run $npx webpack and load the page. However, they function that is supposed to add "hello webpack" to the DOM, does not, as evidence by the fact that nothing shows up at all. The page itself is blank.</p>
<p>My index.js code:</p>
<pre><code>
import './style.css';
console.log("console works");
alert("alert works");
function component() {
const element = document.createElement('div');
// Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
element.classList.add('hello');
return element;
}
document.body.appendChild(component());
</code></pre>
<p>You will notice that it is nearly the exact same as the asset management index.js file from the webpack tutorial. I did this purposely to have as little variance as possible between my stuff and the tutorial.</p>
<p>I don't know if it is too much information, but a link to the whole repo as it currently is set up can be found <a href="https://github.com/manski117/resturaunt-page-project" rel="nofollow noreferrer">here</a></p>
|
[
{
"answer_id": 74469487,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "reduce()"
},
{
"answer_id": 74469494,
"author": "Robby Cornelissen",
"author_id": 3558960,
"author_profile": "https://Stackoverflow.com/users/3558960",
"pm_score": 2,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n\nconst result = Object.entries([...arr1, ...arr2].reduce(\n (a, v) => ({ ...a, [v]: v in a }),\n {}\n)).map(([name, isSame]) => ({ name, isSame }));\n\nconsole.log(result);"
},
{
"answer_id": 74469509,
"author": "code",
"author_id": 15359157,
"author_profile": "https://Stackoverflow.com/users/15359157",
"pm_score": 0,
"selected": false,
"text": "let arr1 = ['one', 'two', 'three'];\nlet arr2 = ['four', 'one', 'two'];\n\nconsole.log(merge(arr1, arr2));\n\nfunction merge(a, b) {\n const merged = a.concat(b); // combine arrays\n const result = [];\n \n let stop = merged.length; // create a variable for when to stop\n for(let i = 0; i < stop; i++) {\n const current = merged[i];\n let same = false;\n \n // look through the rest of the array for indexes\n for(let t = i + 1; t < stop; t++) {\n if(current === merged[t]) {\n same = true;\n merged.splice(t, 1); // remove duplicate elements from the array so we don't come across it again\n stop--; // we've removed an element from the array, so we have to stop 1 earlier\n // we don't break this loop because there may be more than 2 occurences\n }\n }\n const out = { name: current };\n if(same) out.isSame = true;\n \n result.push(out);\n }\n return result;\n}"
},
{
"answer_id": 74469525,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 0,
"selected": false,
"text": "map()"
},
{
"answer_id": 74469634,
"author": "Sanusi hassan",
"author_id": 10944954,
"author_profile": "https://Stackoverflow.com/users/10944954",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one' , 'two' , 'three'];\nconst arr2 = ['four' , 'one' , 'two'];\n// returns the duplicate values in the two arrays\nconst findDuplicates = (arr) => {\n let sorted_arr = arr.slice().sort();\n let results = [];\n for (let i = 0; i < sorted_arr.length - 1; i++) {\n if (sorted_arr[i + 1] == sorted_arr[i]) {\n results.push(sorted_arr[i]);\n }\n }\n return results;\n}\n\nlet values = ([...new Set([...arr1, ...arr2])]);\nlet duplicates = findDuplicates(values);\n\nlet retval = [];\n\nfor(let i = 0; i < values.length; i++) {\n let isSame = duplicates.includes(values[i]);\n retval.push({name: values[i], isSame: isSame})\n}\n"
},
{
"answer_id": 74469684,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 0,
"selected": false,
"text": "const arr1 = ['one', 'two', 'three'];\nconst arr2 = ['four', 'one', 'two'];\n\nconst result = Array.from(new Set(arr1.concat(arr2))).reduce((p, c) => {\n const obj = { name: c };\n if (arr1.concat(arr2).join(\"\").split(c).length - 1 > 1) obj.isSame = true;\n p.push(obj)\n return p;\n}, []);\n\nconsole.log(result);"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11309195/"
] |
74,469,460
|
<p>the card counting rule is attached as below link.
<a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/counting-cards" rel="nofollow noreferrer">link</a></p>
<p>And My code is below:</p>
<pre><code>let count = 0;
function cc(card) {
// Only change code below this line
if ([2,3,4,5,6].includes(card)){
count++;
} else if ( [10, 'J', 'Q', 'K', 'A'].includes(card)) {
count--;
} else {
card = 0;
count = count;
}
return count>0?card+" Bet":card+" Hold"
// Only change code above this line
}
</code></pre>
<p>Can you please correct me why my code is wrong.. Thank you for any feedback!</p>
<p>I tried using if else statement and use includes method.. but I guess the logic required is not right..</p>
|
[
{
"answer_id": 74469750,
"author": "Lucas Vaz",
"author_id": 19375659,
"author_profile": "https://Stackoverflow.com/users/19375659",
"pm_score": 1,
"selected": false,
"text": "return count>0?card+\" Bet\":card+\" Hold\"\n"
},
{
"answer_id": 74469827,
"author": "Md. Mohaiminul Hasan",
"author_id": 9047299,
"author_profile": "https://Stackoverflow.com/users/9047299",
"pm_score": 1,
"selected": true,
"text": "return count > 0 ? count +\" Bet\" : count +\" Hold\"\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19815830/"
] |
74,469,463
|
<p>I have an array made up of data provided by a WordPress plugin, which looks something like this:</p>
<pre><code>array(
[label] => Evening,
[hour] => 15,
[minute] => 00,
[add_time] => enabled,
[zlzkrrwlwchehhtvdnmq_add_date] => 29 November 2022,
[zlzkrrwlwchehhtvdnmq_zoom_id] => null,
[zlzkrrwlwchehhtvdnmq_stock] => null,
[sfujorleiwijcczciess_add_date] => 30 November 2022
)
</code></pre>
<p>I would like to keep all the key-value pairs in the array in which the key contains either 'add_date', 'hour', or 'minute', and discard the rest.</p>
<p>Keeping all the keys containing 'add_date' works fine.</p>
<pre><code>if(strpos($key, 'add_date') == 0) {
unset($datesresult[$key]);
}
}
</code></pre>
<p>This gives me an array containing only key-value pairs related to the date:</p>
<pre><code>array(
[zlzkrrwlwchehhtvdnmq_add_date] => 29 November 2022,
[sfujorleiwijcczciess_add_date] => 30 November 2022
)
</code></pre>
<p>However, when I try to match more than one condition using the OR operator, it doesn't work. This:</p>
<pre><code>if(strpos($key, 'add_date') == 0 OR strpos($key, 'hour') == 0 OR strpos($key, 'minute') == 0) {
unset($datesresult[$key]);
}
}
</code></pre>
<p>...gives me a completely blank array.</p>
<p>I've also tried various double negatives, like</p>
<pre><code>if(!(strpos($key, 'add_date') == true || strpos($key, 'hour') == true || strpos($key, 'minute') == true)){
unset($datesresult[$key]);
}
}
</code></pre>
<p>..but I get the same result.</p>
<p>I'm certain I'm doing something wrong here, either in syntax (I can't seem to find any examples of chaining operators in conditional statements like this in the PHP docs?) or in my understanding of true/false, but I can't work out what - my PHP is incredibly rusty after a long time away from coding.</p>
<p>Any wisdom would be much appreciated!</p>
|
[
{
"answer_id": 74469816,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 2,
"selected": true,
"text": "return"
},
{
"answer_id": 74470304,
"author": "Mohammed Jhosawa",
"author_id": 5599067,
"author_profile": "https://Stackoverflow.com/users/5599067",
"pm_score": 0,
"selected": false,
"text": "preg_match"
},
{
"answer_id": 74470615,
"author": "Swadesh Ranjan Dash",
"author_id": 6385202,
"author_profile": "https://Stackoverflow.com/users/6385202",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n$array = array(\n 'label' => 'Evening', \n 'hour' => 15,\n 'minute' => 00, \n 'add_time' => 'enabled', \n 'zlzkrrwlwchehhtvdnmq_add_date' => '29 November 2022', \n 'zlzkrrwlwchehhtvdnmq_zoom_id' => null,\n 'zlzkrrwlwchehhtvdnmq_stock' => null,\n 'sfujorleiwijcczciess_add_date' => '30 November 2022',\n);\n\nvar_export(\n array_filter(\n $array,\n function($haystack ) {\n if ((is_numeric(strpos($haystack, 'hour'))) || (is_numeric(strpos($haystack, 'minute'))) || (is_numeric(strpos($haystack, 'add_date')))) {\n return $haystack;\n } \n },\n ARRAY_FILTER_USE_KEY\n )\n);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2643383/"
] |
74,469,466
|
<p>I am using typescript, and suddenly all my project became white. The only thing Highlighted are the parenthesis. I have no idea if I pressed a shortcut or something.</p>
<p>Other language like css and html have proper color, but all my Typescript is now fully white.</p>
<p>Is there some setting to check ?</p>
<p>I tried</p>
<ul>
<li>change theme to Dark+</li>
<li>clear editor history</li>
<li>restart computer
<a href="https://i.stack.imgur.com/Ai34u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ai34u.png" alt="enter image description here" /></a></li>
</ul>
|
[
{
"answer_id": 74476355,
"author": "First Arachne",
"author_id": 13818676,
"author_profile": "https://Stackoverflow.com/users/13818676",
"pm_score": 2,
"selected": false,
"text": "v5.0.20221116"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241192/"
] |
74,469,479
|
<p>How can I use python to transfer data from the "weekday" column and multiple columns (Monday, Tuesday, Wednesday...) and vice versa</p>
<pre><code> buyer weekday
0 A Saturday
1 A Friday
2 B Monday
3 B Tuesday
4 B Thursday
5 C Monday
</code></pre>
<p>Desired Outcome:</p>
<pre><code> buyer Monday Tuesday Wednesday Thursday Friday Saturday Sunday
0 A Y Y
1 B Y Y Y
2 C Y
</code></pre>
|
[
{
"answer_id": 74469753,
"author": "Алексей Р",
"author_id": 15035314,
"author_profile": "https://Stackoverflow.com/users/15035314",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],\n 'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})\nw_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\ndf = pd.crosstab(df['buyer'], df['weekday']).replace({0: '', 1: 'Y'})\ndf = df.assign(**dict.fromkeys(set(w_days).difference(df.columns), ''))[w_days].reset_index().rename_axis(columns={'weekday': ''})\nprint(df)\n"
},
{
"answer_id": 74470426,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 0,
"selected": false,
"text": "import calendar\nweekdays = list(calendar.day_name)\n\ndf = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],\n 'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})\n\ndf[\"dummy\"] = \"Y\"\n\ndf = df.pivot(index=\"buyer\", columns=\"weekday\", values=\"dummy\").reindex(labels=weekdays, axis=1).fillna(\"\").reset_index().rename_axis(columns={\"weekday\": \"\"})\n\n[Out]:\n buyer Monday Tuesday Wednesday Thursday Friday Saturday Sunday\n0 A Y Y \n1 B Y Y Y \n2 C Y \n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12769319/"
] |
74,469,480
|
<p>I want to return all the travellers who are currently travelling when I supply a <strong>From</strong> and <strong>To</strong> date. Meaning if I travel from <strong>1 Jan 2022</strong> until <strong>10 Jan 2022</strong> and I supply a <strong>From</strong> date as <strong>5 Jan 2022</strong> and a <strong>To</strong> date <strong>15 Jan 2022</strong> I must be retuned as I was travelling during that time period. So in my code below Mike must be returned.</p>
<pre><code>DECLARE @DateFrom DATE = '2022-01-05',
@DateTo DATE = '2022-01-15'
DROP TABLE IF EXISTS #Dates
CREATE TABLE #Dates
(
DepartureDate Date NULL,
ReturnDate Date NULL,
Name VARCHAR(8) NULL
)
INSERT INTO #Dates (DepartureDate, ReturnDate, Name)
VALUES ('2022-01-01', '2022-01-10', 'Mike' )
SELECT *
FROM #Dates
WHERE DepartureDate >= @DateFrom
AND ReturnDate <= @DateTo
</code></pre>
<p>If you select date range between '2021-12-01' and '2021-12-05' then Mike did not travel so should not be returned. But if you select date range between '2022-01-05' and '2022-01-15' then Mike should be returned as Mike did travel in that date range even though he did not travel all the days.</p>
|
[
{
"answer_id": 74469753,
"author": "Алексей Р",
"author_id": 15035314,
"author_profile": "https://Stackoverflow.com/users/15035314",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],\n 'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})\nw_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\ndf = pd.crosstab(df['buyer'], df['weekday']).replace({0: '', 1: 'Y'})\ndf = df.assign(**dict.fromkeys(set(w_days).difference(df.columns), ''))[w_days].reset_index().rename_axis(columns={'weekday': ''})\nprint(df)\n"
},
{
"answer_id": 74470426,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 0,
"selected": false,
"text": "import calendar\nweekdays = list(calendar.day_name)\n\ndf = pd.DataFrame({'buyer': ['A', 'A', 'B', 'B', 'B', 'C'],\n 'weekday': ['Saturday', 'Friday', 'Monday', 'Tuesday', 'Thursday', 'Monday']})\n\ndf[\"dummy\"] = \"Y\"\n\ndf = df.pivot(index=\"buyer\", columns=\"weekday\", values=\"dummy\").reindex(labels=weekdays, axis=1).fillna(\"\").reset_index().rename_axis(columns={\"weekday\": \"\"})\n\n[Out]:\n buyer Monday Tuesday Wednesday Thursday Friday Saturday Sunday\n0 A Y Y \n1 B Y Y Y \n2 C Y \n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33584/"
] |
74,469,527
|
<p>`</p>
<pre><code>function string2int(s) {
var arr = [];
for (let x of s) {
arr.push(x);
}
arr.map(function (x) {return x*1;});
var result = arr.reduce(function (x, y) {return x*10 + y;});
alert(result);
}
string2int('123456');
</code></pre>
<p>`</p>
<p>`</p>
<pre><code>function string2int(s) {
var arr = [];
for (let x of s) {
arr.push(x*1);
}
var result = arr.reduce(function (x, y) {return x*10 + y;});
alert(result);
}
string2int('123456');
</code></pre>
<p>`</p>
<p>As shown by the name of the function name string2int, the purpose of both two pieces of code is to transform string '123456' into int 123456, the idea is to trasform '123456' into arr(['1', '2', '3', '4', '5', '6']) firstly, then use each char to multiply 1 to turn elements in the array arr into int, and finally use reduce function to get the expected int 1234156. However, it turned out that only the second piece of code worked properly, the first piece would output the result 10203040506.</p>
<p>I added alert(arr); under arr.map(function (x) {return x*1;}); in the first piece of code and found that even after the execution of map function, elements in array arr were still int type, why is this? Besides, in that case, how was the final result 10203040506 got?</p>
|
[
{
"answer_id": 74469605,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 0,
"selected": false,
"text": "arr"
},
{
"answer_id": 74469653,
"author": "Lucas Vaz",
"author_id": 19375659,
"author_profile": "https://Stackoverflow.com/users/19375659",
"pm_score": 2,
"selected": true,
"text": "console.log(typeof result);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525500/"
] |
74,469,552
|
<p>I have a web with the url like this:</p>
<p><strong><a href="https://sampleweb.com" rel="nofollow noreferrer">https://sampleweb.com</a></strong></p>
<p>I display it on android using WebView. The Website have a button when I click the button the URL change to like this and go to another page:</p>
<p><strong><a href="https://sampleweb.com?34JGLSDJDJF8" rel="nofollow noreferrer">https://sampleweb.com?34JGLSDJDJF8</a></strong></p>
<p>How to do that when I click the button from WebView the ID(34JGLSDJDJF8) will Toast to android or store the ID to variable.</p>
<p>Sorry for my english.</p>
|
[
{
"answer_id": 74469605,
"author": "danh",
"author_id": 294949,
"author_profile": "https://Stackoverflow.com/users/294949",
"pm_score": 0,
"selected": false,
"text": "arr"
},
{
"answer_id": 74469653,
"author": "Lucas Vaz",
"author_id": 19375659,
"author_profile": "https://Stackoverflow.com/users/19375659",
"pm_score": 2,
"selected": true,
"text": "console.log(typeof result);\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961581/"
] |
74,469,591
|
<ol>
<li>When I started to code I had two branches Main and PopUp.</li>
<li>I was working in the PopUp branch but I had to stop because I need to work in another feature.</li>
<li>In order to work in this new feature I create another branch called Form.</li>
<li>I finished the work in Form branch and I also merged in to the main branch, after that I delete this branch.</li>
<li>Now I am continuing working in the PopUp branch but I cannot see the changes that was implemented by the Form branch.</li>
<li>When I move to the main branch I can see the changes implemented by the Form branch.</li>
<li>But when i move again to the PopUp branch I cannot see this changes.</li>
</ol>
<p>Could you please help me in order to see this changes from the PopUp branch but I dont want to lose the work that I have in the Pop Up branch.</p>
<p>The changes made in the form branch are totally separate (another section in HTML, here I also create a separate JS file and also a separate CSS file ) that the work that I am doing in the popUp branch but I would like to see the changes.</p>
<p>Thanks
Happy coding ;)</p>
<p>When I move to the PopUp branch and check it with git status told me that is uptodate.
I use terminal to interact with github.</p>
|
[
{
"answer_id": 74469612,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 1,
"selected": false,
"text": "git stash"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525738/"
] |
74,469,617
|
<p>This question is similar to <a href="https://stackoverflow.com/questions/59919887/syntax-error-lastname-must-be-an-aggregate-expression-or-appear-in-group-by">another one</a>, but I'm providing a simpler example. The <a href="https://stackoverflow.com/a/59919952/9754418">other query</a> was too advanced to make sense to me.</p>
<h2>Sample (fake) data</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>gender</th>
<th>kg</th>
</tr>
</thead>
<tbody>
<tr>
<td>4f5a07ca-02e0-8981-3c30-4d9924a169a3</td>
<td>male</td>
<td>103</td>
</tr>
<tr>
<td>4f5a07ca-02e0-8981-3c30-4d9924a169a3</td>
<td>male</td>
<td>85</td>
</tr>
<tr>
<td>4f5a07ca-02e0-8981-3c30-4d9924a169a3</td>
<td>male</td>
<td>469</td>
</tr>
<tr>
<td>e05d54e9-8292-b26c-5618-8a3712b4fc44</td>
<td>female</td>
<td>33</td>
</tr>
</tbody>
</table>
</div><h2>Desired outcome</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>gender</th>
<th>kg</th>
</tr>
</thead>
<tbody>
<tr>
<td>4f5a07ca-02e0-8981-3c30-4d9924a169a3</td>
<td>male</td>
<td>85</td>
</tr>
<tr>
<td>e05d54e9-8292-b26c-5618-8a3712b4fc44</td>
<td>female</td>
<td>33</td>
</tr>
<tr>
<td>e05d54e9-8292-b26c-5618-8a3712b4fc44</td>
<td>female</td>
<td>36</td>
</tr>
<tr>
<td>01f8bbfd-cfc6-3b97-8bc1-8da6f0b4a9a8</td>
<td>female</td>
<td>92</td>
</tr>
</tbody>
</table>
</div>
<p>(Goal is having the same id only show up once, and just picking the first match, given an ordering by <code>kg</code>)</p>
<p>QUERY:</p>
<pre><code>SELECT
p.id,
p.gender,
p.kg
FROM patient p
ORDER BY p.kg
GROUP BY 1
</code></pre>
<p>Error:</p>
<blockquote>
<p>'p.gender' must be an aggregate expression or appear in GROUP BY clause</p>
</blockquote>
<p>And if I change it to <code>GROUP BY 1, 2</code>, I get the same error, one column over:</p>
<blockquote>
<p>'p.kg' must be an aggregate expression or appear in GROUP BY clause</p>
</blockquote>
<p>How can I solve this?</p>
|
[
{
"answer_id": 74469612,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 1,
"selected": false,
"text": "git stash"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9754418/"
] |
74,469,659
|
<p>I have a system I am working with (Zapier!) which I am using to automate a workflow based on a google sheet which refreshes every hour. The Zap outputs raw row data in the following format:</p>
<p><code>list = [["header_1", "header_2", "header_3"], ["uuid_1", "first_timestamp_1", "second_timestamp_1"], ["uuid_2", "first_timestamp_2", "second_timestamp_2"], ["uuid_3", "first_timestamp_3", "second_timestamp_3"]]</code></p>
<p>What I am trying to do is transform this data into a json object that is a collection of key value pairs, with the first list element as the key and the remainder of the list elements as values. Ideally, my output would look like this:</p>
<pre><code>[
{
"header_1":"uuid_1",
"header_2":"first_timestamp_1",
"header_3":"second_timestamp_1"
}
{
"header_1":"uuid_2",
"header_2":"first_timestamp_2",
"header_3":"second_timestamp_2"
}
{
"header_1":"uuid_3",
"header_2":"first_timestamp_3",
"header_3":"second_timestamp_3"
}
]
</code></pre>
<p>This is the python I have thus far.</p>
<pre><code>list = [["header_1", "header_2", "header_3"], ["uuid_1", "first_timestamp_1", "second_timestamp_1"], ["uuid_2", "first_timestamp_2", "second_timestamp_2"], ["uuid_3", "first_timestamp_3", "second_timestamp_3"]]
row_count = len(list)
if row_count == 1:
print(null)
else:
header = list[0]
output = []
for element in list:
output.append(dict())
for i in element:
j = 0
while j < len(header):
key = header[j]
value = i
output = """+key+"":""+value+"""
j = j+1
</code></pre>
<p>At this point, it looks like my code is erroring out when I try to append the new key:value pair to the ouput, but I'm not sure if this is even the right approach to take. The error message is:</p>
<p><strong>AttributeError: 'str' object has no attribute 'append'</strong></p>
<p>Any advice or help would be appreciated!</p>
|
[
{
"answer_id": 74469937,
"author": "Iddo Sadeh",
"author_id": 3620846,
"author_profile": "https://Stackoverflow.com/users/3620846",
"pm_score": 2,
"selected": true,
"text": "output"
},
{
"answer_id": 74470003,
"author": "Mohil Patel",
"author_id": 14417726,
"author_profile": "https://Stackoverflow.com/users/14417726",
"pm_score": 0,
"selected": false,
"text": "output = \"\"\"+key+\"\":\"\"+value+\"\"\""
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4709889/"
] |
74,469,694
|
<p>I have this string:</p>
<pre><code> seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
</code></pre>
<p>given another string</p>
<pre><code>bb_seq <- "rhhhhitv"
</code></pre>
<p>What I'd like to do is to replace <code>?</code> with a character in <code>bb_seq</code> by keeping the order of <code>bb_seq</code> resulting in :</p>
<p>The total length of <code>?</code> is guaranteed to be the same with <code>bb_seq</code>.</p>
<pre><code>KrEDhhHRDDKDKDhHEhREKEitDEvKKK
</code></pre>
<p>How can I achieve that with R?</p>
<p>I tried this but failed:</p>
<pre><code> seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
bb_seq <- "rhhhhitv"
sp <- seed_pattern
gr <- gregexpr("\\?+", sp)
csml <- lapply(gr, function(sp) cumsum(attr(sp, "match.length")))
regmatches(sp, gr) <- lapply(csml, function(sp) substring(bb_seq, c(1, sp[1]), sp))
sp
# KrEDrhhHRDDKDKDrhhhHErhhhhREKErhhhhitDErhhhhitvKKK
</code></pre>
<p>I'm open to non-regex solutions.</p>
|
[
{
"answer_id": 74469728,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": false,
"text": "> target <- strsplit(seed_pattern, \"\")[[1]]\n> replacement <- strsplit(bb_seq, \"\")[[1]]\n> target[target==\"?\"] <- replacement\n> paste(target, collapse = \"\")\n[1] \"KrEDhhHRDDKDKDhHEhREKEitDEvKKK\"\n"
},
{
"answer_id": 74469847,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 1,
"selected": false,
"text": "?"
},
{
"answer_id": 74470582,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ntibble(seed_pattern, bb_seq) %>% \n separate_rows(seed_pattern, sep='\\\\?') %>% \n mutate(seed_pattern = paste(paste0(seed_pattern, substr(bb_seq, row_number(), row_number())), collapse = \"\")) %>% \n slice(1) %>% \n pull(seed_pattern)\n"
},
{
"answer_id": 74470731,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 4,
"selected": true,
"text": "regmatches(seed_pattern, gregexpr(\"\\\\?\", seed_pattern)) <- strsplit(bb_seq, \"\")\n"
},
{
"answer_id": 74478556,
"author": "Ottie",
"author_id": 17732851,
"author_profile": "https://Stackoverflow.com/users/17732851",
"pm_score": 2,
"selected": false,
"text": "regmatches"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8391698/"
] |
74,469,703
|
<p>I am attempting to send two arrays to a function using pointers.</p>
<p>Next, I attempting to assign the dereferenced values from the two *arrays (sent as arguments in the function call) to the two (non-pointer) arrays where they can be manipulated with greater ease.</p>
<p>Note: there are no objects or clesses. I don't see any resson for dynamic memory handling (new, delete).</p>
<p>Original arrays in main:</p>
<pre><code>int arr_fractions[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
int arr_converted_values[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
</code></pre>
<p>This is the function call, in main:</p>
<pre><code>arr_converted_values[2][7] = decimal_conversion(arr_decimals, *arr_converted_values, &var_fract_length);
</code></pre>
<p>Function:</p>
<pre><code>int decimal_conversion(long double* arr_temp_decimals, int* arr_converted_values, int* var_fract_length)
{
// pointer retrieval ----------------------------------------------------------------
long double arr_temp_decimals[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
int arr_temp_values[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
int var_tempt_fract_value = *var_fract_length;
for (int* var_temp_storage = 0; *var_temp_storage < *var_fract_length; *var_temp_storage++)
{
arr_temp_decimals[0][*var_temp_storage] = &arr_decimals[0][*var_temp_storage];
arr_temp_decimals[1][*var_temp_storage] = &arr_decimals[1][*var_temp_storage];
arr_temp_values[0][*var_temp_storage] = arr_converted_values[0][var_temp_storage];
arr_temp_values[1][*var_temp_storage] = arr_converted_values[1][var_temp_storage];
}
// --------------------------------------------------------------------------------------------
...
...
...
return (*arr_converted_values);
}
</code></pre>
<p>The three errors (below) that I am reciving are pointing to the array usage in the for loop, shown above.</p>
<p>E0142: expression must have pointer-to-object type but it has type -->arr_*temp_*decinmals[0[*var_temp_storage]</p>
<p>E0142: expression must have pointer-to-object type but it has type -->arr_*temp_*decinmals[1]*var_temp_storage]</p>
<p>E0020: identifier "arr_decimals" is undefined --- > &arr_decinmals[0][*var_temp_storage];</p>
|
[
{
"answer_id": 74469728,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": false,
"text": "> target <- strsplit(seed_pattern, \"\")[[1]]\n> replacement <- strsplit(bb_seq, \"\")[[1]]\n> target[target==\"?\"] <- replacement\n> paste(target, collapse = \"\")\n[1] \"KrEDhhHRDDKDKDhHEhREKEitDEvKKK\"\n"
},
{
"answer_id": 74469847,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 1,
"selected": false,
"text": "?"
},
{
"answer_id": 74470582,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ntibble(seed_pattern, bb_seq) %>% \n separate_rows(seed_pattern, sep='\\\\?') %>% \n mutate(seed_pattern = paste(paste0(seed_pattern, substr(bb_seq, row_number(), row_number())), collapse = \"\")) %>% \n slice(1) %>% \n pull(seed_pattern)\n"
},
{
"answer_id": 74470731,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 4,
"selected": true,
"text": "regmatches(seed_pattern, gregexpr(\"\\\\?\", seed_pattern)) <- strsplit(bb_seq, \"\")\n"
},
{
"answer_id": 74478556,
"author": "Ottie",
"author_id": 17732851,
"author_profile": "https://Stackoverflow.com/users/17732851",
"pm_score": 2,
"selected": false,
"text": "regmatches"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20506604/"
] |
74,469,718
|
<p>I have this generics where <code>Num</code> is defined in <a href="https://docs.rs/num/0.4.0/num/index.html" rel="nofollow noreferrer"><code>num</code> crate</a>:</p>
<pre class="lang-rust prettyprint-override"><code>//finds `x` where `f(x) == Equal` for `x ∈ [left, right)`
fn binary_search<T: Debug + Copy + PartialOrd + Num, F: FnMut(T) -> Ordering>(
mut left: T,
mut right: T, //exclusive
mut f: F,
) -> Result<T, T> {
while (left < right) {
let mid = left + (right - left) / (T::one() + T::one());
match f(mid) {
Less => left = mid + T::one(),
Greater => right = mid,
Equal => return Ok(mid),
}
}
Err(left)
}
</code></pre>
<p>This binary search works correctly for integer types but NOT for float types (like <code>f64</code>). The evil part is this:</p>
<pre class="lang-rust prettyprint-override"><code>Less => left = mid + T::one(),
</code></pre>
<p>The <code>T::one()</code> should instead be <code>1e-6</code> for float and <code>1</code> for integer. Is it possible?</p>
<p>Here's the <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=92bd28e40bb0c2e904527ad5584a451a" rel="nofollow noreferrer">Rust Playground</a> with some automated tests available. I want to make <code>binary_search_02()</code> pass without breaking <code>binary_search_01()</code>.</p>
|
[
{
"answer_id": 74469973,
"author": "John Kugelman",
"author_id": 68587,
"author_profile": "https://Stackoverflow.com/users/68587",
"pm_score": 2,
"selected": false,
"text": "Less"
},
{
"answer_id": 74470063,
"author": "ynn",
"author_id": 8776746,
"author_profile": "https://Stackoverflow.com/users/8776746",
"pm_score": 0,
"selected": false,
"text": "num::FromPrimitive"
},
{
"answer_id": 74472025,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 1,
"selected": false,
"text": "trait Delta {\n fn delta() -> Self;\n}\n\nimpl Delta for i32 {\n fn delta() -> Self { 1 }\n}\n\nimpl Delta for f32 {\n fn delta() -> Self { 1e-6 }\n}\n\nfn main() {\n println!(\"i32: {}\", i32::delta());\n println!(\"f32: {}\", f32::delta());\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8776746/"
] |
74,469,720
|
<p>I was creating an android notification app which gives notification every 15 minutes after the alarm has been set.</p>
<p>it calls first time, and shows notification but workmanager not calling every 15 minutes.</p>
<pre><code>
val myWorkRequest = PeriodicWorkRequestBuilder<ReminderWorker>(15, TimeUnit.MINUTES).build()
WorkManager.getInstance(applicationContext)
.enqueueUniquePeriodicWork("work", ExistingPeriodicWorkPolicy.REPLACE, myWorkRequest)
</code></pre>
|
[
{
"answer_id": 74469973,
"author": "John Kugelman",
"author_id": 68587,
"author_profile": "https://Stackoverflow.com/users/68587",
"pm_score": 2,
"selected": false,
"text": "Less"
},
{
"answer_id": 74470063,
"author": "ynn",
"author_id": 8776746,
"author_profile": "https://Stackoverflow.com/users/8776746",
"pm_score": 0,
"selected": false,
"text": "num::FromPrimitive"
},
{
"answer_id": 74472025,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 1,
"selected": false,
"text": "trait Delta {\n fn delta() -> Self;\n}\n\nimpl Delta for i32 {\n fn delta() -> Self { 1 }\n}\n\nimpl Delta for f32 {\n fn delta() -> Self { 1e-6 }\n}\n\nfn main() {\n println!(\"i32: {}\", i32::delta());\n println!(\"f32: {}\", f32::delta());\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17504674/"
] |
74,469,721
|
<p>i am getting the data by fetching api.
here is after fetching data from API, i am getting data something like this:</p>
<pre><code>const info={
"suggesstion":0,
"idea":{
"prod": [
{
"group": {
"subj": "English",
"class": "one",
"section": "1A"
},
},
{
"group": {
"subj": "Physics",
"class": "nine",
"section": "2A"
},
},
{
"group": {
"subj": "Math",
"class": "Ten",
"section": "3A"
},
}
]
}
}
</code></pre>
<p>Now when i try to call the data in html table, i am using a function so that i can call the values in table together. here is my function.</p>
<pre><code>const tableD= info?.idea?.prod.map((info) => {
const nS= [],
nC= [],
nSec= [];
nS.push(info.group.subj)
nC.push(info.group.class)
nSec.push(info.group.section)
let table= []
for (let a in nS) {
for (let b in nC) {
for (let c in nSec) {
const nSAll= nS[a],
nCAll= nC[b],
nSecAll= nSec[c];
table+=
`<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
}
}
}
return table;
}).join(' ');
console.log(tableD);
</code></pre>
<p>now when i try to use it in html i get this table:
<a href="https://i.stack.imgur.com/dRsP8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dRsP8.png" alt="enter image description here" /></a></p>
<p>but i want to add serial number for each row in a column like this here will be 1 ,2 ,3</p>
<p><a href="https://i.stack.imgur.com/twF2X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/twF2X.png" alt="enter image description here" /></a></p>
<p>here is my html:</p>
<pre><code><table class="demo">
<thead>
<tr>
<th>No</th>
<th>Subj</th>
<th>Class</th>
<th>Section</th>
</tr>
</thead>
<tbody>
<tr>
<td>${htmlDatasheet}</td>
</tr>
</tbody>
</table>
</code></pre>
<p>How can i do that in the function, anyone can help me?
Thanks for your trying in advance!</p>
|
[
{
"answer_id": 74469973,
"author": "John Kugelman",
"author_id": 68587,
"author_profile": "https://Stackoverflow.com/users/68587",
"pm_score": 2,
"selected": false,
"text": "Less"
},
{
"answer_id": 74470063,
"author": "ynn",
"author_id": 8776746,
"author_profile": "https://Stackoverflow.com/users/8776746",
"pm_score": 0,
"selected": false,
"text": "num::FromPrimitive"
},
{
"answer_id": 74472025,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 1,
"selected": false,
"text": "trait Delta {\n fn delta() -> Self;\n}\n\nimpl Delta for i32 {\n fn delta() -> Self { 1 }\n}\n\nimpl Delta for f32 {\n fn delta() -> Self { 1e-6 }\n}\n\nfn main() {\n println!(\"i32: {}\", i32::delta());\n println!(\"f32: {}\", f32::delta());\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20289307/"
] |
74,469,737
|
<p>I have a list with several dataframes, each dataframe correspond to an election, say 2010, 2013, ..., 2021.</p>
<p>For each dataframe, I want to add the year to every column name except the first three columns. So I'm trying to add the year to [,4:end_column] using a for loop:</p>
<pre><code>for (i in names(SECCIONES_year)) {
year <- (substr(i, nchar(i)-4, nchar(i)))
end_column <- ncol(SECCIONES_year[[i]])
past_names <- names(SECCIONES_year[[i]][ ,4:end_column])
colnames(SECCIONES_year[[i]][,4:end_column]) <- paste(past_names, year, sep="")
}
</code></pre>
<p>Unfortunately, it doesn't work but it does if I work with all column names as:</p>
<pre><code>colnames(SECCIONES_year[[i]]) <- paste(past_names, year, sep=)
</code></pre>
<p>I tried with colnames, names and setNames but failed every try.</p>
|
[
{
"answer_id": 74469838,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "base R"
},
{
"answer_id": 74486747,
"author": "René Martínez",
"author_id": 9352993,
"author_profile": "https://Stackoverflow.com/users/9352993",
"pm_score": 1,
"selected": true,
"text": "colnames(SECCIONES_year[[i]])[4:ncol(SECCIONES_year[[i]])] <- paste(past_names, year, sep=\"\")\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525851/"
] |
74,469,793
|
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Street</th>
<th>City</th>
<th>Hour of Registration</th>
</tr>
</thead>
<tbody>
<tr>
<td>hill st</td>
<td>bolton</td>
<td>11/16/2022 10:00</td>
</tr>
<tr>
<td>flo st</td>
<td>bolton</td>
<td>11/15/2022 10:10</td>
</tr>
</tbody>
</table>
</div>
<p>If city=bolton AND Hour of Registration less than or qual to <= 24hrs then delete Row</p>
<p>So basically, if I run the code against a xls file with the dataset above, only Row 1 (hill st) should be deleted. Basically something like current time - hour of registration.</p>
<p>The code I have below is able to delete a row given 1 condition but I'm not sure how to implement multiple conditions or the time</p>
<p><strong>Count is bottom up. Top down seems to mess up the counting and miss some rows</strong></p>
<pre><code>$file = 'salehouses.xls'
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# open file
$workbook = $excel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item(1)
# get max rows
$rowMax = $sheet.UsedRange.Rows.Count
for ($row = $rowMax; $row -ge 2; $row--) {
$cell = $sheet.Cells[$row, 2].Value2
if ($cell -ieq 'bolton') {
$null = $sheet.Rows($row).EntireRow.Delete() }
$Filename = 'salehouses.xls'
$workbook.SaveAs("c:\xls\salehouses.xls")
$excel.Quit()
Bigger Data set to test against as of 11/17/2022 3:50 PM where everything <24hr should be deleted.
Street City Hour Of Registeration
hill st Bolton 11/16/2022 12:28 >24hr
flow st Bolton 11/16/2022 13:39 >24hr
jane st Bolton 11/16/2022 15:00 >24hr
jack st Bolton 11/16/2022 15:00 >24hr
Gone st Bolton 11/16/2022 18:16 <24hr
top st Bolton 11/16/2022 18:27 <24hr
sale st Bolton 11/16/2022 19:18 <24hr
jack st Bolton 11/16/2022 20:14 <24hr
Gone st Bolton 11/16/2022 20:28 <24hr
top st Bolton 11/17/2022 02:51 <24hr
sale st Bolton 11/17/2022 03:02 <24hr
jack st Bolton 11/17/2022 06:21 <24hr
Gone st Bolton 11/17/2022 08:51 <24hr
</code></pre>
|
[
{
"answer_id": 74469838,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "base R"
},
{
"answer_id": 74486747,
"author": "René Martínez",
"author_id": 9352993,
"author_profile": "https://Stackoverflow.com/users/9352993",
"pm_score": 1,
"selected": true,
"text": "colnames(SECCIONES_year[[i]])[4:ncol(SECCIONES_year[[i]])] <- paste(past_names, year, sep=\"\")\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4717451/"
] |
74,469,808
|
<p>I am writing a jQuery dblclick() method. I am trying to show a hidden menu when double clicked on a button. I am creating a button named "Menu" in my html file with href attribute.</p>
<p>The href attribute in HTML file is this:</p>
<pre><code><a href="#" id="menu_link">Menu</a>
<div id="menu" style="display: none;">
<a href="https://www.youtube.com/">Youtube</a><br/>
<a href="https://www.facebook.com/">Facebook</a><br/>
<a href="https://www.apple.com/">Apple</a>
</div>
</code></pre>
<p>So, when "Menu" is double clicked it show three options - youtube,facebook,apple</p>
<p>and then in js file, I am creating a dblclick() function and giving them id "menu_link" and then using show() to display the hidden menu.</p>
<p>This is what I have in js file:</p>
<pre><code>$('#menu_link').dblclick(function(){
$('#menu').show();
});
</code></pre>
<p>It doesn't work. When I doubleclick the "menu" option it doesn't show me anything.</p>
<p>In Html file :</p>
<pre><code><a href="#" id="menu_link">Menu</a>
<div id="menu" style="display: none;">
<a href="https://www.youtube.com/">Youtube</a><br/>
<a href="https://www.facebook.com/">Facebook</a><br/>
<a href="https://www.apple.com/">Apple</a>
</div>
</code></pre>
<p>In js file :</p>
<pre><code>$(function() {
$('#menu_link').dblclick(function(){
$('#menu').show();
});
});
</code></pre>
<p>The link to the project - <a href="https://glitch.com/edit/#!/comp484-proj2-km" rel="nofollow noreferrer">https://glitch.com/edit/#!/comp484-proj2-km</a></p>
|
[
{
"answer_id": 74470842,
"author": "NoobBit",
"author_id": 15585074,
"author_profile": "https://Stackoverflow.com/users/15585074",
"pm_score": 0,
"selected": false,
"text": "<a href=\"#\" id=\"menu_link\">Menu</a>\n"
},
{
"answer_id": 74471476,
"author": "Graciela Fausten Novindri",
"author_id": 19696694,
"author_profile": "https://Stackoverflow.com/users/19696694",
"pm_score": -1,
"selected": false,
"text": "$('#menu_link').dblclick(function(){\n $('#menu').css(\"display\", \"block\");\n });\n })\n"
},
{
"answer_id": 74477122,
"author": "nenad",
"author_id": 20529108,
"author_profile": "https://Stackoverflow.com/users/20529108",
"pm_score": 0,
"selected": false,
"text": "function openMenu(){\n $(\"#menu\").css(\"display\", \"block\");\n }\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434140/"
] |
74,469,812
|
<p>I want to change the svg icon color in css, but it won't change for some reason. Please, help :
<a href="https://codepen.io/Flowersj/pen/OJExzME" rel="nofollow noreferrer">https://codepen.io/Flowersj/pen/OJExzME</a></p>
<p>I tried adding class to parent tag and trying to style it, didn't work.</p>
<p>HTML:
<code><svg class="navigation-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16"><path fill="none" d="M0 0h24v24H0z"/><path d="M18.031 16.617l4.283 4.282-1.415 1.415-4.282-4.283A8.96 8.96 0 0 1 11 20c-4.968 0-9-4.032-9-9s4.032-9 9-9 9 4.032 9 9a8.96 8.96 0 0 1-1.969 5.617zm-2.006-.742A6.977 6.977 0 0 0 18 11c0-3.868-3.133-7-7-7-3.868 0-7 3.132-7 7 0 3.867 3.132 7 7 7a6.977 6.977 0 0 0 4.875-1.975l.15-.15z" fill="rgba(0,0,0,1)"/></svg></code></p>
<p>CSS:
<code>.navigation-icon { fill: red; }</code></p>
|
[
{
"answer_id": 74469914,
"author": "AtomicUs5000",
"author_id": 17934914,
"author_profile": "https://Stackoverflow.com/users/17934914",
"pm_score": 1,
"selected": false,
"text": "body {\n background-color: black;\n}\n.nav-icon-path {\n fill: red;\n}"
},
{
"answer_id": 74470013,
"author": "ddaannnnyy",
"author_id": 9662179,
"author_profile": "https://Stackoverflow.com/users/9662179",
"pm_score": 0,
"selected": false,
"text": ".navigation-icon path {\n fill: red;\n}"
},
{
"answer_id": 74470870,
"author": "Bqardi",
"author_id": 14647816,
"author_profile": "https://Stackoverflow.com/users/14647816",
"pm_score": 0,
"selected": false,
"text": "fill=\"currentColor\""
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20343913/"
] |
74,469,814
|
<p>I'm new to Nuxt3 and I've been working on the login api inside a function. The api call works when it's outside the function, but when I put it inside a function, it returns a 419 error response.</p>
<p>this is my form:</p>
<pre><code><div>
<div class="grid grid-cols-4 gap-5"></div>
<div class="w-full max-w-xs">
<form
class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"
method="POST"
@submit.prevent="onSubmit"
>
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="email">
Email
</label>
<input
class="
shadow
appearance-none
border
rounded
w-full
py-2
px-3
text-gray-700
leading-tight
focus:outline-none focus:shadow-outline
"
id="email"
type="text"
name="email"
placeholder="Email"
v-model="form.email"
/>
</div>
<div class="mb-6">
<label
class="block text-gray-700 text-sm font-bold mb-2"
for="password"
>
Password
</label>
<input
class="
shadow
appearance-none
border
rounded
w-full
py-2
px-3
text-gray-700
mb-3
leading-tight
focus:outline-none focus:shadow-outline
"
v-model="form.password"
id="password"
name="password"
type="password"
placeholder="******************"
/>
</div>
<div class="flex items-center justify-between">
<button
class="
bg-blue-500
hover:bg-blue-700
text-white
font-bold
py-2
px-4
rounded
focus:outline-none focus:shadow-outline
"
type="submit"
>
Sign In
</button>
<a
class="
inline-block
align-baseline
font-bold
text-sm text-blue-500
hover:text-blue-800
"
href="#"
>
Forgot Password?
</a>
</div>
</form>
<p class="text-center text-gray-500 text-xs">
&copy;2020 Acme Corp. All rights reserved.
</p>
</div>
</div>
</code></pre>
<p>and this is my function:</p>
<pre><code><script setup>
const url = "http://localhost:8085/api/auth/login";
const form = reactive({
email: "janedoe123@gmail.com",
password: "jane123",
});
async function onSubmit() {
const { data, error } = await $fetch(url, {
method: "POST",
headers: {
"x-api-key": "base64:l/KMGWeUbHwHNrlQXOmpFXTafrccJ8KZvlCaTUEkSOw=",
},
body: { form },
});
console.log(data, error);
}
</script>
</code></pre>
<p>I tried ohmyfetch and lazyfetch but it still returns the same error.
but if I use it like this, without the function, it actually works and returns 200 status code. I really don't understand why it wont work inside a function.</p>
<pre><code> const { data, error } = await useFetch(
"http://localhost:8085/api/auth/login",
{
method: "POST",
headers: {
"x-api-key": "base64:l/KMGWeUbHwHNrlQXOmpFXTafrccJ8KZvlCaTUEkSOw=",
"Access-Control-Allow-Origin": "*",
},
body: {
email: "janedoe@gmail.com",
password: "janedoe123",
},
}
</code></pre>
<p>);</p>
|
[
{
"answer_id": 74469914,
"author": "AtomicUs5000",
"author_id": 17934914,
"author_profile": "https://Stackoverflow.com/users/17934914",
"pm_score": 1,
"selected": false,
"text": "body {\n background-color: black;\n}\n.nav-icon-path {\n fill: red;\n}"
},
{
"answer_id": 74470013,
"author": "ddaannnnyy",
"author_id": 9662179,
"author_profile": "https://Stackoverflow.com/users/9662179",
"pm_score": 0,
"selected": false,
"text": ".navigation-icon path {\n fill: red;\n}"
},
{
"answer_id": 74470870,
"author": "Bqardi",
"author_id": 14647816,
"author_profile": "https://Stackoverflow.com/users/14647816",
"pm_score": 0,
"selected": false,
"text": "fill=\"currentColor\""
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19885196/"
] |
74,469,824
|
<p>I have a dependent variable name list as</p>
<pre><code>depend<-c('a', 'b', 'c')
</code></pre>
<p>And I have a formula for regression model can be defined as</p>
<pre><code>1_equ<-d~e
</code></pre>
<p>I would like to automatically switch the dependent variable of that formula by using update.</p>
<p>I have tried</p>
<pre><code>for ( i in depend) {
equ_name<-assign(paste0("1_equ_", i), depend[i])
equ_name<-update(1_equ, paste(depend[i]) ~ .)
}
</code></pre>
<p>Seems like it does not work, it only extract the string, but could not switch the variable.</p>
<p>The print results are</p>
<pre><code>chr NA
</code></pre>
<p>I would like three outpus:</p>
<pre><code>1_equ_a: a~e
1_equ_b: b~e
1_equ_c: c~e
</code></pre>
|
[
{
"answer_id": 74469894,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "\"~ .\""
},
{
"answer_id": 74469945,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 1,
"selected": false,
"text": "call"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17496231/"
] |
74,469,850
|
<pre><code> <div class="hero">
<div class="container">
</div>
</div>
</body>
</code></pre>
<pre><code> height: 100%;
background: hsl(212, 45%, 89%);
}
.container {
margin: auto;
height: 100%;
background-color: white;
padding: 1em;
border-radius: 1em;
margin: 1.1em;
}
@media only screen and (min-width: 1440px) {
body {
height: 100vh;
display: grid;
place-items: center;
}
.container {
margin: auto;
width: 45%;
}
</code></pre>
<p>Mobile version just doesn't vertically center.
Desktop ver is centered but there's a scrollbar because of body: 100vh;</p>
<p>Editing the margin doesn't seem to help.</p>
|
[
{
"answer_id": 74469878,
"author": "Ankit",
"author_id": 19757319,
"author_profile": "https://Stackoverflow.com/users/19757319",
"pm_score": 1,
"selected": false,
"text": "flex-box"
},
{
"answer_id": 74470129,
"author": "Rocky Barua",
"author_id": 16801529,
"author_profile": "https://Stackoverflow.com/users/16801529",
"pm_score": 1,
"selected": true,
"text": "min-height: 100vh"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20451255/"
] |
74,469,853
|
<p>Currently I'm working with a team on a project. Due to some reasons my computer needs some special settings so I want to keep a local file different from git remote, which won't be uploaded when I git push. What should I do?</p>
<p>I guess I may need to do some modifications in .gitignore, but that will have a global effect.</p>
|
[
{
"answer_id": 74469878,
"author": "Ankit",
"author_id": 19757319,
"author_profile": "https://Stackoverflow.com/users/19757319",
"pm_score": 1,
"selected": false,
"text": "flex-box"
},
{
"answer_id": 74470129,
"author": "Rocky Barua",
"author_id": 16801529,
"author_profile": "https://Stackoverflow.com/users/16801529",
"pm_score": 1,
"selected": true,
"text": "min-height: 100vh"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20525919/"
] |
74,469,857
|
<p>I have what I thought was a typical application with React front end and Spring boot as the backend. I'm trying to setup security to use Azure active directory to authenticate and authorize users. Authentication works but authorization doesn't</p>
<p>The UI part is simple and works, I'm using MSAL to authenticate and get the account. I can see in console log that everything is ok from that perspective. I also see the following in the token request/response:
<a href="https://login.microsoftonline.com/*%7BXX%7D*/oauth2/v2.0/token" rel="nofollow noreferrer">https://login.microsoftonline.com/*{XX}*/oauth2/v2.0/token</a></p>
<pre><code>scope: "User.Read profile openid email"
token_type: "Bearer"
</code></pre>
<p>The issue I'm having is in the backend, I'm getting the following error:</p>
<pre><code>Failed to authorize filter invocation [GET /api/document/list] with attributes [hasAuthority('SCOPE_User.Read')] using AffirmativeBased [DecisionVoters=[org.springframework.security.web.access.expression.WebExpressionVoter@470b5213], AllowIfAllAbstainDecisions=false]
Sending JwtAuthenticationToken [Principal=org.springframework.security.oauth2.jwt.Jwt@43ebd8ff, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[]] to access denied handler since access is denied
</code></pre>
<p>As you could see for some reason on the resource server we are not getting the scopes the user has access to (i.e. User.Read)</p>
<p>Spring Security setup:</p>
<pre><code>@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
http.authorizeRequests((authorize) -> authorize
.mvcMatchers("/**").hasAuthority("SCOPE_User.Read") // .permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
}
</code></pre>
<p>In application.properties:</p>
<pre><code>spring.security.oauth2.resourceserver.jwt.issuer-uri=https://login.microsoftonline.com/{XX}/v2.0
</code></pre>
|
[
{
"answer_id": 74470200,
"author": "ch4mp",
"author_id": 619830,
"author_profile": "https://Stackoverflow.com/users/619830",
"pm_score": 1,
"selected": false,
"text": ".well-known/openid-configuration"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2402867/"
] |
74,469,866
|
<blockquote>
</blockquote>
<pre><code>def formater_damier(joueurs):
joueurs = [
{"nom": "1", "pos": [5, 5]},
{"nom": "2", "pos": [8, 6]}
]
grille = (
( ' ----------------------------------- \n'
'9 | . . . . . . . . . | \n'
' | | \n'
'8 | . . . . . . . . . | \n'
' | | \n'
'7 | . . . . . . . . . | \n'
' | | \n'
'6 | . . . . . . . . . | \n'
' | | \n'
'5 | . . . . . . . . . | \n'
' | | \n'
'4 | . . . . . . . . . | \n'
' | | \n'
'3 | . . . . . . . . . | \n'
' | | \n'
'2 | . . . . . . . . . | \n'
' | | \n'
'1 | . . . . . . . . . | \n'
'--| ----------------------------------- \n'
f' | 1 2 3 4 5 6 7 8 9 \n'))
return grille
example grille = (
( ' ----------------------------------- \n'
'9 | . . . . . . . . . | \n'
' | | \n'
'8 | . . . . . . . . . | \n'
' | | \n'
'7 | . . . . . . . . . | \n'
' | | \n'
'6 | . . . . . . . 2 . | \n'
' | | \n'
'5 | . . . . 1 . . . . | \n'
' | | \n'
'4 | . . . . . . . . . | \n'
' | | \n'
'3 | . . . . . . . . . | \n'
' | | \n'
'2 | . . . . . . . . . | \n'
' | | \n'
'1 | . . . . . . . . . | \n'
'--| ----------------------------------- \n'
f' | 1 2 3 4 5 6 7 8 9 \n'))
</code></pre>
<p>i would like to put the position of my players and my walls on my board, but I don't know how to do it. I don't think that's the right way to build the empty board and add the elements afterward. I made an example of how it is supposed to be. I just want to understand, so if someone can put me in the right way, that's will be great.</p>
|
[
{
"answer_id": 74470200,
"author": "ch4mp",
"author_id": 619830,
"author_profile": "https://Stackoverflow.com/users/619830",
"pm_score": 1,
"selected": false,
"text": ".well-known/openid-configuration"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18766563/"
] |
74,469,899
|
<p>I want to send a post request using ballerina to get a access token from the Choreo Dev Portal. I am able to do it using postman. But unable to make it work in Ballerina code level. it gives 415 - unsupported media type error. Need some Help in Ballerina</p>
<pre><code>import ballerina/http;
import ballerina/io;
import ballerina/url;
public function main() returns error? {
final http:Client clientEndpoint = check new ("https://sts.choreo.dev");
http:Request request = new();
string payload = string`grant_type=urn:ietf:params:oauth:grant-type:token-exchange&
subject_token=*******&
subject_token_type=urn:ietf:params:oauth:token-type:jwt&
requested_token_type=urn:ietf:params:oauth:token-type:jwt`;
string encodedPayload = check url:encode(payload, "UTF-8");
io:print(encodedPayload);
request.setTextPayload(encodedPayload);
request.addHeader("Authorization","Basic *****");
request.addHeader("Content-Type","application/x-www-form-urlencoded");
io:print(request.getTextPayload());
json resp = check clientEndpoint->post("/oauth2/token",request);
io:println(resp.toJsonString());
}
</code></pre>
<p>I was expecting an access token from Choreo Devportal for the particular application.</p>
|
[
{
"answer_id": 74470279,
"author": "Chamil E",
"author_id": 6822363,
"author_profile": "https://Stackoverflow.com/users/6822363",
"pm_score": 1,
"selected": false,
"text": "Content-type"
},
{
"answer_id": 74479711,
"author": "Thenusan Santhirakumar",
"author_id": 11291692,
"author_profile": "https://Stackoverflow.com/users/11291692",
"pm_score": 2,
"selected": false,
"text": "import ballerina/http;\nimport ballerina/io;\nimport ballerina/mime;\n\npublic function main() returns error? {\n\n // Creates a new client with the backend URL.\n final http:Client clientEndpoint = check new (\"https://sts.choreo.dev\");\n json response = check clientEndpoint->post(\"/oauth2/token\", \n {\n \"grant_type\": \"urn:ietf:params:oauth:grant-type:token-exchange\",\n \"subject_token_type\": \"urn:ietf:params:oauth:token-type:jwt\",\n \"requested_token_type\":\"urn:ietf:params:oauth:token-type:jwt\",\n \"subject_token\":\"****\"\n },\n {\n \"Authorization\": \"Basic ****\"\n }, \n mime:APPLICATION_FORM_URLENCODED\n \n );\n io:println(response.toString());\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11291692/"
] |
74,469,911
|
<p>I wouldl like to extract the Y-M-D information from the following html.</p>
<pre><code>Created at</th><td><span><time datetime="2001-06-01"
</code></pre>
<pre><code>date= [re.search("Created at</th><td><span><time datetime=([0-9A-Za-z\&;]*)", address).group(1)]
date
</code></pre>
<p>I have tried this code but it does not work.Do you have any ideas?</p>
|
[
{
"answer_id": 74470279,
"author": "Chamil E",
"author_id": 6822363,
"author_profile": "https://Stackoverflow.com/users/6822363",
"pm_score": 1,
"selected": false,
"text": "Content-type"
},
{
"answer_id": 74479711,
"author": "Thenusan Santhirakumar",
"author_id": 11291692,
"author_profile": "https://Stackoverflow.com/users/11291692",
"pm_score": 2,
"selected": false,
"text": "import ballerina/http;\nimport ballerina/io;\nimport ballerina/mime;\n\npublic function main() returns error? {\n\n // Creates a new client with the backend URL.\n final http:Client clientEndpoint = check new (\"https://sts.choreo.dev\");\n json response = check clientEndpoint->post(\"/oauth2/token\", \n {\n \"grant_type\": \"urn:ietf:params:oauth:grant-type:token-exchange\",\n \"subject_token_type\": \"urn:ietf:params:oauth:token-type:jwt\",\n \"requested_token_type\":\"urn:ietf:params:oauth:token-type:jwt\",\n \"subject_token\":\"****\"\n },\n {\n \"Authorization\": \"Basic ****\"\n }, \n mime:APPLICATION_FORM_URLENCODED\n \n );\n io:println(response.toString());\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20462164/"
] |
74,469,920
|
<p>How to replace all "pi" from a string by "3.14"? Example: <code>INPUT = "xpix" ___ OUTPUT = "x3.14x"</code> for a string, not character array.</p>
<p>This doesn't work:</p>
<pre><code>#include<iostream>
using namespace std;
void replacePi(string str)
{
if(str.size() <=1)
return ;
replacePi(str.substr(1));
int l = str.length();
if(str[0]=='p' && str[1]=='i')
{
for(int i=l;i>1;i--)
str[i+2] = str[i];
str[0] = '3';
str[1] = '.';
str[2] = '1';
str[3] = '4';
}
}
int main()
{
string s;
cin>>s;
replacePi(s);
cout << s << endl;
}
</code></pre>
|
[
{
"answer_id": 74470356,
"author": "sxu",
"author_id": 19694882,
"author_profile": "https://Stackoverflow.com/users/19694882",
"pm_score": 0,
"selected": false,
"text": "string::find"
},
{
"answer_id": 74470848,
"author": "A M",
"author_id": 9666018,
"author_profile": "https://Stackoverflow.com/users/9666018",
"pm_score": 1,
"selected": false,
"text": "std::regex_replace"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16827777/"
] |
74,469,926
|
<p>I wanted to show a tooltip when I tap my gesture detector and do different things when the <code>GestureDetector</code> is long pressed, How can I achieve this? I have written some code about it but on long press still shows a tooltip rather than accessing my <code>selectDate()</code> function</p>
<p>this is my current code:</p>
<pre><code> GestureDetector(
onTap: () {
final dynamic tooltip = _toolTipKey.currentState;
tooltip.ensureTooltipVisible();
},
onLongPress: () {
if (widget.ticketData['status'] == 'active') {
showDialog(
context: context,
builder: (context) {
return ReusableConfirmationDialog(
titleText: 'changeDueDateTitle'.tr(),
contentText: 'changeDueDateDesc'.tr(),
declineButtonText: 'cancel'.tr(),
confirmButtonText: 'change'.tr(),
onDecline: () {
Navigator.pop(context);
},
onConfirm: () {
DevMode.log('start changing the due date');
_selectDate(context);
},
);
},
);
}
},
child: Tooltip(
key: _toolTipKey,
message: "Hello",
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 5),
decoration: BoxDecoration(
color: formBackgroundColor,
borderRadius: BorderRadius.circular(15),
),
child: Row(
children: [
Image.asset(
'assets/logo/calendar.png',
width: 20,
height: 20,
),
const SizedBox(width: 5),
],
),
),
),
),
</code></pre>
|
[
{
"answer_id": 74470020,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "triggerMode: TooltipTriggerMode.manual"
},
{
"answer_id": 74470089,
"author": "Ravin Laheri",
"author_id": 19440771,
"author_profile": "https://Stackoverflow.com/users/19440771",
"pm_score": 0,
"selected": false,
"text": "triggerMode: TooltipTriggerMode.tap,"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15529116/"
] |
74,469,962
|
<p>I am trying to run this code in Oracle database but it's giving error :</p>
<blockquote>
<pre><code> ORA-00904: "vw_d"."cl_name": invalid identifier
</code></pre>
</blockquote>
<p>What's wrong with the query:</p>
<pre><code>SELECT *
FROM vw_doctrans vw_d
WHERE (SELECT COUNT(*)
FROM (SELECT *
FROM vw_doctrans vw
WHERE vw.cl_name = vw_d.cl_name
GROUP BY vw.country)) > 1
</code></pre>
<p>I tried this query in MySQL and works fine</p>
|
[
{
"answer_id": 74470020,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "triggerMode: TooltipTriggerMode.manual"
},
{
"answer_id": 74470089,
"author": "Ravin Laheri",
"author_id": 19440771,
"author_profile": "https://Stackoverflow.com/users/19440771",
"pm_score": 0,
"selected": false,
"text": "triggerMode: TooltipTriggerMode.tap,"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526174/"
] |
74,469,980
|
<p>In C++ you can make concepts that check for specific type equality:</p>
<pre><code>template<typename T> concept Int = std::is_same_v<T, int>;
template<typename T> concept String = std::is_same_v<T, std::string>;
</code></pre>
<p>Is it possible to make a concept that checks for type equality of any type, so I could make templates looking something like this:</p>
<pre><code>template<ValidType<int>... Ints> void passInts(Ints... ints) {}
template<ValidType<std::string>... Strings> void passStrings(Strings... strings) {}
</code></pre>
<p>That way I would only need to write a single concept checking for type equality. I know I could use <code>conjunction</code> for this but I think concepts are much cleaner.</p>
|
[
{
"answer_id": 74470014,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 0,
"selected": false,
"text": "template<typename T, typename U> concept ValidType = std::is_same_v<T, U>;\n"
},
{
"answer_id": 74470032,
"author": "Nicol Bolas",
"author_id": 734069,
"author_profile": "https://Stackoverflow.com/users/734069",
"pm_score": 4,
"selected": true,
"text": "std::same_as"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19333949/"
] |
74,469,982
|
<p>I am using Python to create a very basic calculator. for whatever reason the numbers will only add - they will not do any of the other functions. Please help!</p>
<pre><code>equation_type = input("What kind of math do you want to do? ")
equation_type = equation_type.lower()
first_number = float(input("What is the first number? "))
second_number = float(input("What is the 2nd number? "))
if equation_type == "add" or "addition":
result = first_number + second_number
elif equation_type == "subtract" or "subtraction":
result = (first_number - second_number)
elif equation_type == "multiply" or "multiplication":
result = first_number * second_number
elif equation_type == "divide" or "division":
result = first_number / second_number
else:
print("not a valid entry :/")
print(result)
</code></pre>
|
[
{
"answer_id": 74470011,
"author": "DeusDev",
"author_id": 10312417,
"author_profile": "https://Stackoverflow.com/users/10312417",
"pm_score": 0,
"selected": false,
"text": "equation_type == \"add\" or equation_type == \"addition\":"
},
{
"answer_id": 74470015,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 3,
"selected": true,
"text": "equation_type == \"add\" or \"addition\""
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14841552/"
] |
74,469,996
|
<p>Currently, I have a dropdown list and 1-25 values in the dropdown.</p>
<p>The current one is I want to make a checkbox for those values instead of choosing multiple.</p>
<p>Is there any way to add a checkbox for those?</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>var mtf = document.getElementById('affectedwaferid').selectedOptions;
var affectedwf = Array.from(mtf).map(({ value }) => value);
//alert(affectedwf);
document.getElementById("selected-result").innerHTML = affectedwf; </code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="afwid">
<label class="control-label col-sm-4" for="affectedwaferid" style="margin-left: 1px;">Affected Wafer ID : <span id="selected-result"></span></label>
<div class="col-sm-4">
<p class="form-control-static" style="margin-top: -6px;">
<select class="form-control" id="affectedwaferid" name="affectedwaferid" multiple>
<option value="" selected > Select Quantity</option>
<?php
//echo $cbo_oorigsite;
?>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
</p>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74470011,
"author": "DeusDev",
"author_id": 10312417,
"author_profile": "https://Stackoverflow.com/users/10312417",
"pm_score": 0,
"selected": false,
"text": "equation_type == \"add\" or equation_type == \"addition\":"
},
{
"answer_id": 74470015,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 3,
"selected": true,
"text": "equation_type == \"add\" or \"addition\""
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74469996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20496420/"
] |
74,470,059
|
<p>I want help to calculate the RMSE of two groups from the dataset looking like this:</p>
<pre><code>structure(list(machine = c("B", "B", "B", "B", "B", "B", "B",
"B", "B", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"),
measured = c(14.47, 15.33, 18.56, 14.89, 17.24, 16.25, 13,
20.52, 18.06, 13.09, 16.88, 15.92, 14.47, 18.63, 13.88, 16.32,
13.83, 11.67, 13.42), predicted = c(15.83, 16, 17.87, 14.21,
17.77, 14.14, 12.01, 19.31, 16.98, 13.19, 15.6, 17.16, 16.07,
17.38, 17.99, 17.86, 18.54, 10.79, 16.06)), class = "data.frame", row.names = c(NA,
-19L))
</code></pre>
<p>I want to calculate RMSE for each Machine and if possible add it to my scatterplot.</p>
<p>I attempted this</p>
<pre><code>fr <- read.csv(file.choose())
ggplot(fr, aes(measured, predicted, colour = machine)) +
geom_point(size=2)+
geom_smooth(method="lm",se=FALSE) +
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label), sep = "*\", \"*")))+
theme_set(theme_bw(base_size=16))+
theme(axis.line = element_line(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
</code></pre>
<p>I couldn’t find a way to automatically calculate the RMSE for my model.</p>
|
[
{
"answer_id": 74470011,
"author": "DeusDev",
"author_id": 10312417,
"author_profile": "https://Stackoverflow.com/users/10312417",
"pm_score": 0,
"selected": false,
"text": "equation_type == \"add\" or equation_type == \"addition\":"
},
{
"answer_id": 74470015,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 3,
"selected": true,
"text": "equation_type == \"add\" or \"addition\""
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20052956/"
] |
74,470,064
|
<p>I am looking to determine the difference in days by groups across two columns and two rows. Essentially subtract from the End Day by the subsequent Start Day in the subsequent row and record the difference as new column in the data frame and start over when a new group (ID) has been identified.</p>
<pre><code>Start_Date End_Date ID
2014-05-09 2015-05-08 01
2015-05-09 2016-05-08 01
2016-05-11 2017-05-10 01
2017-05-11 2018-05-10 01
2016-08-29 2017-08-28 02
2017-08-29 2018-08-28 02
</code></pre>
<p>The result should be something like table below.</p>
<pre><code>Start_Date End_Date ID Days_Difference
2014-05-09 2015-05-08 01 NA
2015-05-09 2016-05-08 01 01
2016-05-11 2017-05-10 01 03
2017-05-11 2018-05-10 01 01
2016-08-29 2017-08-28 02 NA
2017-08-29 2018-08-28 02 01
</code></pre>
<p>Essentially I want to take the difference of the End Date and its left diagonal Start date across groups (ID). I am having a really hard time with this one. I don't think my code would be helpful. Any solution using tidyverse, data.table, or base R would be greatly appreciated!</p>
|
[
{
"answer_id": 74470084,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "lead"
},
{
"answer_id": 74471978,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "data.table"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526140/"
] |
74,470,083
|
<p>I try every method it can be convert .text to int but I got error like this.</p>
<p>mycode</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=libralyServer;Integrated Security=True");
con1.Open();
SqlCommand cmd1 = new SqlCommand("insert into bookData values(@bookName,@bookWriter,@bookTotel)", con1);
cmd1.Parameters.AddWithValue("@bookName", textBox1.Text);
cmd1.Parameters.AddWithValue("@bookWriter", textBox2.Text);
cmd1.Parameters.AddWithValue("@bookTotel",int.Parse(textBox2.Text));//have error
cmd1.ExecuteNonQuery();
con1.Close();
}
</code></pre>
<p><a href="https://i.stack.imgur.com/SG5O3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SG5O3.png" alt="enter image description here" /></a></p>
<p>how to fix it? I try to search many how to on internet, but I still can't fix this error.</p>
|
[
{
"answer_id": 74470084,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "lead"
},
{
"answer_id": 74471978,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "data.table"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19626264/"
] |
74,470,102
|
<p>Why is this still returning a count of 3 ?</p>
<pre><code>$arr =
[
[
'slug' => 'products-services-pricing',
'text' => 'Products/Services and Pricing',
],
[
'slug' => 'promotions-plan',
'text' => 'Promotions Plan',
],
(1 == 2) ?
[
'slug' => 'distribution-plan',
'text' => 'Distribution Plan',
] : null,
];
echo "Count = ".count($arr)."\n";
print_r($arr);
</code></pre>
<p>My <code>foreach</code> is getting messed up. PHP 8.0<br>
I cannot do condition check in <code>foreach</code> because I am using <code>count</code>.</p>
|
[
{
"answer_id": 74470334,
"author": "José Carlos PHP",
"author_id": 2826112,
"author_profile": "https://Stackoverflow.com/users/2826112",
"pm_score": 2,
"selected": true,
"text": "null"
},
{
"answer_id": 74470613,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 0,
"selected": false,
"text": "...(1 == 2)\n ? [['slug' => 'distribution-plan', 'text' => 'Distribution Plan']]\n : [],\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126833/"
] |
74,470,113
|
<p>To briefly explain the code, we have a simple stream builder which fetches data in the Firestore Database and then we return and display the value of 'username' on the screen.</p>
<p>We also have a TextField in the same widget & I've noticed that whenever I click on it, it seems to rebuild and fetch the data again. The goal would be to avoid rebuilding whenever the device's keyboard opens or closes as this would cost unnecessary reads. Any idea how I can achieve the same result but without the rebuilding effect?</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../models/user.dart';
class Admin extends StatefulWidget {
const Admin({
Key? key,
}) : super(key: key);
@override
State<Admin> createState() => _AdminState();
}
class _AdminState extends State<Admin> {
final TextEditingController _userController = TextEditingController();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
elevation: 4,
toolbarHeight: 50,
backgroundColor: Colors.white,
actions: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
width: MediaQuery.of(context).size.width,
child: const Text('Admin',
style: TextStyle(
color: Colors.black,
fontSize: 20,
letterSpacing: 0.3,
fontWeight: FontWeight.w500)),
),
]),
body: Column(
children: [
TextField(
controller: _userController,
decoration: InputDecoration(
labelText: 'User',
),
),
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.limit(1)
.snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Row();
}
return snapshot.data?.docs.length != 0
? SingleChildScrollView(
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data?.docs.length,
itemBuilder: (context, index) {
User user = User.fromSnap(
snapshot.data!.docs[index],
);
return Text('${user.username}');
},
),
)
: Row();
},
),
],
),
),
);
}
}
</code></pre>
|
[
{
"answer_id": 74477832,
"author": "jaimin rana",
"author_id": 14153321,
"author_profile": "https://Stackoverflow.com/users/14153321",
"pm_score": 2,
"selected": true,
"text": "@override\nvoid initState() {\n super.initState();\n streamData = FirebaseFirestore.instance\n .collection('users')\n .limit(1)\n .snapshots();\n\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20269646/"
] |
74,470,130
|
<p>I have this question in my mind from past couple of days. What is the best way to capture data from an API in our redux store. I am using redux toolkit.</p>
<p>For e.g below is the code -</p>
<pre><code>const userSlice = createSlice({
name: 'user',
initialState,
reducers: {},
extraReducers: builder => {
builder
.addCase(authUser.pending, state => {
state.loading = 'pending';
})
.addCase(authUser.fulfilled, (state: LoginState, action: PayloadAction<Data>) => {
state.loading = 'succeeded';
state.entities.push(action.payload);
})
},
});
</code></pre>
<p>Like I have created an array, <code>entities</code> and pushed all the data inside it. And if I have to access this data inside my react components, it looks like this -</p>
<p><code> const role = useSelector((state: RootState) => state?.user?.entities[0]?.roles[0])</code></p>
<p>Is it fine or is there a better way of doing it. ?</p>
|
[
{
"answer_id": 74477832,
"author": "jaimin rana",
"author_id": 14153321,
"author_profile": "https://Stackoverflow.com/users/14153321",
"pm_score": 2,
"selected": true,
"text": "@override\nvoid initState() {\n super.initState();\n streamData = FirebaseFirestore.instance\n .collection('users')\n .limit(1)\n .snapshots();\n\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19290397/"
] |
74,470,137
|
<p><strong>Solved</strong></p>
<p>I have the current dataframe df:</p>
<pre><code>Farmer Good Fruit
Matt 5
Tom 10
</code></pre>
<p>which I want to change to:</p>
<pre><code>Farmer Fruit
Matt 5
Tom 10
</code></pre>
<p>I am wondering if I can convert any column name containing Fruit, such as "Good Fruit" or "Dope Fruit", to simply "Fruit".</p>
<p>By using</p>
<pre><code>df.columns.str.replace('.*Fruit*', 'Fruit', regex=True)
</code></pre>
<p>I was able to successfully change the column name to "Fruit". However, I'm not sure how to apply this change to the actual dataframe, df.</p>
<pre><code>Index(['Farmer', 'Fruit'], dtype='object')
</code></pre>
<p><strong>edit</strong>
Thanks to @wjandrea for the solution. The code needs to be changed to:</p>
<pre><code>df.columns = df.columns.str.replace('.*Fruit*', 'Fruit', regex=True)
</code></pre>
|
[
{
"answer_id": 74470249,
"author": "Mohammed Jhosawa",
"author_id": 5599067,
"author_profile": "https://Stackoverflow.com/users/5599067",
"pm_score": 0,
"selected": false,
"text": "df.rename(columns = {'Good Fruit':'Fruit'}, inplace = True)\n"
},
{
"answer_id": 74470294,
"author": "shadowtalker",
"author_id": 2954547,
"author_profile": "https://Stackoverflow.com/users/2954547",
"pm_score": 1,
"selected": false,
"text": "import re\n\ndf = df.rename(columns=lambda c: \"Fruit\" if \"Fruit\" in c else c)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18613413/"
] |
74,470,141
|
<pre><code> comp_dict = {'ap': {'val': 0.3, 'count': 3}, 'sd': {'val': 0.02, 'count': 1}, 'ao': {'val': 0.01, 'count': 1}}
avg_rate = {}
for value in comp_dict.keys():
avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']
print(avg_rate[value])
</code></pre>
<p>It seems like the output I got only generates the average I want for the last element and I am wondering how is it possible for me to get the mean for all three elements.</p>
<p>the output i got now is just <code>0.01</code></p>
<p>My desired output would be something like <code>{ap:0.1,sd:0.02,ao:0.01}</code></p>
<p>Thanks a lot!</p>
|
[
{
"answer_id": 74470218,
"author": "pomseb",
"author_id": 14825527,
"author_profile": "https://Stackoverflow.com/users/14825527",
"pm_score": 0,
"selected": false,
"text": "avg_rate = {k:comp_dict[k]['val']/comp_dict[k]['count'] for k in comp_dict for k2 in comp_dict[k]}\n"
},
{
"answer_id": 74471991,
"author": "ramsf",
"author_id": 19876917,
"author_profile": "https://Stackoverflow.com/users/19876917",
"pm_score": 1,
"selected": false,
"text": "avg_rate = {}\n for value in comp_dict.keys():\n avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']\n print(avg_rate)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526299/"
] |
74,470,156
|
<p>I am using js to monitor the mouse xy and when I shrink the window, the media applies to a value that I did not ask. What can be causing this calculus error? Is it the browser-side scrollbar? I am using Brave browser to test this, and it doesn't matter if I try "min-width" or "max-width", the value I set, it only applies less than it, as the images show below.</p>
<p><a href="https://i.stack.imgur.com/SC7P8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SC7P8.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/YxQ1i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YxQ1i.png" alt="enter image description here" /></a></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
body {
background-image: linear-gradient(45deg, #222, #444, black);
min-height: 100vh;
}
@media only screen and (max-width: 1000px) {
body {
background-image: linear-gradient(45deg, purple, yellow, black);
}
}
</style>
</head>
<body>
<span class="window-properties"></span>
<script>
let windowEl = document.querySelector('.window-properties')
setInterval(() => {
let width = windowEl.innerWidth || document.documentElement.clientWidth ||
document.body.clientWidth;
let height = windowEl.innerHeight|| document.documentElement.clientHeight||
document.body.clientHeight;
windowEl.innerHTML = `${width}, ${height}`
}, 1)
</script>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74470218,
"author": "pomseb",
"author_id": 14825527,
"author_profile": "https://Stackoverflow.com/users/14825527",
"pm_score": 0,
"selected": false,
"text": "avg_rate = {k:comp_dict[k]['val']/comp_dict[k]['count'] for k in comp_dict for k2 in comp_dict[k]}\n"
},
{
"answer_id": 74471991,
"author": "ramsf",
"author_id": 19876917,
"author_profile": "https://Stackoverflow.com/users/19876917",
"pm_score": 1,
"selected": false,
"text": "avg_rate = {}\n for value in comp_dict.keys():\n avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']\n print(avg_rate)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13661572/"
] |
74,470,162
|
<p>I'm trying to read lines from a file, and try to put it in html by using beautiful soup.
each line will be appended into a list, and using for loop, I appended them in the string, and '\n' in every end of the line.
for example,</p>
<pre><code>lines = [a,b,c,d]
string = ''
for line in lines:
string = string + line + '\n'
</code></pre>
<p>and then using beautiful soup, I added string into html.</p>
<pre><code>soup = BeautifulSoup(open('simple.html'), 'html.parser')
sentences = soup.new_tag('p')
sentences.string = string
soup.body.div.append(sentences)
</code></pre>
<p>then, I noticed that <code>'\n'</code> is not breaking lines, so I changed bit</p>
<pre><code>sentences.string = string.replace('\n', '<br>')
</code></pre>
<p>but in the html, it appears as <code>&lt;br&gt;</code></p>
<p>how can I convert this escaped characters back to normal so I can break the line?</p>
|
[
{
"answer_id": 74470218,
"author": "pomseb",
"author_id": 14825527,
"author_profile": "https://Stackoverflow.com/users/14825527",
"pm_score": 0,
"selected": false,
"text": "avg_rate = {k:comp_dict[k]['val']/comp_dict[k]['count'] for k in comp_dict for k2 in comp_dict[k]}\n"
},
{
"answer_id": 74471991,
"author": "ramsf",
"author_id": 19876917,
"author_profile": "https://Stackoverflow.com/users/19876917",
"pm_score": 1,
"selected": false,
"text": "avg_rate = {}\n for value in comp_dict.keys():\n avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']\n print(avg_rate)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14399629/"
] |
74,470,164
|
<p>I want to determine complexity for second_max function but how do i do it, how to determine time complexity for my code and for any other code</p>
<pre><code>from random import randint
import sys
from bigO import BigO
def r_array(r_i= 0,r_e = 100,step=10):
return [randint(r_i, r_e) for i in range(r_i, r_e, step)]
def second_max(arr):
n_max = -sys.maxsize
n_s_max = -sys.maxsize
for i in range(0, len(arr)):
if arr[i] > n_max:
n_s_max = n_max
n_max = arr[i]
elif (arr[i] < n_max and arr[i] > n_s_max):
n_s_max = arr[i]
return n_s_max
_lib = BigO()
cmplx = _lib.test(second_max, "")
array = r_array(step=20)
print(f"original array: {array}")
second_large_num = second_max(array)
print(second_large_num)
</code></pre>
<p>I consider my code(second_max) has o(n) complexity but not sure.</p>
<p>i tried bigO module but it returns</p>
<pre><code>for i in range(len(array) - 1):
TypeError: object of type 'int' has no len()
</code></pre>
|
[
{
"answer_id": 74472217,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 3,
"selected": true,
"text": "arr"
},
{
"answer_id": 74472261,
"author": "Ralf Kleberhoff",
"author_id": 8207228,
"author_profile": "https://Stackoverflow.com/users/8207228",
"pm_score": 1,
"selected": false,
"text": "n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19759808/"
] |
74,470,177
|
<p>I've set up a C# project that uses swashbuckler swagger. I've been able to create an Authorize button on one of my definitions successfully. But when adding a new definition, I can't Authorize that new definition, and all my endpoints return a 401 unauthorized. I can only Authorize on the default definition.</p>
<p>In startup.cs I have:</p>
<pre><code> public void ConfigureServices(IServiceCollection services)
{
......
services.AddAuthentication("Basic")
.AddScheme<BasicAuthenticationOptions, CustomAuthenticationHandler>("Basic", null);
services.AddHttpContextAccessor();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "App-Test", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = $"desc",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}, new List<string>()
}
});
});
......
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "App-Test v1"); // able to auth
c.SwaggerEndpoint("/$openapi", "OData raw OpenAPI"); // no auth
});
}
// accesses middleware developed from a demo here:
// https://github.com/OData/AspNetCoreOData/tree/main/sample/ODataRoutingSample/OpenApi
app.UseOdataOpenApi()
......
}
</code></pre>
<p>In the Configure() method, I created two definitions. One titled "App-Test v1", and another one titled "OData raw OpenApi."</p>
<p>When I run my app and navigate to http://localhost:5000/swagger, I'm able to view the definition for "App-Test v1" and able to Authorize. Therefore, all my endpoints on this definition can be executed.</p>
<p>However, when I switch to a different definition, "Odata raw OpenApi", the Authorize button is no longer there. When I try to execute one of my endpoints, I get a 401 unauthorized.</p>
<p>Is there a way to bring over the bearer token from the first definition to the second? Or create a new Authorize button on the second definition? I've read the documents and I couldn't figure out how to do this.</p>
|
[
{
"answer_id": 74470201,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "[AllowAnonymous]\npublic ActionResult SomeMethod()\n{\n}\n"
},
{
"answer_id": 74470567,
"author": "sksallaj",
"author_id": 1449587,
"author_profile": "https://Stackoverflow.com/users/1449587",
"pm_score": 2,
"selected": true,
"text": " ......\n\n OpenApiConvertSettings settings = new OpenApiConvertSettings\n {\n PathProvider = provider,\n ServiceRoot = BuildAbsolute(context, prefixName)\n };\n\n var securiteSchemes = new Dictionary<string, OpenApiSecurityScheme>();\n securiteSchemes.Add(\"Bearer\"\n , new OpenApiSecurityScheme\n {\n Description = $\"desc\",\n Name = \"Authorization\",\n In = ParameterLocation.Header,\n Type = SecuritySchemeType.ApiKey,\n Scheme = \"bearer\"\n });\n\n var securiteRequirements = new List<OpenApiSecurityRequirement>();\n securiteRequirements.Add(\n new OpenApiSecurityRequirement\n {\n {\n new OpenApiSecurityScheme\n {\n Reference = new OpenApiReference\n {\n Type = ReferenceType.SecurityScheme,\n Id = \"Bearer\"\n }\n }, new List<string>()\n }\n });\n\n var openDoc = model.ConvertToOpenApi(settings);\n openDoc.Components.SecuritySchemes = securiteSchemes;\n openDoc.SecurityRequirements = securiteRequirements;\n\n return openDoc;\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1449587/"
] |
74,470,202
|
<p>I recently switched to Python from Java for development and is still not used to some of the implicitness of Python programming.</p>
<p>I have a class which I have defined some class variables, how can I access the class variables within a method in Python?</p>
<pre class="lang-py prettyprint-override"><code>class Example:
CONSTANT_A = "A"
@staticmethod
def mymethod():
print(CONSTANT_A)
</code></pre>
<p>The above code would give me the error message: <code>"CONSTANT_A" is not defined"</code> by Pylance.</p>
<p>I know that I can make this work using <code>self.CONSTANT_A</code>, but <code>self</code> is referring to the Object, while I am trying to directly access to the Class variable (specifically constants).</p>
<hr />
<h3>Question</h3>
<p>How can I directly access Class variables in Python and not through the instance?</p>
|
[
{
"answer_id": 74470250,
"author": "Jongwook Choi",
"author_id": 1534182,
"author_profile": "https://Stackoverflow.com/users/1534182",
"pm_score": 3,
"selected": true,
"text": "self."
},
{
"answer_id": 74470260,
"author": "sahasrara62",
"author_id": 5086255,
"author_profile": "https://Stackoverflow.com/users/5086255",
"pm_score": 1,
"selected": false,
"text": "<class_name>.<variable>"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4776227/"
] |
74,470,221
|
<p>I am trying to run below simple program with virtual threads on my intellij with java19 version selected.</p>
<h2>Code</h2>
<pre><code>public class VTSimple {
public static void main(String[] args) {
Runnable runnable = () -> System.out.println("Inside Runnable");
Thread.startVirtualThread(runnable);
}
}
</code></pre>
<h3>pom.xml</h3>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.java19</groupId>
<artifactId>java19-explore</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
</properties>
</project>
</code></pre>
<h2>Project Settings</h2>
<p>SDK - <code>19</code></p>
<p>Language Level - <code>X Experimental Features as last version shown was </code>17(preview)<code> in Language Level dropdown</code> Also Tried <code>SDK Default</code> Option as well.</p>
<h2>Error</h2>
<p>When I ran the program it gave me below error</p>
<pre><code>java: invalid source release 18 with --enable-preview
(preview language features are only supported for release 19)
</code></pre>
<h2>Few Trials</h2>
<p>I tried to add <code>--enable-preview</code> in VM Options of this small program and as well as compiler settings in preferences but it didn't work.</p>
<h3>Edit 1</h3>
<p><a href="https://i.stack.imgur.com/DrTEx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DrTEx.jpg" alt="intellij compiler preferences" /></a></p>
<h2>Setup Details :</h2>
<p><code>Mac OS Air M1 : 12.1 Monterey</code></p>
<p>Intellij Version : <code>IntelliJ IDEA 2021.3.3 (Community Edition) Build #IC-213.7172.25, built on March 15, 2022</code></p>
<p>Java Version : <code>openjdk 19.0.1 2022-10-18</code></p>
<p><code>OpenJDK Runtime Environment (build 19.0.1+10-21)</code></p>
<p><code>OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)</code></p>
<h2>Edit 2</h2>
<p>Updated Intellij to version <code>IntelliJ IDEA 2022.2.3 (Community Edition)</code> and java version 19 was showing in language level.
But still there is an error</p>
<pre><code>java: ofVirtual() is a preview API and is disabled by default.
(use --enable-preview to enable preview APIs)
</code></pre>
<p>Note : I have already passed <code>--enable-preview</code> in VM Options of program and Compiler settings in preferences.</p>
|
[
{
"answer_id": 74470250,
"author": "Jongwook Choi",
"author_id": 1534182,
"author_profile": "https://Stackoverflow.com/users/1534182",
"pm_score": 3,
"selected": true,
"text": "self."
},
{
"answer_id": 74470260,
"author": "sahasrara62",
"author_id": 5086255,
"author_profile": "https://Stackoverflow.com/users/5086255",
"pm_score": 1,
"selected": false,
"text": "<class_name>.<variable>"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8017666/"
] |
74,470,232
|
<p>I am trying to create a 2D array that I will use to plot a heatmap.</p>
<p>The array needs to be n by n and have the highest value be at its epicenter with diminishing values further away like in the diagram below.</p>
<p>How could I do that?</p>
<p><a href="https://i.stack.imgur.com/Fwd1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fwd1t.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74470577,
"author": "aspiringroboticist",
"author_id": 4639701,
"author_profile": "https://Stackoverflow.com/users/4639701",
"pm_score": 2,
"selected": true,
"text": "\nimport numpy as np\nimport matplotlib.pyplot as plt\n# creating array using numpy\narray=np.ones((9,9),dtype=int)\narray[1:8,1:8]=2\narray[2:7,2:7]=3\narray[3:6,3:6]=4\narray[4,4]=5\nprint(array)\n\nfig, ax = plt.subplots()\nim = ax.imshow(array,cmap=\"PuBuGn\") # cmap can be Greys, YlGnBu, PuBuGn, BuPu etc\n# Create colorbar\ncbar = ax.figure.colorbar(im, ax=ax,ticks=[1,2,3,4,5])\ncbar.ax.set_ylabel(\"My bar [1-5]\", rotation=-90, va=\"bottom\")\nax.set_xticklabels([])\nax.set_yticklabels([])\nax.set_title(\"My heatmap\")\nfig.tight_layout()\nplt.show()\n"
},
{
"answer_id": 74471024,
"author": "aspiringroboticist",
"author_id": 4639701,
"author_profile": "https://Stackoverflow.com/users/4639701",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nlim=100\narr=np.ones((lim,lim),dtype=int)\nfor i in range(1,lim):\n arr[i:len(arr)-i,i:len(arr)-i]=i+1\n \nfig, ax = plt.subplots()\nim = ax.imshow(arr,cmap=\"Purples\") # cmap can be Greys, YlGnBu, PuBuGn, BuPu etc\n# Create colorbar\ncbar = ax.figure.colorbar(im, ax=ax,ticks=list(range(1,lim,5)))\ncbar.ax.set_ylabel(\"My bar [1-50]\", rotation=-90, va=\"bottom\")\nax.set_xticklabels([])\nax.set_yticklabels([])\n\n# Show all ticks and label them with the respective list entries\nax.set_title(\"My heatmap\")\nfig.tight_layout()\nplt.show()\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16762426/"
] |
74,470,240
|
<pre><code>lst1 = [
{"id": "A", "a": "one"},
{"id": "B", "b": "two"}
]
lst2 = [
{"id": "A", "a1": "Three"},
{"id": "B", "b1": "Four"},
{"id": "C", "c1": "Four"}
]
lst3 = [
{"id": "A", "c1": "Five"},
{"id": "B", "d1": "Six"}
]
a = lst1+lst2+lst3
res = [
{'id': 'A', 'a': 'one'},
{'id': 'B', 'b': 'two'},
{'id': 'A', 'a1': 'Three'},
{'id': 'B', 'b1': 'Four'},
{'id': 'C', 'c1': 'Four'},
{'id': 'A', 'c1': 'Five'},
{'id': 'B', 'd1': 'Six'}
]
</code></pre>
<p>I want to group by Id the res will look like this</p>
<pre><code>res = [
{'id': 'A', 'a': 'one','a1': 'Three','c1': 'Five'},
{'id': 'B', 'b': 'two', 'b1': 'Four', 'd1': 'Six'},
{'id': 'C', 'c1': 'Four'},
]
</code></pre>
<p>What I have tried:</p>
<pre><code>result = []
for l1, l2,l3 in zip(lst1, lst2,lst3):
result.append({**l1 , **l2 , **l3})
print(result)
</code></pre>
|
[
{
"answer_id": 74470413,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 2,
"selected": true,
"text": "arr = [\n {'id': 'A', 'a': 'one'},\n {'id': 'B', 'b': 'two'},\n {'id': 'A', 'a1': 'Three'},\n {'id': 'B', 'b1': 'Four'},\n {'id': 'C', 'c1': 'Four'},\n {'id': 'A', 'c1': 'Five'}, \n {'id': 'B', 'd1': 'Six'}\n ]\n\nres_dict = {d['id']:{'id':d['id']} for d in arr}\nfor d in arr:\n res_dict[d['id']].update(d)\nres = list(res_dict.values())\n"
},
{
"answer_id": 74470423,
"author": "John Lehmann",
"author_id": 2716887,
"author_profile": "https://Stackoverflow.com/users/2716887",
"pm_score": 0,
"selected": false,
"text": "def coalesce(updates: list[dict[str,str]], join_key):\n res = {}\n for upd in updates:\n for rec in upd:\n key = rec[join_key]\n if not key in res:\n res[key] = {join_key: key}\n res[key].update(rec)\n return res.values()\n\n\nrecs = [lst1, lst2, lst3]\nfor value in coalesce(recs, \"id\"):\n print(value)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128618/"
] |
74,470,272
|
<p>I have the following image, but i need the blue part to be inside the white div. tried with overflow:hidden but doesn't work. how can i make it not to be visible and retain the border radius of the white div.</p>
<p><a href="https://i.stack.imgur.com/B1gyd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B1gyd.jpg" alt="enter image description here" /></a></p>
<pre><code><div class="qrcode" style=" z-index: 1;display: block; margin: auto; text-align: center; height: 250px; width: 300px; border-radius: 4%; background-color: #ffffff;">
<div class="brand" style=" background-color:rgb(0, 214, 255); height: 260px; width:50px;">
</div>
</div>
</code></pre>
|
[
{
"answer_id": 74470413,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 2,
"selected": true,
"text": "arr = [\n {'id': 'A', 'a': 'one'},\n {'id': 'B', 'b': 'two'},\n {'id': 'A', 'a1': 'Three'},\n {'id': 'B', 'b1': 'Four'},\n {'id': 'C', 'c1': 'Four'},\n {'id': 'A', 'c1': 'Five'}, \n {'id': 'B', 'd1': 'Six'}\n ]\n\nres_dict = {d['id']:{'id':d['id']} for d in arr}\nfor d in arr:\n res_dict[d['id']].update(d)\nres = list(res_dict.values())\n"
},
{
"answer_id": 74470423,
"author": "John Lehmann",
"author_id": 2716887,
"author_profile": "https://Stackoverflow.com/users/2716887",
"pm_score": 0,
"selected": false,
"text": "def coalesce(updates: list[dict[str,str]], join_key):\n res = {}\n for upd in updates:\n for rec in upd:\n key = rec[join_key]\n if not key in res:\n res[key] = {join_key: key}\n res[key].update(rec)\n return res.values()\n\n\nrecs = [lst1, lst2, lst3]\nfor value in coalesce(recs, \"id\"):\n print(value)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14510035/"
] |
74,470,315
|
<p>I am new using .NET MAUI and my issue is very simple but I could not find a way to solve this, I am trying to get any component by its x:Name using Mvvm pattern.</p>
<p>is it possible through ViewModels? For example I have a login page after clicking button I want this button to get blocked to prevent double clicks.</p>
<p><strong>Login.xaml</strong></p>
<pre><code><ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Ventas_Citel.Views.Login.Login"
xmlns:viewmodel="clr-namespace:Sales.ViewModels.Login"
Title="">
<VerticalStackLayout
//... login page xaml form ...
<Button Text="Log In" WidthRequest="200" CornerRadius="5" HorizontalOptions="Center" Command="{Binding LoginCommand}" x:Name="loginButton"/>
//... login page xaml form ...
</VerticalStackLayout>
</code></pre>
<p><strong>Login.xaml.cs</strong></p>
<pre><code> using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Maui.Alerts;
public partial class Login : ContentPage
{
public Login(LoginViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
}
</code></pre>
<p><strong>loginViewModel</strong></p>
<pre><code> public partial class LoginViewModel : ObservableObject
{
[RelayCommand]
async void Login()
{
if (!string.IsNullOrWhiteSpace(Email) && !string.IsNullOrWhiteSpace(Password))
{
// is there a way to call loginButton component?????
// i need to disable it with loginButton.IsEnable = false;
loginButton.IsEnable = false // doesnt work loginButton doesnt exist
// if there is any error i need to enable it again so the user can re enter
// his/her credentials if it fails
loginButton.IsEnable = true;
}
}
}
</code></pre>
<p>How do I solve this?</p>
|
[
{
"answer_id": 74470796,
"author": "Sandman",
"author_id": 6070324,
"author_profile": "https://Stackoverflow.com/users/6070324",
"pm_score": 2,
"selected": false,
"text": "IsLoginButtonEnabled"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091709/"
] |
74,470,339
|
<p>I'm trying to access string value from TempData from the script tag inside <code>.cshtml</code> file.</p>
<pre><code><script>
var FromComTaskLibType = '@TempData["FromComTaskLibType"]';
console.log(FromComTaskLibType.toString())
</script>
</code></pre>
<p>Using this, I am getting value as <code>AAAA</code> instead of getting like <code>'AAAA'</code>. I have called them with <code>.toString()</code>. Still it is not working.</p>
<p>In controller, I am assigning this value like this:</p>
<pre><code>public ActionResult LoginFromCOM(string libType)
{
TempData["FromComTaskLibType"] = libType;
//...
}
</code></pre>
<p>Here value of <code>libType</code> is coming as <code>"AAAA"</code></p>
|
[
{
"answer_id": 74470557,
"author": "Sajjad Emami",
"author_id": 9858518,
"author_profile": "https://Stackoverflow.com/users/9858518",
"pm_score": 0,
"selected": false,
"text": "ViewBag"
},
{
"answer_id": 74470915,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 2,
"selected": true,
"text": "convert to string"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17864851/"
] |
74,470,345
|
<p>How to increase the Until Activity time to more than 7 days in Azure Data factory<strong>strong text</strong></p>
|
[
{
"answer_id": 74485059,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "@range(1, maxNum)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17155606/"
] |
74,470,368
|
<p>I have a .tif file about the ground temperature of a certain region on Earth and I would like to find out the coordinates of the region.</p>
<p>Here is a link to the file I am working on:
<a href="https://drive.google.com/file/d/1wG-qUjshBFQdeHaYYsUsWQToEVvDy2HM/view?usp=share_link" rel="nofollow noreferrer">2017001D.tif</a></p>
<p>Using <code>raster</code> package in <code>R</code>, I was able to load the .tif file as <code>RasterLayer</code> class.</p>
<p>I can extract the coordinate information as</p>
<pre><code>> T001D = raster::raster("2017001D.tif")
> T001D
class : RasterLayer
dimensions : 4255, 5213, 22181315 (nrow, ncol, ncell)
resolution : 1000, 1000 (x, y)
extent : -2926932, 2286068, 1740497, 5995497 (xmin, xmax, ymin, ymax)
crs : NA
source : 2017001D.tif
names : X2017001D
> coords <- raster::xyFromCell(T001D, seq_len(ncell(T001D)))
> head(coords)
x y
[1,] -2926432 5994997
[2,] -2925432 5994997
[3,] -2924432 5994997
[4,] -2923432 5994997
[5,] -2922432 5994997
[6,] -2921432 5994997
</code></pre>
<p>I also used <code>terra</code> package to load it as <code>SpatRaster</code> class and when I do so I found more info:</p>
<pre><code>> T001D = terra::rast("2017001D.tif")
> T001D
class : SpatRaster
dimensions : 4255, 5213, 1 (nrow, ncol, nlyr)
resolution : 1000, 1000 (x, y)
extent : -2926932, 2286068, 1740497, 5995497 (xmin, xmax, ymin, ymax)
coord. ref. : AEA_WGS_1984
source : 2017001D.tif
name : 2017001D
</code></pre>
<p>The coordinate system info seems to be <code>AEA_WGS_1984</code>. I looked for it online and found this post:<a href="https://stackoverflow.com/questions/43215686/how-to-convert-wgs84-to-lat-long-using-r">How to convert WGS84 to Lat/Long using R</a> which is similar to my question except I don't have a "zone" number.</p>
<p>It mentioned <code>sp</code> package and I feel like I need help with the functions in it now, such as the <code>CRS</code> syntax in <code>spTransform()</code> function. Can someone help me with this? Thank you</p>
|
[
{
"answer_id": 74485059,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "@range(1, maxNum)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526292/"
] |
74,470,410
|
<p>How do you take an email_list with emails in the format first.last@domain.com and append unique names to a new update_list? I would use this update_list and convert it to CamelCase, but I'm not sure how to take only part of an index to search for duplicates. Is there some way to use regex? Keep getting TpeError: expected string or bytes-like object.</p>
<pre><code>import re
input_list = []
email_list = []
dup_email_list = []
domain_gmail = []
domain_outlook = []
dup_domain_gmail = []
dup_domain_outlook = []
update_list = []
camel_list = []
n = 0
while n < 5:
input_list = []
email = []
# input_string split by ','; ignores whitespace
input_string = input('enter first, last name, ID and email domain: ')
if input_string == 'done':
n=5
break
else:
input_list = [x.strip() for x in input_string.split(',')]
print(input_list)
# convert input_list into email format first.last@domain.com
email = "{0}.{1}@{3}.com".format(*input_list)
# convert email to lowercase
email_lower =email.lower()
print(email)
# check ID validity (9 digits)
if input_list[2].isdigit() and len(input_list[2]) == 9:
print('valid ID')
continue
else:
print('invalid ID')
n = 0
# check domain validity (gmail or outlook)
if input_list[3] == 'gmail':
email_list.append(email)
domain_gmail.append(email)
n = 0
elif input_list[3] == 'outlook':
email_list.append(email)
domain_outlook.append(email)
n = 0
else:
print('invalid domain!')
n = 0
if n == 5:
# append unique email_list indexes to dup_email_list
for x in email_list:
if x not in dup_email_list:
dup_email_list.append(x)
# append unique emails from domain_gmail to new list
for x in domain_gmail:
if x not in dup_domain_gmail:
dup_domain_gmail.append(x)
# append unique emails from domain_outlook to new list
for x in domain_outlook:
if x not in dup_domain_outlook:
dup_domain_outlook.append(x)
# append dup_email_list to update_list
for string in dup_email_list:
update_list = re.match(r'[a-z]{1}[.]{1}[a-z]{1}', dup_email_list)
# append names from update_list to camel_list in CamelCase format FirstLast
for x in dup_email_list:
while i < len.update_list[i]:
camel_list = re.split(r'[a-z]{1}[.]{1}[a-z]{1}', dup_email_list)
# print cases
print('mail list: ', dup_email_list)
print('After grouping: ', dup_domain_gmail, dup_domain_outlook)
print('After updating: ', update_list)
print('CamelCase list: ', camel_list)
</code></pre>
|
[
{
"answer_id": 74485059,
"author": "HimanshuSinha-msft",
"author_id": 11137679,
"author_profile": "https://Stackoverflow.com/users/11137679",
"pm_score": 0,
"selected": false,
"text": "@range(1, maxNum)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17416196/"
] |
74,470,419
|
<p>I'm trying to click load more button several times using selenium, however I cannot click load more button (it is even not a button...)<br />
When I try to click it, it shows error <code>element click intercepted: Element is not clickable at point</code> even after I explicitly code <code>wait.until(EC.element_to_be_clickable</code>)</p>
<p>I wonder what can be wrong with my code. The code I'm using is</p>
<pre><code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import time
url = "https://www.architectural-review.com/buildings/house"
options = webdriver.ChromeOptions()
driver = webdriver.Chrome()
driver.get(url)
# accept cookies
wait0 = WebDriverWait(driver, 10)
cookie_button = wait0.until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[6]/button[1]')))
cookie_button.click()
print("loading more projects ...")
count=5
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[2]/div/div[3]/section[5]/div/div[5]/a')))
print(element)
print("now element is clickable")
while count>1:
element.click();
count-=1
print(count)
</code></pre>
<p>and the HTML looks like (it's not a button, not sure whether this matters)</p>
<pre><code><div class="view-more">
<a href="#" class="cpb-bottom-more-news-link dynamic-loader" data-term-id="869" data-block-id="7" data-offset="18" data-load-number="4" data-resulting-class="fourth-post" data-exclude="MzE4Mzk5LDMxODM2MCwzMTc2MDAsNjUyNjEsNjQzMTMsNjQzMTgsNjQyNzMsNjMyNTc=">Load More </a>
</div>
</code></pre>
|
[
{
"answer_id": 74472042,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 3,
"selected": true,
"text": "style"
},
{
"answer_id": 74472488,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 1,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport base64\nfrom tqdm import tqdm ## if using Jupyter, do `from tqdm.notebook import tqdm`\nimport pandas as pd\n\nheaders = {\n 'referer': 'https://www.architectural-review.com/buildings/house',\n 'x-requested-with': 'XMLHttpRequest',\n 'accept-language': 'en-US,en;q=0.9',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\ns = requests.Session()\ns.headers.update(headers)\nbig_list = []\nfor x in tqdm(range(0, 50, 4)):\n url = f'https://www.architectural-review.com/wp-admin/admin-ajax.php?action=lazy-load&offset={x}&term_id=869&block_id=7&class=fourth-post&load_number=4&exclude=MzE4Mzk5LDMxODM2MCwzMTc2MDAsNjUyNjEsNjQzMTMsNjQzMTgsNjQyNzMsNjMyNTcsMzI2NzE2LDMyNjY5OSwzNDY3MSwzMjg3MzgsMTc5ODY1LDE3OTgzNSwxNzk3NjgsMTc5NTk4LDg3NDgyLDY3Mjk2LDY1NjIwLDYzNjQwLDYzMzgyLDYzMzQzLDYzMjk3LDYyOTMxLDYyOTI1LDYyMTA2LDYwOTE4LDU3MjMyLDU3MTE0LDU3MTAzLDU3MDg4LDU3MDgxLDU3MDc1LDU2OTkzLDU2OTc4'\n r = s.get(url)\n soup = bs(base64.b64decode(r.json()['body']), 'html.parser')\n houses = soup.select('div[class=\"lazy-post fourth-post\"]')\n for house in houses:\n title = house.select_one('h2').get_text(strip=True)\n author = house.select_one('span[class=\"tie-author\"]').get_text(strip=True)\n url = house.select_one('h2').parent.get('href')\n big_list.append((title, author, url))\ndf = pd.DataFrame(big_list, columns=['title', 'author', 'url'])\nprint(df)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14755028/"
] |
74,470,425
|
<p>I have a type like this</p>
<pre><code>type d = {
(e: 'edit', value: boolean): void;
(e: 'download', value: boolean): void;
(e: 'delete', value: boolean): void;
}
</code></pre>
<p>I want to set the type of a function, which will accept only <code>'edit' | 'download' | 'delete'</code> i.e. all the e values of type d.</p>
<p>e.g.</p>
<pre><code>function myFunc(e: ??what type??) {
}
myFunc('edit'); // valid type
myFunc('some') // invalid type
</code></pre>
|
[
{
"answer_id": 74472042,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 3,
"selected": true,
"text": "style"
},
{
"answer_id": 74472488,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 1,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport base64\nfrom tqdm import tqdm ## if using Jupyter, do `from tqdm.notebook import tqdm`\nimport pandas as pd\n\nheaders = {\n 'referer': 'https://www.architectural-review.com/buildings/house',\n 'x-requested-with': 'XMLHttpRequest',\n 'accept-language': 'en-US,en;q=0.9',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\ns = requests.Session()\ns.headers.update(headers)\nbig_list = []\nfor x in tqdm(range(0, 50, 4)):\n url = f'https://www.architectural-review.com/wp-admin/admin-ajax.php?action=lazy-load&offset={x}&term_id=869&block_id=7&class=fourth-post&load_number=4&exclude=MzE4Mzk5LDMxODM2MCwzMTc2MDAsNjUyNjEsNjQzMTMsNjQzMTgsNjQyNzMsNjMyNTcsMzI2NzE2LDMyNjY5OSwzNDY3MSwzMjg3MzgsMTc5ODY1LDE3OTgzNSwxNzk3NjgsMTc5NTk4LDg3NDgyLDY3Mjk2LDY1NjIwLDYzNjQwLDYzMzgyLDYzMzQzLDYzMjk3LDYyOTMxLDYyOTI1LDYyMTA2LDYwOTE4LDU3MjMyLDU3MTE0LDU3MTAzLDU3MDg4LDU3MDgxLDU3MDc1LDU2OTkzLDU2OTc4'\n r = s.get(url)\n soup = bs(base64.b64decode(r.json()['body']), 'html.parser')\n houses = soup.select('div[class=\"lazy-post fourth-post\"]')\n for house in houses:\n title = house.select_one('h2').get_text(strip=True)\n author = house.select_one('span[class=\"tie-author\"]').get_text(strip=True)\n url = house.select_one('h2').parent.get('href')\n big_list.append((title, author, url))\ndf = pd.DataFrame(big_list, columns=['title', 'author', 'url'])\nprint(df)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277696/"
] |
74,470,431
|
<p>For example, if there is a table named paper, I execute sql with
[ select paper.user_id, paper.name, paper.score from paper where user_id in (201,205,209……) ]</p>
<p>I observed that when this statement is executed, index will only be used when the number of "in" is less than a certain number. and the certain number is dynamic.
For example,when the total number of rows in the table is 4000 and cardinality is 3939, the number of "in" must be less than 790,MySQL will execute index query.
(View MySQL explain. If <790, type=range; if >790, type=all)
when the total number of rows in the table is 1300000 and cardinality is 1199166, the number of "in" must be less than 8500,MySQL will execute index query.</p>
<p>The result of this experiment is very strange to me.</p>
<p>I imagined that if I implemented this "in" query, I would first find in (max) and in (min), and then find the page where in (max) and in (min) are located,Then exclude the pages before in (min) and the pages after in (max). This is definitely faster than performing a full table scan.</p>
<p>Then, my test data can be summarized as follows:
Data in the table 1 to 1300000
Data of "in" 900000 to 920000</p>
<p>My question is, in a table with 1300000 rows of data, why does MySQL think that when the number of "in" is more than 8500, it does not need to execute index queries?</p>
<p>mysql version 5.7.20</p>
<p>In fact, this magic number is 8452. When the total number of rows in my table is 600000, it is 8452. When the total number of rows is 1300000, it is still 8452. Following is my test screenshot</p>
<p>When the number of in is 8452, this query only takes 0.099s.
<a href="https://i.stack.imgur.com/LDENl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LDENl.png" alt="enter image description here" /></a>
Then view the execution plan. range query.</p>
<p><a href="https://i.stack.imgur.com/kzWah.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kzWah.png" alt="enter image description here" /></a></p>
<p>If I increase the number of in from 8452 to 8453, this query will take 5.066s, even if I only add a duplicate element.</p>
<p><a href="https://i.stack.imgur.com/0gXYt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0gXYt.png" alt="enter image description here" /></a></p>
<p>Then view the execution plan. type all.
<a href="https://i.stack.imgur.com/hweOD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hweOD.png" alt="enter image description here" /></a></p>
<p>This is really strange. It means that if I execute the query with "8452 in" first, and then execute the remaining query, the total time is much faster than that of directly executing the query with "8453 in".</p>
<p>who can debug MySQL source code to see what happens in this process?</p>
<p>thanks very much.</p>
|
[
{
"answer_id": 74472042,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 3,
"selected": true,
"text": "style"
},
{
"answer_id": 74472488,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 1,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport base64\nfrom tqdm import tqdm ## if using Jupyter, do `from tqdm.notebook import tqdm`\nimport pandas as pd\n\nheaders = {\n 'referer': 'https://www.architectural-review.com/buildings/house',\n 'x-requested-with': 'XMLHttpRequest',\n 'accept-language': 'en-US,en;q=0.9',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\ns = requests.Session()\ns.headers.update(headers)\nbig_list = []\nfor x in tqdm(range(0, 50, 4)):\n url = f'https://www.architectural-review.com/wp-admin/admin-ajax.php?action=lazy-load&offset={x}&term_id=869&block_id=7&class=fourth-post&load_number=4&exclude=MzE4Mzk5LDMxODM2MCwzMTc2MDAsNjUyNjEsNjQzMTMsNjQzMTgsNjQyNzMsNjMyNTcsMzI2NzE2LDMyNjY5OSwzNDY3MSwzMjg3MzgsMTc5ODY1LDE3OTgzNSwxNzk3NjgsMTc5NTk4LDg3NDgyLDY3Mjk2LDY1NjIwLDYzNjQwLDYzMzgyLDYzMzQzLDYzMjk3LDYyOTMxLDYyOTI1LDYyMTA2LDYwOTE4LDU3MjMyLDU3MTE0LDU3MTAzLDU3MDg4LDU3MDgxLDU3MDc1LDU2OTkzLDU2OTc4'\n r = s.get(url)\n soup = bs(base64.b64decode(r.json()['body']), 'html.parser')\n houses = soup.select('div[class=\"lazy-post fourth-post\"]')\n for house in houses:\n title = house.select_one('h2').get_text(strip=True)\n author = house.select_one('span[class=\"tie-author\"]').get_text(strip=True)\n url = house.select_one('h2').parent.get('href')\n big_list.append((title, author, url))\ndf = pd.DataFrame(big_list, columns=['title', 'author', 'url'])\nprint(df)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15654534/"
] |
74,470,542
|
<pre><code>library(data.table)
table1 <- data.table(id1 = c(1324, 2324, 29, 29, 1010, 1010),
type = c(1, 1, 2, 1, 1, 1),
class = c("A", "A", "B", "D", "D", "A"),
number = c(1, 98, 100, 100, 70, 70))
table2 <- data.table(id2 = c(1998, 1998, 2000, 2000, 2000, 2010, 2012, 2012),
type = c(1, 1, 3, 1, 1, 5, 1, 1),
class = c("D", "A", "D", "D", "A", "B", "A", "A"),
min_number = c(34, 0, 20, 45, 5, 23, 1, 1),
max_number = c(50, 100, 100, 100, 100, 9, 10, 100))
> table1
id1 type class number
1: 1324 1 A 1
2: 2324 1 A 98
3: 29 2 B 100
4: 29 1 D 100
5: 1010 1 D 70
6: 1010 1 A 70
> table2
id2 type class min_number max_number
1: 1998 1 D 34 50
2: 1998 1 A 0 100
3: 2000 3 D 20 100
4: 2000 1 D 45 100
5: 2000 1 A 5 100
6: 2010 5 B 23 9
7: 2012 1 A 1 10
8: 2012 1 A 1 100
</code></pre>
<p><strong>Step 1.</strong> I have two tables, and I would like to merge them based on <code>type</code>, <code>class</code>, and whether <code>number</code> lies between <code>min_number</code> and <code>max_number</code>.</p>
<pre><code>merged <- table2[table1, on = c("type", "class", "max_number >= number", "min_number <= number")]
> merged
id2 type class min_number max_number id1
1: 1998 1 A 1 1 1324
2: 2012 1 A 1 1 1324
3: 2012 1 A 1 1 1324
4: 1998 1 A 98 98 2324
5: 2000 1 A 98 98 2324
6: 2012 1 A 98 98 2324
7: NA 2 B 100 100 29
8: 2000 1 D 100 100 29
9: 2000 1 D 70 70 1010
10: 1998 1 A 70 70 1010
11: 2000 1 A 70 70 1010
12: 2012 1 A 70 70 1010
</code></pre>
<p><strong>Step 2.</strong> Then for each <code>class</code>, I would like to count how many unique <code>id1</code>s there are and how many unique <code>id2</code>s there are. The final desired output is this:</p>
<pre><code>library(dplyr)
count_merged <- merged %>% group_by(class) %>%
summarise(n_id2 = n_distinct(id2[!is.na(id2)]),
n_id1 = n_distinct(id1))
> count_merged
# A tibble: 3 × 3
class n_id2 n_id1
<chr> <int> <int>
1 A 3 3
2 B 0 1
3 D 1 2
</code></pre>
<p>My question: is there a faster way of doing this? If <code>table1</code> and <code>table2</code> have hundreds of thousands of rows, then it is extremely slow to do merge the two tables in <strong>Step 1</strong>. Is there a way to obtain the counts without merging?</p>
|
[
{
"answer_id": 74472042,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 3,
"selected": true,
"text": "style"
},
{
"answer_id": 74472488,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 1,
"selected": false,
"text": "import requests\nfrom bs4 import BeautifulSoup as bs\nimport base64\nfrom tqdm import tqdm ## if using Jupyter, do `from tqdm.notebook import tqdm`\nimport pandas as pd\n\nheaders = {\n 'referer': 'https://www.architectural-review.com/buildings/house',\n 'x-requested-with': 'XMLHttpRequest',\n 'accept-language': 'en-US,en;q=0.9',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\ns = requests.Session()\ns.headers.update(headers)\nbig_list = []\nfor x in tqdm(range(0, 50, 4)):\n url = f'https://www.architectural-review.com/wp-admin/admin-ajax.php?action=lazy-load&offset={x}&term_id=869&block_id=7&class=fourth-post&load_number=4&exclude=MzE4Mzk5LDMxODM2MCwzMTc2MDAsNjUyNjEsNjQzMTMsNjQzMTgsNjQyNzMsNjMyNTcsMzI2NzE2LDMyNjY5OSwzNDY3MSwzMjg3MzgsMTc5ODY1LDE3OTgzNSwxNzk3NjgsMTc5NTk4LDg3NDgyLDY3Mjk2LDY1NjIwLDYzNjQwLDYzMzgyLDYzMzQzLDYzMjk3LDYyOTMxLDYyOTI1LDYyMTA2LDYwOTE4LDU3MjMyLDU3MTE0LDU3MTAzLDU3MDg4LDU3MDgxLDU3MDc1LDU2OTkzLDU2OTc4'\n r = s.get(url)\n soup = bs(base64.b64decode(r.json()['body']), 'html.parser')\n houses = soup.select('div[class=\"lazy-post fourth-post\"]')\n for house in houses:\n title = house.select_one('h2').get_text(strip=True)\n author = house.select_one('span[class=\"tie-author\"]').get_text(strip=True)\n url = house.select_one('h2').parent.get('href')\n big_list.append((title, author, url))\ndf = pd.DataFrame(big_list, columns=['title', 'author', 'url'])\nprint(df)\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3391549/"
] |
74,470,550
|
<p>You init a 2-d matrix like this</p>
<pre><code>board = [[0] * width for _ in range(height)]
</code></pre>
<p>Instead of</p>
<pre><code>board = [[0] * width] * height
</code></pre>
<p>as it creates the list once and every row references the same list.</p>
<p>Is it not the same in the first case, we still use <code>*</code> so each column in each row should reference the same element for a given row. But this is not the case, why?</p>
|
[
{
"answer_id": 74470618,
"author": "Jongwook Choi",
"author_id": 1534182,
"author_profile": "https://Stackoverflow.com/users/1534182",
"pm_score": 0,
"selected": false,
"text": "In [1]: a = object() \n \nIn [1]: [a] * 10 \nOut [1]: \n[<object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>, \n <object at 0x7f57d0670a90>] \n"
},
{
"answer_id": 74470770,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "0"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3646408/"
] |
74,470,626
|
<p>Enter your height in meters: t
Invalid choice. Try again
Enter your height in meters: 1.7
Enter your weight in kg: g
Invalid choice. Try again
Enter your height in meters:</p>
<p>This is my output.
The first time the user inputs an invalid choice the correct display is shown and the user is directed to re-enter their height.
When the weight input is incorrect the code is incorrect and repeats enter your height rather than weight.</p>
<pre><code>def mainMenu():
print("1. Calculate body mass index (BMI).")
print("2. View membership cost.")
print("3. Exit the program.")
while True:
try:
choice = int(input("Enter your choice: "))
if choice == 1:
BMI()
break
elif choice ==2:
Membership()
break
elif choice ==3:
break
else:
print("Incorrect choice. Enter 1-3")
mainMenu
except ValueError:
print("Invalid choice. Enter 1-3")
exit
def BMI():
while True:
try:
h=float(input("Enter your height in meters: "))
w=float(input("Enter your weight in kg: "))
BMI=w/(h*h)
print("BMI Calculated is: ",BMI)
if(BMI<18.5):
print("Underweight")
if(BMI>=18.5 and BMI <25):
print("Normal")
if(BMI>=25 and BMI <30):
print("Overweight")
if(BMI>30):
print("Obese")
else:
print("Incorrect choice.")
mainMenu
except ValueError:
print("Invalid choice. Try again")
exit
mainMenu()
</code></pre>
<p>I am new to coding so would appreciate any help.</p>
|
[
{
"answer_id": 74470901,
"author": "unleashed gamer",
"author_id": 13794470,
"author_profile": "https://Stackoverflow.com/users/13794470",
"pm_score": 1,
"selected": false,
"text": "def BMI():\n\nwhile True:\n\n try:\n\n try:\n\n h=float(input(\"Enter your height in meters: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n try: \n\n\n\n w=float(input(\"Enter your weight in kg: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n BMI=w/(h*h)\n\n print(\"BMI Calculated is: \",BMI)\n\n \n if(BMI<18.5):\n\n print(\"Underweight\")\n\n if(BMI>=18.5 and BMI <25):\n\n print(\"Normal\")\n\n if(BMI>=25 and BMI <30):\n\n print(\"Overweight\")\n\n if(BMI>30):\n\n print(\"Obese\")\n\n else:\n\n print(\"Incorrect choice.\")\n\n mainMenu\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n \n \n"
},
{
"answer_id": 74471131,
"author": "UNK30WN",
"author_id": 18025253,
"author_profile": "https://Stackoverflow.com/users/18025253",
"pm_score": 0,
"selected": false,
"text": "\ndef mainMenu():\n\n while True:\n print(\"1. Calculate body mass index (BMI).\")\n print(\"2. View membership cost.\")\n print(\"3. Exit the program.\")\n try:\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n BMI()\n elif choice ==2:\n # Membership()\n break\n elif choice ==3:\n break\n else:\n print(\"Incorrect choice. Enter 1-3\")\n # here you tried to run the function mainMenu(). Don't do it while loop will take care of it.\n\n except ValueError:\n print(\"Invalid choice. Enter 1-3\")\n\ndef BMI():\n # here i seperate the while loop for every input so it will only repeat the wrong input \n while True:\n try:\n h=float(input(\"Enter your height in meters: \"))\n break\n except:\n print(\"Invalid height. \")\n\n while True:\n try:\n w=float(input(\"Enter your weight in kg: \"))\n break\n except:\n print(\"Invalid Weight.\")\n \n\n BMI=w/(h*h)\n\n\n print(\"\\n\\n\") #this is here just to create some space between result and other program\n \n print(\"BMI Calculated is: \",BMI)\n \n\n # you had used if statements for every one of these so i used elif instead\n # so the program won't have to read all these every time\n # it will be a little bit easier\n if(BMI<18.5):\n print(\"Underweight\")\n elif(BMI>=18.5 and BMI <25):\n print(\"Normal\")\n elif(BMI>=25 and BMI <30):\n print(\"Overweight\")\n elif(BMI>30):\n print(\"Obese\")\n else:\n print(\"incorrect choice\")\n\n # here are these print statements to create some space when the program is run another time\n print(\"\\n\")\n print(\"=========================================\")\n print(\"\\n\")\n\n\n mainMenu()\n\n\nmainMenu()\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19422638/"
] |
74,470,644
|
<p>at the moment our react components look something like this:</p>
<p>Parent.tsx:</p>
<pre><code>const Child1 = () => ...
const Child2 = () => ...
export const Parent = () => ...
</code></pre>
<p>Wrapper.tsx</p>
<pre><code>import { Parent } from 'Parent.tsx'
/// use parent
</code></pre>
<p>This makes it difficult to see what the component is actually about since there are multiple in one file - however we also don't want to unnecessarily expose components that are not needed anywhere else. We would like to move the child components to a subfolder and only expose them to their parent.</p>
<p>So in the end the preferred folder structure would be something like this:</p>
<pre><code>src
├── feature
| ├── components
│ | ├── Child1.tsx
│ | └── Child2.tsx
| └── Parent.tsx
└── screens
└── App.tsx <-- imports Parent.tsx - can't import children
</code></pre>
<p>Is this somehow possible without exposing them to the whole application?
How do you deal with such bigger components in your production applications?</p>
|
[
{
"answer_id": 74470901,
"author": "unleashed gamer",
"author_id": 13794470,
"author_profile": "https://Stackoverflow.com/users/13794470",
"pm_score": 1,
"selected": false,
"text": "def BMI():\n\nwhile True:\n\n try:\n\n try:\n\n h=float(input(\"Enter your height in meters: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n try: \n\n\n\n w=float(input(\"Enter your weight in kg: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n BMI=w/(h*h)\n\n print(\"BMI Calculated is: \",BMI)\n\n \n if(BMI<18.5):\n\n print(\"Underweight\")\n\n if(BMI>=18.5 and BMI <25):\n\n print(\"Normal\")\n\n if(BMI>=25 and BMI <30):\n\n print(\"Overweight\")\n\n if(BMI>30):\n\n print(\"Obese\")\n\n else:\n\n print(\"Incorrect choice.\")\n\n mainMenu\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n \n \n"
},
{
"answer_id": 74471131,
"author": "UNK30WN",
"author_id": 18025253,
"author_profile": "https://Stackoverflow.com/users/18025253",
"pm_score": 0,
"selected": false,
"text": "\ndef mainMenu():\n\n while True:\n print(\"1. Calculate body mass index (BMI).\")\n print(\"2. View membership cost.\")\n print(\"3. Exit the program.\")\n try:\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n BMI()\n elif choice ==2:\n # Membership()\n break\n elif choice ==3:\n break\n else:\n print(\"Incorrect choice. Enter 1-3\")\n # here you tried to run the function mainMenu(). Don't do it while loop will take care of it.\n\n except ValueError:\n print(\"Invalid choice. Enter 1-3\")\n\ndef BMI():\n # here i seperate the while loop for every input so it will only repeat the wrong input \n while True:\n try:\n h=float(input(\"Enter your height in meters: \"))\n break\n except:\n print(\"Invalid height. \")\n\n while True:\n try:\n w=float(input(\"Enter your weight in kg: \"))\n break\n except:\n print(\"Invalid Weight.\")\n \n\n BMI=w/(h*h)\n\n\n print(\"\\n\\n\") #this is here just to create some space between result and other program\n \n print(\"BMI Calculated is: \",BMI)\n \n\n # you had used if statements for every one of these so i used elif instead\n # so the program won't have to read all these every time\n # it will be a little bit easier\n if(BMI<18.5):\n print(\"Underweight\")\n elif(BMI>=18.5 and BMI <25):\n print(\"Normal\")\n elif(BMI>=25 and BMI <30):\n print(\"Overweight\")\n elif(BMI>30):\n print(\"Obese\")\n else:\n print(\"incorrect choice\")\n\n # here are these print statements to create some space when the program is run another time\n print(\"\\n\")\n print(\"=========================================\")\n print(\"\\n\")\n\n\n mainMenu()\n\n\nmainMenu()\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13794223/"
] |
74,470,667
|
<pre><code>String value = "0001111000010000000100000100100110000000000000101010000101000000011000000010011110011001001101100011101011110110000100001101010111010011101010011001011001100001001000010000000010110001001001001011"
BigInteger bi = new BigInteger(value, 2);
// bi : 11794183182202048648710358761397377436458666044077659329099
byte[] bytes = bi.toByteArray();
// bytes : [B@647aa62
</code></pre>
<p>I have Java code like above. Trying to convert this to Swift.</p>
<p>I wonder how to do the above conversion to get the same result in Swift.</p>
<p>I know it's okay to use 'BigInteger' as 'Int' in Swift.</p>
<pre><code>Int(value,radix: 2)!
</code></pre>
<p>I found 'Int(value,radix: 2)!' in Swift. But this didn't work.(I got nil as result.
)</p>
<p>What method should I use to get the same result as above java in Swift? And what additional information do I need to get to do this?</p>
|
[
{
"answer_id": 74470901,
"author": "unleashed gamer",
"author_id": 13794470,
"author_profile": "https://Stackoverflow.com/users/13794470",
"pm_score": 1,
"selected": false,
"text": "def BMI():\n\nwhile True:\n\n try:\n\n try:\n\n h=float(input(\"Enter your height in meters: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n try: \n\n\n\n w=float(input(\"Enter your weight in kg: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n BMI=w/(h*h)\n\n print(\"BMI Calculated is: \",BMI)\n\n \n if(BMI<18.5):\n\n print(\"Underweight\")\n\n if(BMI>=18.5 and BMI <25):\n\n print(\"Normal\")\n\n if(BMI>=25 and BMI <30):\n\n print(\"Overweight\")\n\n if(BMI>30):\n\n print(\"Obese\")\n\n else:\n\n print(\"Incorrect choice.\")\n\n mainMenu\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n \n \n"
},
{
"answer_id": 74471131,
"author": "UNK30WN",
"author_id": 18025253,
"author_profile": "https://Stackoverflow.com/users/18025253",
"pm_score": 0,
"selected": false,
"text": "\ndef mainMenu():\n\n while True:\n print(\"1. Calculate body mass index (BMI).\")\n print(\"2. View membership cost.\")\n print(\"3. Exit the program.\")\n try:\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n BMI()\n elif choice ==2:\n # Membership()\n break\n elif choice ==3:\n break\n else:\n print(\"Incorrect choice. Enter 1-3\")\n # here you tried to run the function mainMenu(). Don't do it while loop will take care of it.\n\n except ValueError:\n print(\"Invalid choice. Enter 1-3\")\n\ndef BMI():\n # here i seperate the while loop for every input so it will only repeat the wrong input \n while True:\n try:\n h=float(input(\"Enter your height in meters: \"))\n break\n except:\n print(\"Invalid height. \")\n\n while True:\n try:\n w=float(input(\"Enter your weight in kg: \"))\n break\n except:\n print(\"Invalid Weight.\")\n \n\n BMI=w/(h*h)\n\n\n print(\"\\n\\n\") #this is here just to create some space between result and other program\n \n print(\"BMI Calculated is: \",BMI)\n \n\n # you had used if statements for every one of these so i used elif instead\n # so the program won't have to read all these every time\n # it will be a little bit easier\n if(BMI<18.5):\n print(\"Underweight\")\n elif(BMI>=18.5 and BMI <25):\n print(\"Normal\")\n elif(BMI>=25 and BMI <30):\n print(\"Overweight\")\n elif(BMI>30):\n print(\"Obese\")\n else:\n print(\"incorrect choice\")\n\n # here are these print statements to create some space when the program is run another time\n print(\"\\n\")\n print(\"=========================================\")\n print(\"\\n\")\n\n\n mainMenu()\n\n\nmainMenu()\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14964159/"
] |
74,470,679
|
<p>I've written a code that lets the user continuously input new members' names for The Beatles, and prints a new list of members' names once the user has done with inputting, but I keep getting repeated names if I enter more than one name.</p>
<p>Could somebody help me out here?</p>
<pre><code># step 1
beatles = ['John Lennon', 'Paul McCartney', 'George Harrison']
new_list=[]
new_member = ''
while True:
new_member = input ('Please enter new memebers to the group, enter NA to exit entering: ')
if new_member == 'NA':
break
else:
new_list.append (new_member)
for i in new_list:
beatles.append(i)
print("Step 3:", beatles)
</code></pre>
|
[
{
"answer_id": 74470901,
"author": "unleashed gamer",
"author_id": 13794470,
"author_profile": "https://Stackoverflow.com/users/13794470",
"pm_score": 1,
"selected": false,
"text": "def BMI():\n\nwhile True:\n\n try:\n\n try:\n\n h=float(input(\"Enter your height in meters: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n try: \n\n\n\n w=float(input(\"Enter your weight in kg: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n BMI=w/(h*h)\n\n print(\"BMI Calculated is: \",BMI)\n\n \n if(BMI<18.5):\n\n print(\"Underweight\")\n\n if(BMI>=18.5 and BMI <25):\n\n print(\"Normal\")\n\n if(BMI>=25 and BMI <30):\n\n print(\"Overweight\")\n\n if(BMI>30):\n\n print(\"Obese\")\n\n else:\n\n print(\"Incorrect choice.\")\n\n mainMenu\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n \n \n"
},
{
"answer_id": 74471131,
"author": "UNK30WN",
"author_id": 18025253,
"author_profile": "https://Stackoverflow.com/users/18025253",
"pm_score": 0,
"selected": false,
"text": "\ndef mainMenu():\n\n while True:\n print(\"1. Calculate body mass index (BMI).\")\n print(\"2. View membership cost.\")\n print(\"3. Exit the program.\")\n try:\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n BMI()\n elif choice ==2:\n # Membership()\n break\n elif choice ==3:\n break\n else:\n print(\"Incorrect choice. Enter 1-3\")\n # here you tried to run the function mainMenu(). Don't do it while loop will take care of it.\n\n except ValueError:\n print(\"Invalid choice. Enter 1-3\")\n\ndef BMI():\n # here i seperate the while loop for every input so it will only repeat the wrong input \n while True:\n try:\n h=float(input(\"Enter your height in meters: \"))\n break\n except:\n print(\"Invalid height. \")\n\n while True:\n try:\n w=float(input(\"Enter your weight in kg: \"))\n break\n except:\n print(\"Invalid Weight.\")\n \n\n BMI=w/(h*h)\n\n\n print(\"\\n\\n\") #this is here just to create some space between result and other program\n \n print(\"BMI Calculated is: \",BMI)\n \n\n # you had used if statements for every one of these so i used elif instead\n # so the program won't have to read all these every time\n # it will be a little bit easier\n if(BMI<18.5):\n print(\"Underweight\")\n elif(BMI>=18.5 and BMI <25):\n print(\"Normal\")\n elif(BMI>=25 and BMI <30):\n print(\"Overweight\")\n elif(BMI>30):\n print(\"Obese\")\n else:\n print(\"incorrect choice\")\n\n # here are these print statements to create some space when the program is run another time\n print(\"\\n\")\n print(\"=========================================\")\n print(\"\\n\")\n\n\n mainMenu()\n\n\nmainMenu()\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20475880/"
] |
74,470,685
|
<p>I am stuck with this problem of giving padding to all sides to a <strong>value</strong> inside NumericUpDown control in Winforms.</p>
<p>Apparently no one has asked this before.</p>
<p>Actual how control is looking: (<a href="https://i.stack.imgur.com/KIweV.png" rel="nofollow noreferrer">https://i.stack.imgur.com/KIweV.png</a>)
Expected how I want control to look: <a href="https://i.stack.imgur.com/K6SZL.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Ignore other differences in both the attached images. Just need to pad the value from top, bottom and left; as part of this question.</p>
<p>So far, I have only figured out that there is a TextAlign property which can align either Left or Right or Center, but that doesn't help in giving padding to top and bottom edges of the control.</p>
<p>Below code is not solving my problem
this.numericUpDown1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;</p>
|
[
{
"answer_id": 74470901,
"author": "unleashed gamer",
"author_id": 13794470,
"author_profile": "https://Stackoverflow.com/users/13794470",
"pm_score": 1,
"selected": false,
"text": "def BMI():\n\nwhile True:\n\n try:\n\n try:\n\n h=float(input(\"Enter your height in meters: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n try: \n\n\n\n w=float(input(\"Enter your weight in kg: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n BMI=w/(h*h)\n\n print(\"BMI Calculated is: \",BMI)\n\n \n if(BMI<18.5):\n\n print(\"Underweight\")\n\n if(BMI>=18.5 and BMI <25):\n\n print(\"Normal\")\n\n if(BMI>=25 and BMI <30):\n\n print(\"Overweight\")\n\n if(BMI>30):\n\n print(\"Obese\")\n\n else:\n\n print(\"Incorrect choice.\")\n\n mainMenu\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n \n \n \n"
},
{
"answer_id": 74471131,
"author": "UNK30WN",
"author_id": 18025253,
"author_profile": "https://Stackoverflow.com/users/18025253",
"pm_score": 0,
"selected": false,
"text": "\ndef mainMenu():\n\n while True:\n print(\"1. Calculate body mass index (BMI).\")\n print(\"2. View membership cost.\")\n print(\"3. Exit the program.\")\n try:\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n BMI()\n elif choice ==2:\n # Membership()\n break\n elif choice ==3:\n break\n else:\n print(\"Incorrect choice. Enter 1-3\")\n # here you tried to run the function mainMenu(). Don't do it while loop will take care of it.\n\n except ValueError:\n print(\"Invalid choice. Enter 1-3\")\n\ndef BMI():\n # here i seperate the while loop for every input so it will only repeat the wrong input \n while True:\n try:\n h=float(input(\"Enter your height in meters: \"))\n break\n except:\n print(\"Invalid height. \")\n\n while True:\n try:\n w=float(input(\"Enter your weight in kg: \"))\n break\n except:\n print(\"Invalid Weight.\")\n \n\n BMI=w/(h*h)\n\n\n print(\"\\n\\n\") #this is here just to create some space between result and other program\n \n print(\"BMI Calculated is: \",BMI)\n \n\n # you had used if statements for every one of these so i used elif instead\n # so the program won't have to read all these every time\n # it will be a little bit easier\n if(BMI<18.5):\n print(\"Underweight\")\n elif(BMI>=18.5 and BMI <25):\n print(\"Normal\")\n elif(BMI>=25 and BMI <30):\n print(\"Overweight\")\n elif(BMI>30):\n print(\"Obese\")\n else:\n print(\"incorrect choice\")\n\n # here are these print statements to create some space when the program is run another time\n print(\"\\n\")\n print(\"=========================================\")\n print(\"\\n\")\n\n\n mainMenu()\n\n\nmainMenu()\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14623711/"
] |
74,470,708
|
<p>This suddenly happened after I created a new file while working on a project. Almost all characters are simply white text (except for brackets, because I have <em>bracket pair colorization</em> enabled)</p>
<p><a href="https://i.stack.imgur.com/9A2HY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9A2HY.png" alt="First image showing how JavaScript and TypeScript syntax highlighting is not working" /></a></p>
<p><a href="https://i.stack.imgur.com/gzX6N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gzX6N.png" alt="second image showing how JavaScript and TypeScript syntax highlighting is not working" /></a></p>
<p><a href="https://i.stack.imgur.com/iLI6v.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iLI6v.png" alt="third image showing how JavaScript and TypeScript syntax highlighting is not working" /></a></p>
<p>I already tried resetting my configurations, checked my configurations (both globally and in my workspace), and tried <a href="https://marketplace.visualstudio.com/items?itemName=evgeniypeshkov.syntax-highlighter" rel="noreferrer">this extension</a> that offers an alternative syntax highlighting (which worked, but I would prefer using the Visual Studio Code one).</p>
|
[
{
"answer_id": 74480373,
"author": "Vitalii",
"author_id": 13111228,
"author_profile": "https://Stackoverflow.com/users/13111228",
"pm_score": -1,
"selected": false,
"text": "JavaScript"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14649369/"
] |
74,470,781
|
<p>table 1: decks</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>deckid</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1662490522316</td>
<td>test1</td>
</tr>
<tr>
<td>1662975567468</td>
<td>test3</td>
</tr>
<tr>
<td>1663153348829</td>
<td>test4/@/4</td>
</tr>
<tr>
<td>1664289454461</td>
<td>Science Class EBP Physics 9th</td>
</tr>
<tr>
<td>1665037005819</td>
<td>d/@/dog</td>
</tr>
</tbody>
</table>
</div>
<p>table 2: cards</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>cardid</th>
<th>noteid</th>
<th>deckid</th>
</tr>
</thead>
<tbody>
<tr>
<td>1635883239955</td>
<td>1635883239955</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883239956</td>
<td>1635883239955</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883343194</td>
<td>1635883343194</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883343195</td>
<td>1635883343194</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883382043</td>
<td>1635883382043</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883382044</td>
<td>1635883382043</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883439273</td>
<td>1635883439273</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883439274</td>
<td>1635883439273</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883509673</td>
<td>1635883509673</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1635883509674</td>
<td>1635883509673</td>
<td>1664289454461</td>
</tr>
<tr>
<td>1662490587893</td>
<td>1662490587892</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1662491389237</td>
<td>1662491389237</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1662491433306</td>
<td>1662491433306</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1662886491604</td>
<td>1662886491600</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1662886955205</td>
<td>1662886955203</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1662965836930</td>
<td>1662965836929</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1663129181833</td>
<td>1663129181832</td>
<td>1662975567468</td>
</tr>
<tr>
<td>1663675409308</td>
<td>1663675409308</td>
<td>1663153348829</td>
</tr>
<tr>
<td>1663675409309</td>
<td>1663675409308</td>
<td>1663153348829</td>
</tr>
<tr>
<td>1663728830758</td>
<td>1663728830757</td>
<td>1662975567468</td>
</tr>
<tr>
<td>1664353381308</td>
<td>1664353381307</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1664358364077</td>
<td>1664358364074</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1664358364078</td>
<td>1664358364075</td>
<td>1662490522316</td>
</tr>
<tr>
<td>1665037065057</td>
<td>1665037065047</td>
<td>1665037005819</td>
</tr>
</tbody>
</table>
</div>
<p>i want a query to return deckid, name and count of cards. for each decks
each deck will have n number of cards which is shown in table 2: cards</p>
<p>I
did that with two queries
1)</p>
<pre><code>SELECT decks.deckid, decks.name FROM decks
</code></pre>
<p>which returns</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>deckid</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1662490522316</td>
<td>test1</td>
</tr>
<tr>
<td>1662975567468</td>
<td>test3</td>
</tr>
<tr>
<td>1663153348829</td>
<td>test4/@/4</td>
</tr>
<tr>
<td>1664289454461</td>
<td>Science Class EBP Physics 9th</td>
</tr>
<tr>
<td>1665037005819</td>
<td>d/@/dog</td>
</tr>
</tbody>
</table>
</div>
<p>2)</p>
<pre><code>SELECT cards.deckid, count(cards.deckid)
FROM cards
GROUP BY cards.deckid
</code></pre>
<p>which returns number(or)count of cards in one deck id</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>deckid</th>
<th>count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1662490522316</td>
<td>9</td>
</tr>
<tr>
<td>1662975567468</td>
<td>2</td>
</tr>
<tr>
<td>1663153348829</td>
<td>2</td>
</tr>
<tr>
<td>1664289454461</td>
<td>10</td>
</tr>
<tr>
<td>1665037005819</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>i am expecting a query which returns this two result in to one like.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>deckid</th>
<th>name</th>
<th>count(crad.cardid)</th>
</tr>
</thead>
<tbody>
<tr>
<td>1662490522316</td>
<td>test1</td>
<td>9</td>
</tr>
<tr>
<td>1662975567468</td>
<td>test3</td>
<td>2</td>
</tr>
<tr>
<td>1663153348829</td>
<td>test4/@/4</td>
<td>2</td>
</tr>
<tr>
<td>1664289454461</td>
<td>Science Class EBP Physics 9th</td>
<td>10</td>
</tr>
<tr>
<td>1665037005819</td>
<td>d/@/dog</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74480373,
"author": "Vitalii",
"author_id": 13111228,
"author_profile": "https://Stackoverflow.com/users/13111228",
"pm_score": -1,
"selected": false,
"text": "JavaScript"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17183867/"
] |
74,470,792
|
<p>Is there a better way to write this constructor which has multiple <code>if</code> statements and multiple arguments? I'm a noob to programming so any leads would be helpful.</p>
<pre class="lang-java prettyprint-override"><code>public Latency(final double full, final double cpuOne, final double cpuTwo, final double cpuThree, final double cpuFour) {
if (full > 10.0 || (full <= 0.0)) {
throw new IllegalArgumentException("Must check the values");
}
this.full = full;
if (cpuOne == 0 && cpuTwo == 0 && cpuThree == 0 && cpuFour == 0) {
throw new IllegalArgumentException("not all can be zero");
} else {
if (cpuOne == 0.5) {
this.cpuOne = full;
} else {
this.cpuOne = cpuOne;
}
if (cpuTwo == 0.5) {
this.cpuTwo = full;
} else {
this.cpuTwo = cpuTwo;
}
if (cpuThree == 0.5) {
this.cpuThree = full;
} else {
this.cpuThree = cpuThree;
}
if (cpuFour == 0.5) {
this.cpuFour = full;
} else {
this.cpuFour = cpuFour;
}
}
}
</code></pre>
<p>I think this code doesn't need much of context as it is pretty straight forward.</p>
<p>I found out that we can't use <code>switch</code> statements for type <code>double</code>. How to optimize this?</p>
|
[
{
"answer_id": 74471012,
"author": "Abra",
"author_id": 2164365,
"author_profile": "https://Stackoverflow.com/users/2164365",
"pm_score": 2,
"selected": false,
"text": "if"
},
{
"answer_id": 74471044,
"author": "Dawood ibn Kareem",
"author_id": 1081110,
"author_profile": "https://Stackoverflow.com/users/1081110",
"pm_score": 2,
"selected": false,
"text": "else"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400359/"
] |
74,470,800
|
<p>I have a table, I want to pivot the table, my desired output is @tab2.</p>
<p>My table is as follows:</p>
<pre><code>declare @tab1 table(name varchar(50),mobile varchar(10),address varchar(100))
insert into @tab1 values('Test','2612354598','CG-10')
select * from @tab1
</code></pre>
<p>My desired output is:</p>
<pre><code>declare @tab2 table(colname varchar(50),value varchar(100))
insert into @tab2 values('name','Test'),('mobile','2612354598'),('address','CG-10')
select * from @tab2
</code></pre>
<p>Please help</p>
|
[
{
"answer_id": 74471045,
"author": "RF1991",
"author_id": 14799981,
"author_profile": "https://Stackoverflow.com/users/14799981",
"pm_score": 2,
"selected": false,
"text": "Unpivot"
},
{
"answer_id": 74471103,
"author": "Charles",
"author_id": 20525287,
"author_profile": "https://Stackoverflow.com/users/20525287",
"pm_score": 2,
"selected": true,
"text": "SELECT colname, valueid\n FROM \n(SELECT CAST(name as varchar(100)) name, CAST(mobile as varchar(100)) \n mobile, address FROM @tab1) p \nUNPIVOT \n (valueid FOR colname IN \n (name,mobile, address) \n )AS unpvt;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7769070/"
] |
74,470,808
|
<p>Recently, my text color has been of for js,jsx,ts,tsx files in VS Code.</p>
<p>I don't really know what happened but it's not working all of a sudden.</p>
<p><a href="https://i.stack.imgur.com/PA3pA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PA3pA.png" alt="enter image description here" /></a></p>
<p>As you see, the file is detected to be a typescript react file, but I do not have any text coloring.</p>
|
[
{
"answer_id": 74471045,
"author": "RF1991",
"author_id": 14799981,
"author_profile": "https://Stackoverflow.com/users/14799981",
"pm_score": 2,
"selected": false,
"text": "Unpivot"
},
{
"answer_id": 74471103,
"author": "Charles",
"author_id": 20525287,
"author_profile": "https://Stackoverflow.com/users/20525287",
"pm_score": 2,
"selected": true,
"text": "SELECT colname, valueid\n FROM \n(SELECT CAST(name as varchar(100)) name, CAST(mobile as varchar(100)) \n mobile, address FROM @tab1) p \nUNPIVOT \n (valueid FOR colname IN \n (name,mobile, address) \n )AS unpvt;\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15377591/"
] |
74,470,819
|
<p>I am trying to split a string of numbers separated by commas into a list but it it giving me this error:</p>
<p>TypeError: 'str' object cannot be interpreted as an integer</p>
<p>This is what I've tried:</p>
<pre><code>numbers = "1, 2, 3, 4, 5, 500, 600, 800"
numbers_list = numbers.split(",", " ")
print(numbers_list)
</code></pre>
|
[
{
"answer_id": 74470893,
"author": "creatorpravin",
"author_id": 17981270,
"author_profile": "https://Stackoverflow.com/users/17981270",
"pm_score": -1,
"selected": false,
"text": "import re\n \nnumbers = \"1, 2, 3, 4, 5, 500, 600, 800\"\n \nval = re.sub(r'[^\\w]', ' ', numbers)\nli = val.split(\" \") \nli2 = [] \nfor i in li:\n if i == \"\":\n pass\n else:\n li2.append(i)\n \nprint(li2)\n"
},
{
"answer_id": 74470930,
"author": "PoultryPants",
"author_id": 16660743,
"author_profile": "https://Stackoverflow.com/users/16660743",
"pm_score": 1,
"selected": false,
"text": ".split"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19698970/"
] |
74,470,821
|
<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>function findUpper(text) {
let arr = [];
if (text.length === 0) {
return arr;
}
if (text.charAt(0) === text[0].toUpperCase()) {
arr.push(text[0]);
}
arr = arr.concat(findUpper(text.slice(1)));
console.log(arr);
return arr;
}
findUpper("i am a Web developer Student");</code></pre>
</div>
</div>
</p>
<p>The desired output is "W", since it is the first upper case letter, But I cannot figure out how to print out that result.</p>
|
[
{
"answer_id": 74470893,
"author": "creatorpravin",
"author_id": 17981270,
"author_profile": "https://Stackoverflow.com/users/17981270",
"pm_score": -1,
"selected": false,
"text": "import re\n \nnumbers = \"1, 2, 3, 4, 5, 500, 600, 800\"\n \nval = re.sub(r'[^\\w]', ' ', numbers)\nli = val.split(\" \") \nli2 = [] \nfor i in li:\n if i == \"\":\n pass\n else:\n li2.append(i)\n \nprint(li2)\n"
},
{
"answer_id": 74470930,
"author": "PoultryPants",
"author_id": 16660743,
"author_profile": "https://Stackoverflow.com/users/16660743",
"pm_score": 1,
"selected": false,
"text": ".split"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526861/"
] |
74,470,878
|
<p>So I have this list:</p>
<pre><code>[['chocolate', '10225.25', '9025.0', '9505.0', '8750.0'], ['cookie dough', '7901.25', '4267.0', '7056.5', '3550.25'], ['rocky road', '6700.1', '5012.45', '6011.0', '5225.15'], ['strawberry', '9285.15', '8276.1', '8705.0', '7655.1'], ['vanilla', '8580.0', '7201.25', '8900.0', '3500.25']]
</code></pre>
<p>is there a way I can turn each list inside the list into a dictionary where it would look like this:</p>
<pre><code>{'chocolate' : ['10225.25', '9025.0', '9505.0', '8750.0'], 'cookie dough' : ['7901.25', '4267.0', '7056.5', '3550.25'], 'rocky road' : ['6700.1', '5012.45', '6011.0', '5225.15']} ...
</code></pre>
<p>you get the idea</p>
<p>I have tried lots of things but I can't seem to find the solution to my problem.</p>
<p>anything would be helpful :)
thx</p>
|
[
{
"answer_id": 74470987,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 1,
"selected": false,
"text": "l=[['chocolate', '10225.25', '9025.0', '9505.0', '8750.0'], ['cookie dough', '7901.25', '4267.0', '7056.5', '3550.25'], ['rocky road', '6700.1', '5012.45', '6011.0', '5225.15'], ['strawberry', '9285.15', '8276.1', '8705.0', '7655.1'], ['vanilla', '8580.0', '7201.25', '8900.0', '3500.25']]\n"
},
{
"answer_id": 74577013,
"author": "Jean Albino",
"author_id": 20601581,
"author_profile": "https://Stackoverflow.com/users/20601581",
"pm_score": 0,
"selected": false,
"text": " new_dict = {}\n for item in lst:\n new_dict[item[0]] = item[1:]\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20263526/"
] |
74,470,890
|
<p>i have two date :
$from = 2022-11-01
$to = 2022-11-05</p>
<p>now , i wanna create a array like this :
$date = ['2022-11-01','2022-11-02','2022-11-03','2022-11-04','2022-11-05']</p>
<p>and now check '2022-11-03' is exist in $date array or not.</p>
<p>alrady use :
<code>$date = Carbon\CarbonPeriod::create($from, $to);</code></p>
<pre><code>if(in_array('2022-11-03', $date)){
echo "Got it";
}
</code></pre>
<p><strong>#But Still not Work</strong></p>
|
[
{
"answer_id": 74471034,
"author": "Ross_102",
"author_id": 3657308,
"author_profile": "https://Stackoverflow.com/users/3657308",
"pm_score": 4,
"selected": true,
"text": "$from = '2022-11-01';\n$to = '2022-11-05';\n$date = Carbon\\CarbonPeriod::create($from, $to);\nif ($date->contains('2022-11-03')) {\n echo 'Got it';\n}\n"
},
{
"answer_id": 74471036,
"author": "Sachin Bahukhandi",
"author_id": 5192105,
"author_profile": "https://Stackoverflow.com/users/5192105",
"pm_score": 0,
"selected": false,
"text": "parse"
},
{
"answer_id": 74472233,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 2,
"selected": false,
"text": "$from = \"2022-11-01\";\n$to = \"2022-11-05\";\n$check = \"2022-11-03\";\nif(Carbon::parse($check)->between($from,$to)){\n echo $check.' is between '.$from.' and '.$to;\n} else {\n echo $check.' is not between '.$from.' and '.$to;\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11970472/"
] |
74,470,907
|
<p>I'm trying to check if a certain word is mentioned in a file, then the words under it become a part of a set, which then this set would be put in a tuple.
For instance, the file would say:</p>
<pre><code>COUNTRIES
America
Canada
Russia
Poland
PEOPLE
George
John
James
Kenny
</code></pre>
<p>Which would then become a list like this:</p>
<pre><code>[{'America', 'Canada', 'Russia', 'Poland'}, {'George', 'John', 'James', 'Kenny'}]
</code></pre>
<p>I started off by doing this to check if I can start going through each individual string:</p>
<pre><code>input = open('countries.txt', 'r')
l = input.readline()
while l.startswith('COUNTRIES'):
j = input.readline
if j == 'PEOPLE'
break`
</code></pre>
<p>This code runs forever and it does not stop. I figured if that I could figure out why it does not stop when it reaches the word people then I could possibly separate the strings under <code>PEOPLE</code> and <code>COUNTRIES</code> into separate sets.</p>
|
[
{
"answer_id": 74471034,
"author": "Ross_102",
"author_id": 3657308,
"author_profile": "https://Stackoverflow.com/users/3657308",
"pm_score": 4,
"selected": true,
"text": "$from = '2022-11-01';\n$to = '2022-11-05';\n$date = Carbon\\CarbonPeriod::create($from, $to);\nif ($date->contains('2022-11-03')) {\n echo 'Got it';\n}\n"
},
{
"answer_id": 74471036,
"author": "Sachin Bahukhandi",
"author_id": 5192105,
"author_profile": "https://Stackoverflow.com/users/5192105",
"pm_score": 0,
"selected": false,
"text": "parse"
},
{
"answer_id": 74472233,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 2,
"selected": false,
"text": "$from = \"2022-11-01\";\n$to = \"2022-11-05\";\n$check = \"2022-11-03\";\nif(Carbon::parse($check)->between($from,$to)){\n echo $check.' is between '.$from.' and '.$to;\n} else {\n echo $check.' is not between '.$from.' and '.$to;\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526562/"
] |
74,470,928
|
<pre><code>
</code></pre>
<p>private async Task DoDownloadFile(ChatMessageListRefDataModel chatMessage)
{</p>
<pre><code> var status = await Permissions.RequestAsync<Permissions.StorageWrite>();
if(status == PermissionStatus.Granted)
{
await HttpRequestHelper.DownloadFile(chatMessage.FileUrl, chatMessage.FileName);
}
}
</code></pre>
<pre><code>
</code></pre>
<pre><code>
</code></pre>
<p>public static async Task DownloadFile(string url, string fileName) {</p>
<pre><code> var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), fileName);
using (var downloadStream = await client.GetStreamAsync(url))
{
using (var memoryStream = new MemoryStream())
{
await downloadStream.CopyToAsync(memoryStream);
using(FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
byte[] bytes = new byte[memoryStream.Length];
memoryStream.Read(bytes, 0, (int)memoryStream.Length);
file.Write(bytes, 0, bytes.Length);
memoryStream.Close();
}
}
}
</code></pre>
<pre><code>
</code></pre>
<p>The code produces no error it is just the file was not found on the phone's directory. What could have gone wrong. Thanks.</p>
|
[
{
"answer_id": 74472759,
"author": "Liyun Zhang - MSFT",
"author_id": 17455524,
"author_profile": "https://Stackoverflow.com/users/17455524",
"pm_score": 1,
"selected": false,
"text": "Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), fileName);"
},
{
"answer_id": 74485591,
"author": "Ken",
"author_id": 8951304,
"author_profile": "https://Stackoverflow.com/users/8951304",
"pm_score": 0,
"selected": false,
"text": "Launcher.OpenAsync(fileUrl)"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8951304/"
] |
74,470,932
|
<p>I am currently working on a project and need validation for validating dummy emails like
mailinator or yopmail.
These emails should not go through but I can't get any regex for this particular issue.</p>
<p>I have tried different regex but none them worked.</p>
|
[
{
"answer_id": 74470992,
"author": "MrShakila",
"author_id": 19292778,
"author_profile": "https://Stackoverflow.com/users/19292778",
"pm_score": 0,
"selected": false,
"text": "void main() {\n\n var email = \"fredrik@gmail.com\";\n\n assert(EmailValidator.validate(email));\n}\n"
},
{
"answer_id": 74471090,
"author": "Gursewak Singh",
"author_id": 11818376,
"author_profile": "https://Stackoverflow.com/users/11818376",
"pm_score": 2,
"selected": false,
"text": "final disposableEmail = [\n \"xxyxi.com\",\n \"musiccode.me\",\n]\n\nfinal splitList = _emailController.text.split(\"@\");\nif (disposableEmail.contains(splitList[1].trim())) {\n print('Registration with temporary-email-address not allowed');\n return;\n}\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74470932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19245224/"
] |
74,471,008
|
<p>So basically, I'm writing out statistics.</p>
<pre><code>date,students
2022-11-16,22
2022-11-17,29
</code></pre>
<p>I want to read this csv back in and pull the col2 value from "yesterdays" row and compare it to the col2 value from "todays" row and look for a threshold difference. Something like a 5% variance. The last part is straightforward but I'm having a heck of a time with pulling the right rows and re-capturing the 'student' count for comparison.</p>
<p>I can do the hunt operation good enough with Pandas but I lose the second column in the match and its just not clicking for me.</p>
<pre><code>import pandas as pd
from datetime import date
from datetime import timedelta
today = date.today()
yesterday = date.today() - timedelta(1)
print("today is ", today, " and yesterday was ", yesterday)
df = pd.read_csv('test.csv')
col1 = df.timestamp
col2 = df.hostcount
for row in col1:
if row == str(yesterday):
print(row)
</code></pre>
<p>Any ideas are greatly appreciated! I'm sure this is something goofy that I'm overlooking at 1am.</p>
|
[
{
"answer_id": 74471334,
"author": "Chana Drori",
"author_id": 10787867,
"author_profile": "https://Stackoverflow.com/users/10787867",
"pm_score": 0,
"selected": false,
"text": "\n today = str(date.today())\n yesterday = str(date.today() - timedelta(1))\n \n print(\"today is \", today, \" and yesterday was \", yesterday)\n \n df = pd.read_csv('test.csv')\n \n today_value = df.loc[df['date'] == today, 'students'].values[0]\n\n"
},
{
"answer_id": 74471706,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 2,
"selected": true,
"text": "from datetime import datetime, timedelta\n\nnow = datetime.now()\ntoday, *_ = str(now).split()\nyesterday, *_ = str(now - timedelta(days=1)).split()\n\ntv = None\nyv = None\n\nwith open('test.csv') as data:\n for line in data.readlines()[1:]:\n d, s = line.split(',')\n if d == today:\n tv = float(s)\n elif d == yesterday:\n yv = float(s)\n if tv and yv:\n variance = (tv-yv)/yv*100\n print(f'Variance={variance:.2f}%')\n break\n"
}
] |
2022/11/17
|
[
"https://Stackoverflow.com/questions/74471008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11891979/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.