QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
74,888,374
10,681,828
How to synchronize access inside async for?
<p>I found this library for asynchronously consuming kafka messages: <a href="https://github.com/aio-libs/aiokafka" rel="nofollow noreferrer">https://github.com/aio-libs/aiokafka</a></p> <p>It gives this code example:</p> <pre><code>from aiokafka import AIOKafkaConsumer import asyncio async def consume(): consumer...
<python><async-await><python-asyncio>
2022-12-22 12:13:36
1
2,272
Pavel Orekhov
74,888,295
694,360
Detect almost grayscale image with Python
<p>Inspired by this <a href="https://stackoverflow.com/q/23660929/694360">question</a> and this <a href="https://stackoverflow.com/a/74834150/694360">answer</a> (which isn't very solid) I realized that I often find myself converting to grayscale a color image that is <em>almost</em> grayscale (usually a color scan from...
<python><colors><python-imaging-library><grayscale>
2022-12-22 12:07:02
2
5,750
mmj
74,888,098
13,158,157
pandas: expand and replace rows with rows from another data frames
<p>I have two data frames with many different column names but a few common ones. One frame has rows that have to be &quot;expanded&quot; with rows from the other data frame:</p> <p>Example:</p> <pre><code>df = pd.DataFrame({'option':['A', 'A', 'B', 'B', 'fill_A', 'fill_B', ], 'items':['11111', '22222', '33333', '11111...
<python><pandas><dataframe>
2022-12-22 11:49:04
1
525
euh
74,887,925
7,826,511
How to allow CORS from Axios get request in Django backend?
<p>I've been looking for a solution to this problem but nothing seems to work. I've arrived at the <a href="https://github.com/adamchainz/django-cors-headers" rel="nofollow noreferrer">django-cors-headers</a> package but can't get it to work.</p> <p>I'm sending an <code>axios</code> request form my <code>vue</code> fro...
<python><django><rest><axios><cors>
2022-12-22 11:32:27
1
6,153
Artur MΓΌller Romanov
74,887,884
19,155,645
pandas: .isna() shows that whole column is NaNs, but it is strings
<p>I have a pandas dataframe with a column that is populated by &quot;yes&quot; or &quot;no&quot; strings. When I do <code>.value_counts()</code> to this column, i receive the correct distribution. <br> But, when I run <code>.isna()</code> it shows that the whole column is NaNs.</p> <p>I suspect later it creates proble...
<python><pandas>
2022-12-22 11:28:33
1
512
ArieAI
74,887,868
12,474,157
Python transform synchronous request into asynchronous to download image (httpio)
<p>I'm using synchronous responses to get image data from a url into bytes format. But I would like to make it an asynchronous process. My approach is changing python requests for httpio. to achieve it.</p> <p>My original code, which is working throws the following result</p> <p><a href="https://i.sstatic.net/0JMJH.png...
<python><asynchronous><async-await><python-asyncio>
2022-12-22 11:27:12
0
1,720
The Dan
74,887,645
350,403
Retrieving object metadata while traversing S3 using Minio client's list_objects method
<p>I am using the <a href="https://min.io/docs/minio/linux/developers/python/API.html#list_objects" rel="nofollow noreferrer"><code>list_objects</code></a> method of the python minio client and trying to retrieve the metadata for each object while traversing folders in S3. I attempted to do this by setting the <code>in...
<python><client><metadata><traversal><minio>
2022-12-22 11:09:20
2
1,327
evermean
74,887,383
12,559,770
Order lists according to another list in python
<p>I have multiple lists such as :</p> <pre><code>List1=['Canis_lupus','Cattus_catus','Mus_musculus','Rattus_rattus','Bombyx'] List2=['Homo_sapiens','Homo_erectus','Pan_troglodys'] List3=['Cattus_cattus','Bombyx','Homo_erectus','Mus_musculus'] </code></pre> <p>And a predefined ordered list with all the element that cou...
<python><python-3.x>
2022-12-22 10:45:22
3
3,442
chippycentra
74,887,245
11,023,647
How to alter foreignkey with Alembic
<p>I handle my PostgreSQL migrations with <code>Alembic</code>. This is how I create a table <code>items</code>:</p> <pre><code>from alembic import op import sqlalchemy as sa def upgrade(): items_table = op.create_table( &quot;items&quot;, sa.Column(&quot;id&quot;, UUID(as_uuid=True), primary_key=T...
<python><postgresql><sqlalchemy><alembic>
2022-12-22 10:34:59
1
379
lr_optim
74,887,205
8,076,879
Paramiko equivalent of OpenSSH ssh -J switch
<p>I am trying to translate this <code>ssh</code> this command to Python using the <code>paramiko</code> library.</p> <pre class="lang-bash prettyprint-override"><code>sshpass -p SomePassword ssh -J specificSshHost admin@11.0.0.0 \ -oHostKeyAlgorithms=+ssh-rsa \ -oKexAlgorithms=+diffie-hellman-group1-sha1 \ ...
<python><ssh><paramiko>
2022-12-22 10:31:15
1
2,438
DaveR
74,887,176
5,368,122
Calculating difference of two columns with lag and storing result in other
<p>I have <strong>base dataframe</strong> that looks like this:</p> <pre><code>mname p_code p_name fcval shotdate actual_1 actual_2 actual_3 0 101_1210 BankABC 5590890 2015-02-05 10 20 30 ...
<python><pandas>
2022-12-22 10:28:48
2
844
Obiii
74,886,735
9,363,181
Python unittest case expected not matching with the actual
<p>I am trying to mock the <code>secrets manager client</code>. Earlier the variables weren't in the class so I was able to mock the client directly using a patch like below:</p> <pre><code>@patch('my_repo.rc.client') </code></pre> <p>and now since I am using an instance method, I need to mock the instance method.</p> ...
<python><python-3.x><unit-testing><python-unittest><python-unittest.mock>
2022-12-22 09:49:31
2
645
RushHour
74,886,418
3,415,597
Cannot install and import tensorflow_federated in colab
<p>I want to try a simple federated learning example in python. For it, I need to import tensorflow_federated package.</p> <pre class="lang-py prettyprint-override"><code>import tensorflow_federated as tff </code></pre> <p>Here is the stack trace</p> <pre class="lang-py prettyprint-override"><code>TypeError ...
<python><tensorflow-federated><federated-learning>
2022-12-22 09:18:37
0
465
HoOman
74,886,375
4,377,521
Best way to suppress mypy's "has no attribute" for global variable that is initialized later
<p>I have read other questions on this topic - and all of them are about another level (classes, methods or function). I'm trying to find a way to suppress &quot;has not attribute&quot; message from mypy for a <strong>module level</strong> name.</p> <p>Code looks like this</p> <pre><code>service: Service | None = None ...
<python><mypy><linter>
2022-12-22 09:14:46
1
2,938
sashaaero
74,886,225
4,879,688
How can I get `stdout` back in a running cell of a reloaded Jupyter notebook?
<p>I run a Jupyter notebook. One cell contains a control loop of a CPU/memory intensive FEniCS computations. The loop uses <code>print(i)</code> as a progress indicator (where <code>i</code> is the iteration count). As <a href="https://stackoverflow.com/questions/74864501/how-can-i-get-pid-of-a-running-jupyter-noteb...
<python><python-3.x><jupyter-notebook><stdout><python-3.7>
2022-12-22 09:00:52
0
2,742
abukaj
74,886,170
11,883,900
use different array lists as a dropdown list on streamlit app
<p>I am developing a streamlit dashboard and I have different array lists that look like this</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import streamlit as st svm_pred = np.array([1.50, 2.51, 3.34, 4.123, 5.22]) linear_pred = np.array([0.31, 2.11, 0.33, 4.0, 5]) bayesian_pred = np.array([...
<python><arrays><numpy><streamlit>
2022-12-22 08:55:35
1
1,098
LivingstoneM
74,886,169
6,459,056
pytest no module named common
<p>I'm trying to get started with python and pytest, I have the following project structure :</p> <pre><code>. β”œβ”€β”€ my_module β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ common β”‚ β”‚ β”œβ”€β”€ __init__.py β”‚ β”‚ └── utils.py β”‚ └── my_script.py └── test β”œβ”€β”€ __init__.py └── test_my_script.py </code></pre> <p>When I run tests (usin...
<python><python-3.x><pytest><tox>
2022-12-22 08:55:31
1
3,121
aName
74,886,164
913,098
Pycharm doesn't recognize packages with remote interpreter
<h2>TL;DR - This is a PyCharm remote interpreter question.</h2> <p>Remote libraries are not properly synced, and PyCharm is unable to index properly when using remote interpreter. Everything runs fine.</p> <p>Following is the entire <s>(currently unsuccessful)</s> debug process</p> <p><strong>See update section for a n...
<python><windows><pycharm><remote-debugging>
2022-12-22 08:54:58
3
28,697
Gulzar
74,885,954
11,332,693
Checking if any string element of the column is matching with other column string list in python
<p>df</p> <pre><code> CAR1 CAR2 ['ford','hyundai'] ['ford','hyundai'] ['ford','hyundai'] ['hyundai','nissan'] ['ford','hyundai'] ['bmw', 'audi'] </code></pre> <p>Expected output :</p> <pre><code> CAR1 CAR2 Flag ['ford','hyundai'...
<python><pandas><string><list><dataframe>
2022-12-22 08:31:31
2
417
AB14
74,885,777
4,619,958
How to implement associated types in Python/Mypy? Or, what to do when wanting sub-classes to have subclass arguments?
<p>Consider the (simplified) code, where I want <code>Lean*</code> and <code>Isabelle*</code> extend the <code>Base*</code>.</p> <pre class="lang-py prettyprint-override"><code>class BaseProblem: ... class BaseStep: ... class LeanProblem(BaseProblem): ... class LeanStep(BaseStep): ... class IsabelleProblem(BaseProble...
<python><types><mypy><type-systems>
2022-12-22 08:15:36
0
17,865
ch271828n
74,885,555
10,710,625
Transform one row to a data frame with multiple rows
<p>I have a data frame containing one row:</p> <pre class="lang-py prettyprint-override"><code>df_1D = pd.DataFrame({'Day1':[5], 'Day2':[6], 'Day3':[7], 'ID':['AB12'], 'Country':['US'], 'Destination_A':['Miami'], ...
<python><pandas><dataframe>
2022-12-22 07:55:31
5
739
the phoenix
74,885,464
7,826,511
How to configure BaseURL in Django4?
<p>I'm new to <code>django</code> and trying to set a <code>baseURL</code> in <code>django4</code>. I came upon <a href="https://stackoverflow.com/questions/17420478/how-to-set-base-url-in-django">How to set base URL in Django</a> of which the solution is:</p> <pre><code>from django.conf.urls import include, url from ....
<python><django>
2022-12-22 07:44:21
1
6,153
Artur MΓΌller Romanov
74,885,462
3,247,006
"&" and "|" vs "and" and "or" for "AND" and "OR" operators in Django
<p>I have <strong><code>Blog</code> model</strong> below. *I use <strong>Django 3.2.16</strong> and <strong>PostgreSQL</strong>:</p> <pre class="lang-py prettyprint-override"><code># &quot;store/models.py&quot; from django.db import models class Blog(models.Model): post = models.TextField() def __str__(s...
<python><python-3.x><django><sql>
2022-12-22 07:44:05
2
42,516
Super Kai - Kazuya Ito
74,885,227
16,727,671
How to run command from variable instead of those line in python?
<p>I have below commands for run az aks command:</p> <pre><code>from azure.cli.core import get_default_cli az_cli = get_default_cli() res = az_cli.invoke(['login', '--service-principal', '-u', client_id, '-p', client_secret,'--tenant',tenant_id]) az_cli.invoke(['aks','command','invoke','--resource-group',resourcegroup,...
<python><azure><azure-cli>
2022-12-22 07:20:04
1
448
microset
74,885,225
11,479,825
Cast features to ClassLabel
<p>I have a dataset with type dictionary which I converted to <code>Dataset</code>:</p> <p>ds = datasets.Dataset.from_dict(bio_dict)</p> <p>The shape now is:</p> <pre><code>Dataset({ features: ['id', 'text', 'ner_tags', 'input_ids', 'attention_mask', 'label'], num_rows: 8805 }) </code></pre> <p>When I use the <...
<python><huggingface-transformers><huggingface-datasets>
2022-12-22 07:19:48
1
985
Yana
74,885,183
1,762,051
How to create zoom bot which can join and record meeting using official zoom API or SDK way?
<p>I want to create zoom bot which can join and record meeting using official way using zoom API or SDK.</p> <p>I saw there exists <a href="https://marketplace.zoom.us/docs/api-reference/introduction/" rel="nofollow noreferrer">ZOOM API Reference</a>, <a href="https://marketplace.zoom.us/docs/sdk/native-sdks/introducti...
<python><node.js><zoom-sdk>
2022-12-22 07:14:58
1
10,924
Alok
74,885,052
16,082,534
FHIR Converter for Python
<p>Is there is any function available in python to convert the given json input into HL7 FHIR format. By passing the Liquid Template (Shopify) and the input source data.</p>
<python><shopify><hl7-fhir><liquid-template>
2022-12-22 06:55:53
1
1,326
Akram
74,885,035
11,922,765
Import data from another dataframe for matching cells
<p>I have two data frames that I import from the excel sheets. There is some information I need to import from auxiliary dataframe to main dataframe if there is a matching. My code:</p> <pre><code>auxdf =pd.DataFrame({'prod':['look','duck','chik']},index=['prod_team1','prod_team2','prod_team3']) auxdf = ...
<python><excel><pandas><dataframe><numpy>
2022-12-22 06:53:49
3
4,702
Mainland
74,885,010
988,279
Flask. Roles_required decorator no more working after Flask upgrade
<p>When I upgrade my Flask project (Flask 1.0.2, Flask-Login 0.4.1) to the latest versions, the roles_required decorator no longer works. The &quot;login&quot; itself is working.</p> <p>models.py</p> <pre><code>... from flask_user import UserMixin class ApiUserRoles(db.Model): __tablename__ = 'apiuser_roles' u...
<python><flask>
2022-12-22 06:50:56
1
522
saromba
74,884,921
1,588,857
How to add attributes to a `enum.StrEnum`?
<p>I have an <code>enum.StrEnum</code>, for which I want to add attributes to the elements.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>class Fruit(enum.StrEnum): APPLE = (&quot;Apple&quot;, { &quot;color&quot;: &quot;red&quot; }) BANANA = (&quot;Banana&quot;, { &quot;color&quot;: &q...
<python><python-3.x><enums>
2022-12-22 06:36:15
1
2,844
midrare
74,884,887
4,377,095
Pandas setting column values to adjacent ones for duplicates found in a key column
<p>Assuming we have the following table:</p> <pre><code>+---------+------+------+------+------+------+------+------+------+ | COL_ID | ColB | COLC | COLD | COLE | COLF | COLG | COLH | COLI | +---------+------+------+------+------+------+------+------+------+ | aa1 | 1 | 1 | | | | | |...
<python><pandas>
2022-12-22 06:31:42
1
537
Led
74,884,821
10,710,625
Remove rows from grouped data frames based on column values
<p>I would like to remove from each subgroup in a data frame, the rows which satisfy certain conditions. The subgroups are grouped based on the two columns <code>Days</code> &amp; <code>ID</code>, here's my data frame:</p> <pre><code>df = pd.DataFrame({'Days':[5,5,5,5,6,6], 'ID':['A11','A11','A11','A...
<python><pandas><dataframe><filter><group-by>
2022-12-22 06:23:13
1
739
the phoenix
74,884,772
10,226,040
Regex - how can I get the last tag in this string
<p>I have a string</p> <pre><code>&quot;&lt;li style=&quot;-moz-float-edge: content-box&quot;&gt;... that in &lt;i&gt;&lt;b&gt;&lt;a href=&quot;/wiki/La%C3%9Ft_uns_sorgen,_la%C3%9Ft_uns_wachen,_BWV_213&quot; title=&quot;Lat uns sorgen, lat uns wachen, BWV 213&quot;&gt;Die Wahl des Herkules&lt;/a&gt;&lt;/b&gt;&lt;/i&gt;...
<python><regex>
2022-12-22 06:16:30
4
311
Chainsaw
74,884,688
19,321,677
How to aggregate dataframe and sum by boolean columns?
<p>I have this df and want to aggregate it so that the last 2 columns sum up and reduce duplicates per user id.</p> <p>current</p> <pre><code>user_id | name | product | ...| purchase_flag | retention_flag 123 | John | book | ...| 0 | 1 123 | John | book | ...| 1 | 0 .... </code></p...
<python><pandas>
2022-12-22 06:05:08
1
365
titutubs
74,884,660
149,900
pip specify package version either '==x.y' or '>=a.b'
<p>When installing with <code>pip</code> -- or by specifying through <code>requirements.txt</code> -- how do I specify that the version is <em>either</em>:</p> <ul> <li><code>==x.y</code>, <em>or</em></li> <li><code>&gt;=a.b</code></li> </ul> <p>where <code>x.y &lt; a.b</code>.</p> <p>For example, I want a package to b...
<python><pip>
2022-12-22 06:00:48
2
6,951
pepoluan
74,884,618
574,308
Dockerized python.django app does not run in the browser
<p>I have a python-Django app built in ubuntu OS that I am trying to containerize. Docker builds and runs with no errors. But when I try to browse the site in a browser, I do not see it.</p> <p>This is my allowed hosts in settings.py</p> <pre><code>ALLOWED_HOSTS = [&quot;localhost&quot;, &quot;127.0.0.1&quot;,&quot;0.0...
<python><django><docker>
2022-12-22 05:53:50
1
2,750
Reza.Hoque
74,884,538
3,004,472
python regex to extract only specific pattern file names from a list
<p>I would like to extract only certain files from a list. I need to apply following rules while extracting only selected files from a list.</p> <p>if the file contains patterns like <strong>f[1-99]</strong> or <strong>t[1-99]</strong> or <strong>v[1-99]</strong> or combination of <strong>f[1-9]_v[1-9]_t[1-9]</strong>....
<python><regex><python-re>
2022-12-22 05:43:53
1
880
BigD
74,884,385
5,928,682
Print a string with " " in place of '' in python
<p>I am trying a create a role in AWS.</p> <p>These role details are coming in from a json object.</p> <pre><code>shared ={ &quot;mts&quot;:{ &quot;account_id&quot;:&quot;11111&quot;, &quot;workbench&quot;:&quot;aaaaa&quot;, &quot;prefix&quot;:&quot;zzzz&quot; }, &quot;tsf&quot;:{ ...
<python><amazon-web-services>
2022-12-22 05:16:47
4
677
Sumanth Shetty
74,884,154
9,542,989
Dynamically Enable/Disable Form Fields in Streamlit
<p>I have a form in Streamlit that looks something like this,</p> <pre><code>with st.form(&quot;my_form&quot;): text_input_1 = st.text_input(&quot;Input 1&quot;) drop_down_1 = st.selectbox(&quot;Dropdown 1&quot;, [&quot;Option 1&quot;, &quot;Option 2&quot;]) drop_down_2 = st.selectbox(&quot;Dropdown 2&quot;, ...
<python><python-3.x><streamlit>
2022-12-22 04:34:15
1
2,115
Minura Punchihewa
74,884,117
3,247,006
How to run "AND" operator with "filter()" without "SyntaxError: keyword argument repeated:" error in Django?
<p>I have <strong><code>Blog</code> model</strong> below. *I use <strong>Django 3.2.16</strong> and <strong>PostgreSQL</strong>:</p> <pre class="lang-py prettyprint-override"><code># &quot;store/models.py&quot; from django.db import models class Blog(models.Model): post = models.TextField() def __str__(s...
<python><python-3.x><django><django-filter><sql>
2022-12-22 04:24:57
1
42,516
Super Kai - Kazuya Ito
74,884,113
5,769,497
Read a CSV file with Json column using Pandas
<p>I've a CSV file that contains couple of JSON columns and I'm reading it using python panda. The sample file data looks like the following :</p> <pre><code>12345,67890,{&quot;key1&quot;:&quot;value1&quot;,&quot;key2&quot;:&quot;value2&quot;,&quot;key3&quot;:&quot;value3&quot;},abcdefgh,{&quot;key4&quot;:&quot;value4&...
<python><pandas><csv>
2022-12-22 04:24:11
1
2,489
Sanket Makani
74,883,991
2,392,358
awk + adding a column baed on values of another column + adding a field name in the 1 command
<p>I want to add a new column at the end, based on the text of another column(with an if statement), and then I want to add a new column/field name. I am close but I am struggling with the syntax, I am using awk, but apologies its been a while since I used this. and I am wondering if I should use python/anaconda(jupyte...
<python><awk>
2022-12-22 03:57:23
4
4,703
HattrickNZ
74,883,933
11,225,821
Django logger refuse to show full traceback in file message
<p>Currently, i'm setting up logging in Django following the document <a href="https://docs.djangoproject.com/en/2.2/topics/logging/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.2/topics/logging/</a> (I'm using Django 2.2 with python3.7) and Django rest framework. Here is my settings.py:</p> <pre><cod...
<python><django><logging><django-rest-framework>
2022-12-22 03:45:43
1
3,960
Linh Nguyen
74,883,922
313,042
Removing pixels below a certain threshold
<p>I have a grayscale image with something written in the front and something at the back. I'd like to filter out the back part of the letters and only have the front. It's only grayscale and not RGB, and I'd rather not have to calculate pixels manually.</p> <p>Is there any library function I can use to do this? I'm ne...
<python><image-processing><python-imaging-library>
2022-12-22 03:42:53
2
11,966
Rajath
74,883,814
13,079,519
How to send message to a specific discord channel
<p>I am trying to send a message to a specific channel and I can run the code below just nothing show up on the channel and I have no idea why... I put the channel Id in the get_channel input, just putting a random number here.</p> <pre><code>import discord client = discord.Client() async def send_msg(msg): chann...
<python><discord>
2022-12-22 03:14:35
1
323
DJ-coding
74,883,691
14,397,434
what does a variable mean on its own in a python list?
<pre><code>list1 = [&quot;Mike&quot;, &quot;&quot;, &quot;Emma&quot;, &quot;Kelly&quot;, &quot;&quot;, &quot;Brad&quot;] [i for i in list1 if i] ['Mike', 'Emma', 'Kelly', 'Brad'] </code></pre> <p>Why is it that simply saying &quot;if i&quot; works?</p> <p>Why doesn't i==True work? Or why doesn't i==False return anythi...
<python><list><for-loop><boolean>
2022-12-22 02:43:51
1
407
Antonio
74,883,192
911,971
Intentionally returning None instead of object
<p>Suppose I have two simple classes:</p> <pre class="lang-py prettyprint-override"><code>@dataclass class Item(): Name: str Valie: float class Registry(): items = [] def __init__(self): # load some items from external source, etc &quot;&quot;&quot; find an element in an array or return None &quot;&q...
<python><python-typing>
2022-12-22 00:51:05
1
506
parasit
74,883,180
1,897,151
dataclasss python reconstruct value
<p>lets say i have this dataclass</p> <pre><code>@dataclass_json @dataclass class TestMetaData: edit_meta: MetaData @dataclass_json @dataclass class MetaData: list_meta: list[MetaDataList] @dataclass_json @dataclass class MetaDataList: name: str fields: list[MetaDataFields] class MetaDataFields: ...
<python>
2022-12-22 00:48:23
0
503
user1897151
74,883,102
2,444,023
Is it possible to simulate a distribution from a glm fit in statsmodels?
<p>I would like to fit a multiple linear regression. It will have a couple input parameters and no intercept.</p> <p>Is it possible to fit a glm fit with statsmodels then use that fit to simulate a distribution of predicted values?</p>
<python><statistics><statsmodels>
2022-12-22 00:33:02
1
2,838
Alex
74,883,093
213,759
How to deal with system Python and `brew link python` on MacOS?
<p>I cannot link Python 3.8 over system Python 3.9.</p> <p>I have few installed python versions (3.8, 3.10, etc) by brew and system Python 3.9.</p> <p>P.S. I cannot uninstall system one (it does not appear in Applications).</p> <pre class="lang-bash prettyprint-override"><code>$ python3 --version ...
<python><macos><homebrew>
2022-12-22 00:32:09
2
3,127
Kirby
74,882,649
12,361,700
multiprocessing.Pool not using all the cores in M1 Mac
<p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>from multiprocessing.dummy import Pool def process_board(elems): # do something for _ in range(1000): with Pool(cpu_count()) as p: _ = p.map(process_board, enumerate(some_array)) </code></pre> <p>and this is the activity monitor of my mac w...
<python><multithreading><cpu>
2022-12-21 23:09:46
1
13,109
Alberto
74,882,623
15,178,267
Django: how to write django signal to update field in django?
<p>i want to write a simple django signal that would automatically change the status of a field from <strong>live</strong> to <strong>finished</strong>, when i check a button <strong>completed</strong>.</p> <p>I have a model that looks like this\</p> <pre><code> class Predictions(models.Model): ## other fields are ...
<python><django>
2022-12-21 23:05:04
1
851
Destiny Franks
74,882,555
1,551,027
How to log all permissions an application is using in Google Cloud's SDK
<p>I have a sandbox project that I am currently in an owner role for. This gives me great freedom in development and I've written a bunch of python code that uses the following:</p> <pre><code>Storage Security Center Storage Notifications Datastore Secret Manager Pub/Sub </code></pre> <p>I would like to log all of the ...
<python><google-cloud-platform><google-cloud-iam><google-cloud-logging>
2022-12-21 22:55:37
1
3,373
Dshiz
74,882,548
17,487,457
Calculate time difference of 2 adjacent datapoints for each user
<p>I have the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( {'user_id': [53, 53, 53, 53, 53, 53, 53, 53, 54, 54, 54, 54, 54, 54, 54], 'timestamp': [10, 15, 20, 25, 30, 31, 34, 37, 14, 16, 18, 20, 22, 25, 28], 'activity': ['A', 'A', 'A', 'A', 'A', 'A', 'A', '...
<python><pandas><dataframe>
2022-12-21 22:54:17
1
305
Amina Umar
74,882,495
5,568,409
Convert a Python dataframe date column in seconds
<p>I am reading a <code>.csv</code> data file using <code>pd.read_csv</code> and I get these first 5 rows from my global dataframe (containing thousands of rows):</p> <pre><code> time id time_offset 0 2017-12-01 21:00:00 0 -60 1 2017-12-01 21:01:00 0 -59 2 2017-12-01 21:02:00 ...
<python><pandas><dataframe><datetime>
2022-12-21 22:46:26
3
1,216
Andrew
74,882,381
2,326,896
Best practices for defining fields only relevant in subclasses in Python
<p>If I have a variable that is only used in a subclass, should I assign None to it in the superclass?</p> <p>This is minimum example, there other subclasses where β€˜number’ is different but the β€˜show’ method is still relevant.</p> <pre><code>class A: def show(self): print(self.number) class C(A): numbe...
<python><oop>
2022-12-21 22:29:57
1
891
Fernando CΓ©sar
74,882,139
5,212,614
How can we parse a JSON file for specific records of county borders and overlay that on a Folium HeatMap?
<p>I found a JSON file that has borders of US counties, right here.</p> <p><a href="https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_500k.json" rel="nofollow noreferrer">https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_500k.json</a></p> <p>How can I parse that file for specific records...
<python><json><python-3.x><folium>
2022-12-21 21:55:41
1
20,492
ASH
74,882,136
5,604,562
Memory efficient dot product between a sparse matrix and a non-sparse numpy matrix
<p>I have gone through similar questions that has been asked before (for example <a href="https://stackoverflow.com/questions/41942115/numpy-efficient-large-dot-products">[1]</a> <a href="https://stackoverflow.com/questions/20983882/efficient-dot-products-of-large-memory-mapped-arrays">[2]</a>). However, none of them c...
<python><numpy><matrix><scipy><sparse-matrix>
2022-12-21 21:55:02
3
3,604
Grayrigel
74,882,120
10,096,713
Scrape info from popup window with Playwright in Python and store in pandas df
<p>I'm using Playwright in a Jupyter Notebook to obtain building construction years from a property appraiser's website. Some web pages, <a href="https://www.pbcgov.org/papa/Asps/PropertyDetail/PropertyDetail.aspx?parcel=73414434010020070" rel="nofollow noreferrer">like this one</a>, have multiple buildings' data viewa...
<python><pandas><async-await><playwright-python>
2022-12-21 21:52:58
1
335
Adam
74,882,060
12,506,687
Select related is not returning all the values from the relation in Django
<p>I'm doing this query</p> <pre class="lang-sql prettyprint-override"><code>SELECT [User].[User_Id], [User].[Client_id], [User].[EMail], [User].[First_Name], [User].[Family_Name], [User].[Telephone], [Clients].[Client_Id], [Clients].[Name], [Clients].[Organization_type] FROM [User] INNER JOIN [Clients] ON ([User].[Cli...
<python><django>
2022-12-21 21:44:55
2
476
Rinzler21
74,881,986
14,594,208
How to cross join (cartesian product) two Series?
<p>Consider the following two series.</p> <p>Let <code>x</code> be:</p> <pre class="lang-py prettyprint-override"><code>x a 10 b 20 c 30 Name: x_value </code></pre> <p>And let <code>y</code> be:</p> <pre class="lang-py prettyprint-override"><code>y d 100 e 200 Name: y_value </code></pre> <p>Ideally, the resul...
<python><pandas><series>
2022-12-21 21:35:03
2
1,066
theodosis
74,881,956
1,901,114
Inconsistent default logarithm base in sqlite3
<p>I've been experiencing an issue where SQLite's log function returns inconsistent results between PyCharm's Query console and when running the same query in python environments. The code where I first spotted this used SQLAlchemy, but it can also be seen using sqlite3 module here:</p> <pre><code>&gt;&gt;&gt; from sql...
<python><sqlite><pycharm>
2022-12-21 21:30:49
0
1,656
Mirac7
74,881,643
14,084,653
Passing lambda function as Parameter to threading.Thread
<p>Im new to python so forgive me if Im not applying best practices and I welcome any feedback to help doing the code below the python way. I have the following code and the out put is making me very confused and not sure how to fix in order to get the expected output. Im getting the name Sal on both greetings:</p> <pr...
<python><python-3.x>
2022-12-21 20:50:28
0
779
samsal77
74,881,441
14,867,609
Why is Scipy's cross correlation function giving incorrect results for audio signals
<p>I'm trying to calculate the location of a sound source using TDOA, by cross correlating audio recordings from different microphones and getting the time delay. I am fairly confident that the recording start times are synchronized to 0.01ms or less. The microphones are all plugged into a RaspberryPi.</p> <p>However, ...
<python><audio>
2022-12-21 20:25:17
0
306
Jevon Mao
74,881,425
769,449
Python loop through nested JSON object without root element
<p>I've already checked <a href="https://stackoverflow.com/questions/34818782/iterate-through-nested-json-object-and-get-values-with-python">here</a> and <a href="https://stackoverflow.com/questions/45784067/scrapy-on-a-json-response">here</a>.</p> <p>I have the following json which has no root element and I want to lo...
<python><for-loop><nested>
2022-12-21 20:23:06
2
6,241
Adam
74,881,392
1,218,712
Is there a way to simplify an undirected graph with OSMNX?
<p>In my research, I use OpenStreetMap data for traffic-related simulations. Part of the data preparation involves using the <em>osmnx</em> library to get a <a href="https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.simplification.simplify_graph" rel="nofollow noreferrer">simplified graph</a> of the road network....
<python><networkx><openstreetmap><graph-theory><osmnx>
2022-12-21 20:19:34
1
571
David Murray
74,881,369
5,977,437
TypeError when creating Series from custom ExtensionArray
<p>I've created a basic example custom Pandas Extension Type for storing 2D coordinates, with source code below.</p> <p>I'm able to successfully create arrays of this type using pd.array() which work as expected:</p> <pre><code>arr = pd.array([(1.5, 2.0), (156, 21), (-120, 98.5)], dtype='coordinate') </code></pre> <p><...
<python><pandas>
2022-12-21 20:16:35
1
369
Finn Andersen
74,881,303
738,794
Snips-nlu fit failed with error module 'numpy' has no attribute 'float' after following quick start
<p>With the latest version 0.20.2 snips-nlu library on a windows 10 machine (python 3.8.15 and numpy 1.24.0), I got attribute Error when fitting the engine. What could be the issue?</p> <pre><code>(nlpenv) C:\Users\one&gt;python -m snips_nlu train sample_dataset.json nlu_engine Create and train the engine... Traceback ...
<python><nlu>
2022-12-21 20:08:45
1
697
YuMei
74,881,272
17,889,840
How to create Tensorflow dataset batches for variable shape inputs?
<p>I have dataset for image captioning. Each image has different number of captions (or sentences), let say some images have seven captions and other may have ten or more. I used the following code for dataset creation:</p> <pre><code>def make_dataset(videos, captions): dataset = tf.data.Dataset.from_tensor_slices(...
<python><tensorflow-datasets><batchsize>
2022-12-21 20:05:36
0
472
A_B_Y
74,881,230
3,200,552
How to use asyncio.gather with dynamically generated tasks?
<p>I have an async method called <code>send_notifications_async(token)</code>. This method users a library to sent apple push notifications asynchronously. Given a list of tokens how can I dynamically create a iterable set of tasks to run asynchronously with asyncio.gather?</p> <pre><code>async def gather_notification_...
<python><asynchronous><apple-push-notifications><python-asyncio>
2022-12-21 20:01:03
0
785
merhoo
74,881,208
7,984,318
pandas python how to convert time duration to milliseconds?
<p>I have a df ,you can have it by copy and run the following code:</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; b_id duration1 duration2 user 384 28 days 21:05:16.141263 0 days 00:00:44.999706 Test &...
<python><pandas><dataframe><datetime><timedelta>
2022-12-21 19:58:54
2
4,094
William
74,881,196
5,716,633
I am looking for a comprehensive explanation of the `inputs` parameter of the `.backward()` method in PyTorch
<p>I am having trouble understanding the usage of the <code>inputs</code> keyword in the <code>.backward()</code> call.</p> <p>The Documentation says the following:</p> <blockquote> <p><strong>inputs</strong> (sequence of Tensor) – Inputs w.r.t. which the gradient will be accumulated into .grad. All other Tensors will ...
<python><pytorch><autograd>
2022-12-21 19:57:49
1
449
Shashwat
74,881,158
9,415,280
deleat row with nan in a tensorflow dataset
<p>There is a way to do like pandas inside tensor dataset, deleating row with a nan like this???</p> <pre><code>ds = ds[~np.isnan(ds).any(axis=1)] </code></pre> <p>My test exemple is:</p> <pre><code>simple_data_samples = np.array([ [1, 11, 111, -1, -11], [2, np.nan, 222, -2, -22], [3, 33, 333, -3, -33], ...
<python><tensorflow><nan><tensorflow-datasets><tf.data.dataset>
2022-12-21 19:53:55
1
451
Jonathan Roy
74,881,051
360,557
Rendering an ellipse using matplotlib to a basemap with a projection
<p>I'm plotting an ellipse using matplotlib using this code:</p> <pre><code>lat = float(ellipse['cy']) lng = float(ellipse['cx']) width = float(ellipse['rx']) / 111111.0 height = float(ellipse['ry']) / 111111.0 rot = float(ellipse['rotation']) # + 180? xpt, ypt = lng, lat if m != None: xpt, ypt = m(lng, lat) ell =...
<python><matplotlib><ellipse>
2022-12-21 19:40:58
1
534
Mike Stoddart
74,880,905
7,984,318
pandas how to get mean value of datetime timestamp with some conditions?
<p>I have a df ,you can have it by copy and run the following code:</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; b_id duration1 duration2 user 366 NaN 38 days 22:05:06.807430 Test 3...
<python><pandas><dataframe><numpy><pandas-timeindex>
2022-12-21 19:26:51
1
4,094
William
74,880,762
8,587,712
How to fill between two curves of different x and y ranges with matplotlib
<p>Say I have two lines, defined by the data</p> <pre><code>x1 = [0,1,2,3] y1 = [3,5,4,6] x2 = [1.5,2.5,3.5,4.5] y2 = [1,3,2,4] </code></pre> <p>which make the plot</p> <pre><code>plt.figure(figsize=(10,10)) plt.plot(x1, y1) plt.plot(x2, y2) plt.show() </code></pre> <p><a href="https://i.sstatic.net/z2zoZ.png" rel="nof...
<python><matplotlib><plot><astronomy>
2022-12-21 19:11:21
0
313
Nikko Cleri
74,880,750
5,399,268
Problem using exec within class' function in Python
<p>The following code works as expected</p> <pre><code>name = &quot;Test&quot; myname = &quot;&quot; exec('myname =&quot;' + name + '&quot;') print(myname) </code></pre> <p>Which shows as result:</p> <pre><code>Test </code></pre> <h2>Problem</h2> <p>However, if I define the same within a function in a <code>class</code...
<python><class><exec>
2022-12-21 19:10:15
1
4,793
Cedric Zoppolo
74,880,733
7,984,318
pandas error:None of ['b_id'] are in the columns
<p>I'm trying to create a dataframe from the following code:</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; b_id Rejected Remediation user 366 NaN 38 days 22:05:06.807430 Test 367 ...
<python><pandas><dataframe>
2022-12-21 19:08:31
1
4,094
William
74,880,709
1,677,381
How to identify the user or machine making an HTTP request to an Apache web server on RHEL 7 using server side Python or client side script?
<p>I have a RHEL 7 Linux server using Apache 2.4 as the httpd daemon. One of the pages served by Apache is a simple https form that is generated using Python 3.11. Currently, the form is submitting and being processed properly, but we have no way to track where the form was submitted from.</p> <p>Ideally, there would b...
<python><apache><authentication><https><rhel>
2022-12-21 19:06:31
1
363
Calab
74,880,628
6,382,242
OneHotEncoder - Predefined categories for SOME columns?
<p>Let's say I have this dataframe:</p> <pre><code>df = pd.DataFrame({&quot;a&quot;: [1,2,3], &quot;b&quot;: [&quot;d&quot;, &quot;d&quot;, &quot;d&quot;]}) </code></pre> <p>And I want to OneHotEncode both the &quot;a&quot; and &quot;b&quot; columns. But let's say that I know what the categories of the &quot;a&quot; co...
<python><pandas><one-hot-encoding>
2022-12-21 18:57:34
2
529
WalksB
74,880,421
7,598,461
Can't create venv in docker jupyter image (permissions)
<p>When trying to docker build from this Dockerfile:</p> <pre><code>FROM jupyter/datascience-notebook:latest ENV VIRTUAL_ENV=/opt/venv RUN python -m venv $VIRTUAL_ENV </code></pre> <p>... I receive the following error:</p> <pre><code>Error: [Errno 13] Permission denied: '/opt/venv' The command '/bin/bash -o pipefail -c...
<python><docker><permissions><python-venv>
2022-12-21 18:36:45
0
5,091
jsstuball
74,880,315
10,164,750
extract hypen separated values from a column and apply UDF
<p>I have a <code>dataframe</code> like as provided below:</p> <pre><code>+--------+-------+-------+--------------+--------------------+-----------------+----------+--------------------+------------+ |sequence|recType|valCode|registerNumber| rest| errorCode|errorType | errorDescription|isSucces...
<python><apache-spark><pyspark>
2022-12-21 18:23:56
1
331
SDS
74,880,185
4,752,223
TypeError: cannot pickle '_hashlib.HASH' object
<p>I have a rather simple dataclass.</p> <p>I saved it on a pickle (using dill instead of the real pickle).</p> <p><code>import dill as pickle</code></p> <p>After some other operations:</p> <ul> <li>Loading the same pickle fails</li> <li>Trying to save the same object fails</li> </ul> <p>Error:</p> <p><code>TypeError: ...
<python><pickle><dill>
2022-12-21 18:11:31
2
2,928
Rub
74,880,162
14,256,643
How to get specific part of any url using urlparse()?
<p>I have an url like this</p> <pre><code>url = 'https://grabagun.com/firearms/handguns/semi-automatic-handguns/glock-19-gen-5-polished-nickel-9mm-4-02-inch-barrel-15-rounds-exclusive.html' </code></pre> <p>When I use <code>urlparse()</code> function, I am getting result like this:</p> <pre><code>&gt;&gt;&gt; url = url...
<python><urllib><python-re><url-parsing>
2022-12-21 18:09:45
4
1,647
boyenec
74,880,134
14,791,134
BeautifulSoup find.text returns empty string although element exists
<p>I am scraping the following; <a href="https://www.espn.com/nfl/scoreboard/" rel="nofollow noreferrer">https://www.espn.com/nfl/scoreboard/</a> and trying to get the times of the games</p> <pre class="lang-py prettyprint-override"><code>import requests from bs4 import BeautifulSoup r = requests.get(&quot;https://www...
<python><web-scraping><beautifulsoup><espn>
2022-12-21 18:07:03
1
468
earningjoker430
74,880,119
1,828,289
Get peak memory usage of process tree
<p>I have a commandline program that launches a bunch of subprocesses (which themselves can launch more subprocesses). I'd like to somehow determine the peak combined memory usage of all subprocesses in the whole tree. This is on linux; I don't have source code for the program.</p> <p>I can run the program from pytho...
<python><linux><memory><memory-profiling>
2022-12-21 18:05:43
0
20,357
Alex I
74,879,980
9,603,285
How to overlay two 2D-histograms in Matplotlib?
<p>I have two datasets (corresponding with the time-positional data of hydrogen atoms and time-positional data of alumina atoms) in the same system. I want to plot the density of each element by overlaying two <code>hist2d</code> plots using matplotlib.</p> <p>I am currently doing this by setting an alpha value on the ...
<python><matplotlib>
2022-12-21 17:52:55
1
601
lcdumort
74,879,738
16,009,435
unable to host flask app on a specific ip and port
<p>I wanted to host my flask app on a specific port but the method I am using is not working. What I did is assign the <code>host</code> and <code>port</code> properties in my <code>socket.run()</code>. When I go to the specified address the page doesn't load. Where did I go wrong and how can I properly host a flask ap...
<python><flask>
2022-12-21 17:30:42
2
1,387
seriously
74,879,722
6,635,590
Check if a filename has multiple '.'/periods in it
<p>So I'm making a website and in one of the pages you can upload images.</p> <p>I didn't think of this before when making my file upload function but files are allowed to have multiple <code>.</code> in them, so how can I differentiate between the &quot;real&quot; <code>.</code> and the fake <code>.</code> to get the ...
<python><file><bottle>
2022-12-21 17:29:31
2
734
tygzy
74,879,616
4,414,359
How to filter a pandas dataframe after groupby and mean
<p>Does anyone know off the top of their head how to filter after grouping a dataframe and applying the mean function? I'd like to be able to get the <code>hour</code>s and <code>count</code>s for <code>day</code>s 0, 5, 6.</p> <p><a href="https://i.sstatic.net/Cp3Mn.png" rel="nofollow noreferrer"><img src="https://i.s...
<python><pandas><function><filter><group-by>
2022-12-21 17:19:52
1
1,727
Raksha
74,879,346
387,851
Upgrade SQLite version on Lambda Python3.9
<p>The built-in version of SQLite on the AWS Lambda runtime Python 3.9 is v3.7.17 which was released in 2013. I am unable to upgrade this version with a Layer or Code Deployment because library sources are arranged in such a away where it's not overridable since Python 3.9 is bundled with SQLite (batteries included and...
<python><sqlite><aws-lambda>
2022-12-21 16:58:29
1
1,748
four43
74,879,306
5,901,870
Convert a pyspark dataframe into a dictionary filtering and collecting values from columns
<p>I need to convert this DataFrame to a dictionary:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>value-1</th> <th>value-2</th> <th>value-3</th> </tr> </thead> <tbody> <tr> <td>1A</td> <td>Approve</td> <td>NULL</td> <td>NULL</td> </tr> <tr> <td>2B</td> <td>Approve</td> <td>Ap...
<python><dataframe><dictionary><pyspark>
2022-12-21 16:55:13
1
400
Mikesama
74,879,287
11,693,768
Pandas not filtering unless dataframe is saved into a csv and read back as a csv, source is a json loaded into dataframe
<p>I have a json output which looks like this.</p> <pre><code>{'pagination': {'limit': 100, 'offset': 0, 'count': 38, 'total': 38}, 'data': [{'name': 'Ceco Environmental Corp', 'symbol': 'CECE', 'has_intraday': False, 'has_eod': True, 'country': None, 'stock_exchange': {'name': 'NASDAQ Stock Exchange', ...
<python><json><pandas><dataframe><filter>
2022-12-21 16:53:31
2
5,234
anarchy
74,879,238
598,057
How to reliably access root tag's namespace declarations and attributes using lxml?
<p>In the following example, is there a way to either:</p> <ol> <li>only print the root <code>REQ-IF</code> tags's complete attributes without having lxml to print the whole XML document or</li> <li>to enumerate the root tag's namespaces and attributes in the same order as they appear in an XML document?</li> </ol> <p>...
<python><lxml>
2022-12-21 16:49:16
0
11,408
Stanislav Pankevich
74,879,188
1,044,326
Limit the height of the violin plot data within range
<p>How can I make sure that violin plot contained within it's data range? I have binary classified feature categories (1,0). Within that values can range from 0 to 1. However as you can see when binary classification is 1 (orange). There is no values beyond 0.6. How can I fix that?</p> <pre><code>for f in binary_featur...
<python><matplotlib><seaborn><violin-plot>
2022-12-21 16:44:56
1
1,550
MonteCristo
74,879,157
2,878,290
Azure Data Factory Trigger Azure Notebook Failure
<p>I am trying to execute the notebook via azure datafactory to Azure Databricks notebook but unable to success my ADF pipeline, if I run the azure databricks notebook separately on my pyspark scripts, there is no error but if run via the ADF pipeline, i am getting below like.</p> <blockquote> <p>ModuleNotFoundError: N...
<python><pyspark><azure-databricks><azure-data-factory>
2022-12-21 16:41:48
1
382
Developer Rajinikanth
74,879,155
20,652,094
Pandas or R - Merge Rows By Same Value in Column Over NaN values - Look at Example
<p>I have a very specific dataset it looks something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>record_id</th> <th>event_id</th> <th>instrument</th> <th>repeat_inst</th> </tr> </thead> <tbody> <tr> <td>PI0005</td> <td>v03_abc_1</td> <td><code>NaN</code></td> <td>1</td> </tr>...
<python><r><pandas>
2022-12-21 16:41:44
1
307
user123
74,879,121
10,682,580
Efficiently localize an array of datetimes with pytz
<p>What is the most efficient way of converting an array of naive <code>datetime.datetime</code> objects to an array of timezone-aware datetime objects?</p> <p>Currently I have them in a numpy array. The answer doesn't necessarily need to end up as a numpy array, but should consider starting as one.</p> <p>e.g. if I ha...
<python><arrays><numpy><datetime><pytz>
2022-12-21 16:38:37
1
2,419
alex_danielssen
74,879,104
16,389,095
Kivy MD: How to switch between different layouts using MD Tabs
<p>I'm trying to design a user interface in Python / Kivy MD. The layout should include a MDTab with some icons on top, a button at the bottom and some widgets in the middle. By clicking on the tab icons, the widget in the middle should change accordingly. For example modifying the text of a label (<em>see code</em>). ...
<python><layout><kivy><kivy-language><kivymd>
2022-12-21 16:37:18
1
421
eljamba
74,879,074
5,212,614
How can we search for a few strings in a column and multiply another column by a constant?
<p>I thought I could search for a string in a column, and if the result is found, multiply a value in another column by a string, like this.</p> <pre><code>df_merged['MaintCost'] = df_merged.loc[df_merged['Code_Description'].str.contains('03 Tree','17 Tree'), 'AvgTotal_OH_Miles'] * 15 df_merged['MaintCost'] = df_merged...
<python><python-3.x><pandas>
2022-12-21 16:34:42
1
20,492
ASH