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
75,313,590
1,112,097
Modifying pandas dataframe colums based on conditionals
<p>I am trying to modify the values in columns of a pandas DataFrame based on conditionals. This answer: <a href="https://stackoverflow.com/a/50779719/1112097">https://stackoverflow.com/a/50779719/1112097</a> is close, but the conditionals used are too simple for my use case, which uses a dictionary of lists in the con...
<python><pandas><dataframe>
2023-02-01 16:54:57
5
2,704
Andrew Staroscik
75,313,574
2,403,819
Automate the update of packages in pyproject.toml from virtualenv or pip-tools
<p>I am trying to update my Python CI environment and am working on package management right now. I have several reasons that I do not want to use Poetry; however, one nice feature of poetry is the fact that it automatically updates the <code>pyproject.toml</code> file. I know that pip-tools can create a <code>requir...
<python><pip><python-packaging><pyproject.toml><pip-tools>
2023-02-01 16:54:05
1
1,829
Jon
75,313,520
935,376
How to bring pytorch datasets into pandas dataframe
<p>I have seen a lot of code on how to convert pandas data to pytorch dataset. However, I haven't found or been able to figure out to do the reverse. i.e. Load pytorch dataset into pandas dataframe. I want to load AG news into pandas. Can you please help? Thanks.</p> <p><code>from torchtext.datasets import AG_NEWS</cod...
<python><pandas><pytorch><torchtext>
2023-02-01 16:49:55
1
2,064
Zenvega
75,313,508
4,506,929
How can I type wider range of LaTeX characters in the IPython REPL
<p>This question is specific about the IPython REPL, not the Jupyter notebook.</p> <p>Currently according to the <a href="https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.completer.html#forward-latex-unicode-completion" rel="nofollow noreferrer">docs on forward latex completion</a>:</p> <blockquote> ...
<python><jupyter-notebook><ipython>
2023-02-01 16:49:07
1
3,547
TomCho
75,313,493
2,398,593
Cannot install awesomeversion==22.9.0 because these package versions have conflicting dependencies
<p>I've never done any Python so I'm not familiar with the package versions and dependencies system overall. I'm trying to run this repo <a href="https://github.com/Maaxion/homeassistant2influxdb" rel="nofollow noreferrer">https://github.com/Maaxion/homeassistant2influxdb</a></p> <p>For this, I want to use Docker. So o...
<python><pip>
2023-02-01 16:47:50
2
23,968
maxime1992
75,313,457
4,831,435
OpenAI API: openai.api_key = os.getenv() not working
<p>I am just trying some simple functions in Python with OpenAI APIs but running into an error:</p> <p>I have a valid API secret key which I am using.</p> <p>Code:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import openai &gt;&gt;&gt; openai.api_key = os.getenv(&quot;I have placed the key here&quot;) &gt;&gt;&gt...
<python><openai-api><chatgpt-api><gpt-3><gpt-4>
2023-02-01 16:44:32
3
9,549
Ranadip Dutta
75,313,424
4,751,273
Can not run the code of this repository - NETL-Automatic-Topic-Labelling-
<p>I am trying to run this <a href="https://github.com/sb1992/NETL-Automatic-Topic-Labelling-" rel="nofollow noreferrer">code</a> - Automatic Labelling of Topics with Neural Embeddings</p> <p>The problem is that they did not mention what versions they used for the libraries and tools they used. Sadly, not even which Py...
<python><nlp><gensim><word-embedding><python-embedding>
2023-02-01 16:41:51
1
1,064
ziMtyth
75,313,204
1,710,392
Correct way to append to string in python
<p>I've read this <a href="https://stackoverflow.com/a/4435752/1710392">reply</a> which explains that CPython has an optimization to do an in-place append without copy when appending to a string using <code>a = a + b</code> or <code>a += b</code>. I've also read this PEP8 recommendation:</p> <blockquote> <p>Code should...
<python>
2023-02-01 16:22:57
2
5,078
Étienne
75,312,974
5,754,828
List index out of range (Fractional Knapsack)
<p>I'm attempting to implement a greedy algorithm for the fractional knapsack problem for a coursera assignment. The course insists on not giving the inputs that cause the problem. Below is my code of the solution and the code I used for stress testing.</p> <pre><code>def optimal_value(capacity, weights, values): v...
<python><greedy>
2023-02-01 16:04:47
0
397
Erol Can Akbaba
75,312,873
19,003,861
Django form with m2m relationship not saving
<p>I have a form where I want <code>request.user</code> to populate as little as possible and rely on the views to populate other fields automatically.</p> <p>As a result, some of these fields are not rendered on the form.</p> <p>The code in my view seems to work fine for the <code>FK relationship</code>, but some reas...
<python><django><django-views><django-forms><django-queryset>
2023-02-01 15:58:29
1
415
PhilM
75,312,786
11,725,056
How the change EVERY children tag (of a specific nature) to a different one using BeauifulSoup
<p>In the Given <code>HTML</code> below:</p> <pre><code>given = &quot;&quot;&quot;&lt;html&gt; &lt;body&gt; Free Text: Above &lt;ul&gt; &lt;li&gt; data 1 &lt;/li&gt; &lt;li&gt; &lt;ul&gt; &lt;li&gt; &lt;ol start = &...
<python><html><python-3.x><beautifulsoup><replace>
2023-02-01 15:51:40
1
4,292
Deshwal
75,312,706
12,469,912
Find all combinations of positive integers in increasing order that adds up to a given positive number n
<p>How to write a function that takes <code>n</code> (where n &gt; 0) and returns the list of all combinations of positive integers that sum to <code>n</code>? This is a common question on the web. And there are different answers provided such as <a href="https://www.geeksforgeeks.org/find-all-combinations-that-adds-up...
<python><python-3.x>
2023-02-01 15:44:06
3
599
plpm
75,312,537
9,472,066
SQLAlchemy - is BigInteger Identity column possible in ORM?
<p>I want to create BigInteger Identity column in SQLAlchemy ORM. <a href="https://docs.sqlalchemy.org/en/20/dialects/postgresql.html" rel="noreferrer">Documentation</a> does not have any example of either ORM Identity or BigInteger Identity.</p> <ol> <li>Is this possible at all? I don't see any parameter for Identity ...
<python><postgresql><sqlalchemy>
2023-02-01 15:31:40
1
1,563
qalis
75,312,508
1,468,810
Create a dataframe of combinations with an ID with pandas
<p>I'm running into a wall in terms of how to do this with Pandas. Given a dataframe (df1) with an ID column, and a separate dataframe (df2), how can I combine the two to make a third dataframe that preserves the ID column with all the possible combinations it could have?</p> <p>df1</p> <pre><code>ID name.x 1 a 2 ...
<python><pandas><dataframe>
2023-02-01 15:29:13
1
721
Benjamin
75,312,431
4,183,498
Python - test a function was called with context
<p>Say I have a context manager and a function which has to be called within this context.</p> <pre><code>with my_context_manager(): my_function() </code></pre> <p>Is it possible to test that <code>my_function</code> was called in the context of <code>my_context_manager</code>?</p>
<python><testing><contextmanager>
2023-02-01 15:23:36
0
10,009
Dušan Maďar
75,312,384
9,756,752
Using APscheduler with Textual in Python
<p>i need a scheduler in a Textual application to periodically query an external data source. As a test i've tried to use APscheduler to call a <code>tick()</code> function every second.</p> <p>However nothing happens although the scheduler should be started.</p> <p>What is going on and how to debug this?</p> <pre clas...
<python><rich>
2023-02-01 15:19:28
1
705
Marvin Noll
75,312,333
4,682,492
Truncated result when using Paramiko invoke_shell
<p>I am using Paramiko <code>invoke_shell</code> to pull results of the <code>top</code> command from a remote system. But I am getting truncated lines when looking at the results.</p> <p>Code as follows :</p> <pre><code>channel = token.invoke_shell() channel.send ('terminal length 0\n') time.sleep(1) resp = channel.r...
<python><ssh><paramiko>
2023-02-01 15:15:59
1
396
Dan G
75,312,320
4,958,693
How to create a model from a select query/CTE in peewee?
<p>Lets say I have a table called flights and I want an aggregation on it like:</p> <pre><code>SELECT plane, count(flightId) as num from flights; </code></pre> <p>And let´s say I don´t want to create a permanent View. Can I use an SQL Query or its results as the source for a Model?</p>
<python><peewee>
2023-02-01 15:14:41
1
373
Dennis Beier
75,312,141
11,092,636
Type-hinting problem with mypy when iterating through a list of arguments
<p>Here is a MRE:</p> <pre class="lang-py prettyprint-override"><code>def test(a: int | tuple[int, int]): print(a) if __name__ == &quot;__main__&quot;: for b in [1, (1, 2)]: test(b) </code></pre> <p>mypy outputs: <code>7: error: Argument 1 to &quot;test&quot; has incompatible type &quot;object&quot;; ...
<python><mypy>
2023-02-01 15:01:30
1
720
FluidMechanics Potential Flows
75,312,036
954,698
imageio get_data skips frames
<p>For a viewer, I am trying to randomly access frame in an mp4 file. Unfortunately, depending on where I start off, I am getting different frames from the same index, in my case for any frame after frame 123:</p> <pre><code>import imageio import hashlib from tqdm import tqdm reader = imageio.get_reader(&quot;360_0011...
<python><video><mp4><python-imageio>
2023-02-01 14:53:43
0
356
mcandril
75,311,843
7,800,760
Python poetry: adding the --allow-prereleases flag to an already installed package
<p>By mistake I added <strong>black</strong> to my poetry environment along with all other dependencies without the <strong>--allow-prereleases</strong> flag.</p> <p>If I try to do it now I get:</p> <pre><code>(rssita-py3.10) (base) bob@Roberts-Mac-mini rssita % poetry add --group dev black --allow-prereleases** The fo...
<python><python-poetry>
2023-02-01 14:39:52
1
1,231
Robert Alexander
75,311,760
11,267,783
Matplotlib performance on pan
<p>I working on a PyQt GUI in order to plot 2D/3D data. Matplotlib is very interesting concerning all its available features. However, Matplotlib seems to not be relevant when you have huge amount of data (for instance 10000x10000). I found that maybe GTKAgg backend is really efficient for this issue, but not really.</...
<python><matplotlib>
2023-02-01 14:33:16
0
322
Mo0nKizz
75,311,712
9,950,503
Extract json data from an array in PySpark
<p>I am trying to flatten and extract only one value (time) from the JSON file and its array (records), and store it in the new column (date). Then I want to get the max date from that column. However, it seems like I can only get the time value from the first batch of the records array, but not all the other records a...
<python><json><apache-spark><pyspark>
2023-02-01 14:28:59
0
341
saraherceg
75,311,496
10,689,857
Pip freeze separate test vs non test
<p>I have a python project for which I want to create:</p> <ul> <li>requirements.txt -&gt; with the modules needed for running the code but not the tests.</li> <li>requirements_dev.txt -&gt; with just the extra modules needed for the tests.</li> </ul> <p>I will reuse those in the install_requires and extras_require fie...
<python>
2023-02-01 14:13:17
0
854
Javi Torre
75,311,480
13,361,176
argparse - two optional arguments must be provided both or none
<p>I am writing a script that accepts multiple arguments, some are optional but should be provided together, how can I achieve this behaviour?</p> <p>Ex: arg1 is a required argument</p> <p>opt-arg-1 and opt-arg-2 should be provided together or none at all</p> <pre><code>python my_script.py --arg1 val1 # Works fine pyth...
<python><arguments><argparse>
2023-02-01 14:12:11
0
560
arnino
75,311,368
544,542
Python: removing black pixels from an image where the text to be extracted is black
<p>I have the following code to extract text from an image</p> <pre class="lang-py prettyprint-override"><code>img = cv2.imread('download.jpg') text = pytesseract.image_to_string(img, lang='lets', config='--psm 6 ') solution = re.sub('[^0-9]','', text) </code></pre> <p>However using an image like below where it says <c...
<python><python-3.x><tesseract><python-tesseract>
2023-02-01 14:04:25
1
3,797
pee2pee
75,311,365
5,680,504
How to get column index which is matching with specific value in Pandas?
<p>I have the following dataframe as below.</p> <pre><code> 0 1 2 3 4 5 6 7 True False False False False False False False [1 rows * 8 columns] </code></pre> <p>As you can see, there is one <code>True</code> value which is the first column.</p> <p>Therefore, I want ...
<python><pandas>
2023-02-01 14:04:12
6
1,329
sclee1
75,311,342
3,047,977
Why does this Python Try not catch an exception when the return value is assigned to a variable?
<p>I've got a try block like so:</p> <pre><code>try: result = api.call_to_api(arg1, ar2) except: ValueError </code></pre> <p>Which gets called via a unit test where api.call_to_api() is patched as following:</p> <pre><code>@patch('api.call_to_api') def myTest(self, mock): mock.side_effect = [DEFAULT, ValueError]...
<python><unit-testing><mocking><try-catch>
2023-02-01 14:02:53
1
316
Brad B.
75,311,321
3,801,865
AWS Lambda function can't connect to and query SQLite DB file from S3
<p>My goal is to upload a SQLite database file to AWS S3, use AWS Lambda &amp; python (<code>sqlite3</code>) to connect to the database, query it, and return some of its data.</p> <p>Having uploaded the database file to S3, I wrote a python script (which is to become the Lambda function) that <em>successfully</em> down...
<python><sqlite><amazon-s3><aws-lambda>
2023-02-01 14:01:47
1
1,022
Josh Clark
75,311,210
7,714,681
ImportError: cannot import name 'prod' from 'math' (unknown location)
<p>When I try to run</p> <p>either :</p> <pre><code>from math import prod </code></pre> <p>or:</p> <pre><code>import math arr = (1,2,3) math.prod(arr) </code></pre> <p>I get the following error message:</p> <pre><code>ImportError: cannot import name 'prod' from 'math' (unknown location) </code></pre> <p>or:</p> <pre><c...
<python><math><importerror>
2023-02-01 13:53:04
0
1,752
Emil
75,311,138
4,458,718
cdk SageMaker.CfnModel outputs empty containers property when passed model package arn
<p>When I try to pass a model package to cdk CfnModel the template output has an empty dictionary. Then input checks require an array of objects, however whatever I pass does not end up in the template output. What is the issue here?</p> <p>Given the input below, I am expecting an output with the containers property se...
<python><amazon-web-services><aws-cdk><amazon-sagemaker>
2023-02-01 13:47:51
1
1,931
L Xandor
75,311,131
11,177,720
Why is yield "blocking" all other functionality?
<p>I decided to finally learn <code>yield</code> to make generators and came across this weird thing:</p> <p>If I run this code, it prints out <code>&lt;generator ...&gt;</code>. It doesn't print <code>num</code> or stop execution at <code>3.1</code>...</p> <p>If I remove the for-yield lines, then it works correctly.</...
<python><python-3.x><yield>
2023-02-01 13:47:13
0
1,865
12944qwerty
75,311,099
5,553,962
"EOFError: Ran out of input" when packaging a Python script with PyInstaller
<p>I'm developing an application for Windows operating systems written in Python 3.8 and which makes use of the nnunet library (<a href="https://pypi.org/project/nnunet/" rel="nofollow noreferrer">https://pypi.org/project/nnunet/</a>) which uses multiprocessing. I have tested the script and it works correctly.</p> <p>N...
<python><python-3.x><multiprocessing><pyinstaller><eoferror>
2023-02-01 13:44:51
0
729
El_Merendero
75,311,057
12,248,220
1D histogram from 4 column txt dataset in python?
<p>I have a text file with 4 columns, the first 3 are the x, y and z coordinates of one datapoint, and the 4th column is the value of the datapoint at that x, y, z set of coordinates.</p> <p>For example:</p> <pre><code>0 1 2 10000 0 1 3 20000 0 2 1 30000 1 0 0 40000 1 1 1 50000 </code></pre> <p>I want to make a plot ha...
<python><arrays><numpy><data-science><histogram>
2023-02-01 13:41:15
1
576
velenos14
75,311,034
5,114,342
Bokeh Server not finding images
<p>I'm trying to achieve the seemingly simple thing of showing a picture in a Bokeh Server.<br /> [It works just fine for me when I do this in a Jupyter Notebook, by the way.]</p> <p>My file layout is</p> <pre><code>logo.png server_folder/ main.py logo.png static/ logo.png </code></pre> <p>With ...
<python><bokeh>
2023-02-01 13:39:59
1
3,912
Aziuth
75,311,023
3,575,623
Print rows of df as columns
<p>I have a data frame that looks like this:</p> <pre><code>category ID values A foo ABCDEF A baz GHIJKL B bar MNOPQR B biff STUVWX C bop YZABCD </code></pre> <p>All of the <code>values</code> are the same length.</p> <p>I'd like to print the <code>ID</code> and <co...
<python><pandas>
2023-02-01 13:39:00
7
507
Whitehot
75,310,934
6,027,879
python iterate yaml and filter result
<p>I have this yaml file</p> <pre><code>data: - name: acme_aws1 source: aws path: acme/acme_aws1.zip - name: acme_gke1 source: gke path: acme/acme_gke1.zip - name: acme_oci source: oci path: acme/acme_oci1.zip - name: acme_aws2 source: aws path: acme/acme_aws2.zip - name: acme_...
<python><yaml><pyyaml>
2023-02-01 13:31:16
2
406
hare krshn
75,310,911
403,425
Can Django's URL tag show the URL of the RedirectView
<p>Let's say that in my urls.py I have a url like this:</p> <pre><code>path(&quot;support/&quot;, RedirectView.as_view(url=&quot;http://www.example.com&quot;), name=&quot;support&quot;), </code></pre> <p>And in one of my templates I use the url tag:</p> <pre><code>{% url &quot;support&quot; %} </code></pre> <p>This of ...
<python><django><http-redirect><django-views><django-urls>
2023-02-01 13:30:04
1
5,828
Kevin Renskers
75,310,835
11,829,398
Can you modify an object's field every time another field is modified?
<p>I have a dataclass that looks like this</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, field @dataclass class Data: name: str | None = None file_friendly_name: str | None = field(default=None, init=False) def __post_init__(self): # If name, automatically ...
<python><python-dataclasses><python-class>
2023-02-01 13:23:40
3
1,438
codeananda
75,310,791
19,580,067
Extract the values, if the part of string in one column matches with part of string in another column
<p>I have 2 data frames with 2 columns in each table. Now, I need to match the values of col A from <strong>df1</strong> with the col C of <strong>df2</strong> and get only the matched values.</p> <p>For example:</p> <p><strong>df1</strong></p> <pre><code> A B ABC PVT Ltd 1FWE23 Auxil Solut...
<python><string><dataframe><lambda>
2023-02-01 13:20:16
1
359
Pravin
75,310,708
11,558,143
how to accelerate the numpy for-loop, for coloring point-cloud by its intensity
<p>enter code hereI want to color a point-cloud by its intensity.</p> <p>currently I use the following for-loop to apply <a href="https://stackoverflow.com/questions/20792445/calculate-rgb-value-for-a-range-of-values-to-create-heat-map">a colormap function</a> to the intensity(4th-dim) of points:</p> <pre><code>import ...
<python><numpy><colors><open3d>
2023-02-01 13:13:43
1
1,462
zheyuanWang
75,310,668
10,693,596
PyScript: is it possible to execute an uploaded Python script?
<p>Is it possible to have a user upload an arbitrary Python script (that uses built-ins only, no external packages) and then execute it using PyScript?</p>
<python><pyscript>
2023-02-01 13:10:40
1
16,692
SultanOrazbayev
75,310,650
16,813,096
How to get font path from font name [python]?
<p>My aim is to get the font path from their common font name and then use them with <code>PIL.ImageFont</code>.</p> <p>I got the names of all installed fonts by using <code>tkinter.font.families()</code>, but I want to get the full path of each font so that I can use them with <code>PIL.ImageFont</code>. Is there any ...
<python><python-3.x><tkinter><python-imaging-library>
2023-02-01 13:09:09
2
582
Akascape
75,310,636
4,331,885
Poetry Install crashes because excluded dependency cannot be found
<p>One of our repositories relies on another first-party one. Because we're in the middle of a migration from (a privately hosted) gitlab to azure, some of our dependencies aren't available in gitlab, which is where the problem comes up.</p> <p>Our pyproject.toml file has this <a href="https://python-poetry.org/docs/1....
<python><python-3.x><gitlab><gitlab-ci><python-poetry>
2023-02-01 13:08:00
1
1,438
Gloweye
75,310,578
1,990,524
Pandas Pivot Table, How to create new variables
<p>I am working with pandas in python.</p> <p>I have the following data frame:</p> <pre><code>ID | Time | X_mean | Y_mean | status 1 1 0.1 0.6 0 1 2 0.2 0.7 0 1 3 0.3 0.8 0 2 1 0.6 0.3 1 2 2 0.2 0.5 1 2 3 0.3 0....
<python><pandas><dataframe>
2023-02-01 13:02:32
2
1,709
jjuser19jj
75,310,547
4,495,790
Conditional binary replacement in Pandas column with NaNs
<p>I have the following Pandas data frame in Python:</p> <pre><code>col1 ---- A B NaN A A NaN NaN B C </code></pre> <p>I would like to replace the values so that all <code>A</code> remain <code>A</code>, all other values (<code>B, C</code> in this example) are replaced with <code>D</code>, and <code>NaN</code> remain u...
<python><pandas>
2023-02-01 12:59:53
2
459
Fredrik
75,310,472
6,224,790
Can't satisfy Django configuration for AUTH_USER_MODEL setting
<p>I use Django Rest Framework and have a AbstractUser that I have inherited to create my user :</p> <p>file : Project/NovalixExpedition/models/NovalixUserModel</p> <pre class="lang-py prettyprint-override"><code>from NovalixBackend.models.AddressModel import Address from NovalixBackend.models.RoleModel import Role fro...
<python><django-models><django-rest-framework><django-authentication><django-apps>
2023-02-01 12:53:19
2
373
Pazka
75,310,448
9,552,161
Why does np.split create a copy when passing into an existing array?
<p>I am new to Python and trying to understand the behaviour of views and copies, so apologies if this is an obvious question! In the example below, I use <code>np.split()</code> to split an array <code>x</code>. When I pass np.split into a new object (either <code>x1</code>, a list of 3 1D arrays or <code>x2, x3, x4</...
<python><numpy>
2023-02-01 12:50:30
2
321
Lucy Wheeler
75,310,340
19,290,081
How do round decimals when writing dataframe in streamlit
<pre class="lang-py prettyprint-override"><code>import streamlit as st import pandas as pd data = {'Days': [&quot;Sunday&quot;, &quot;Wednesday&quot;, &quot;Friday&quot;], 'Predictions': [433.11, 97.9, 153.65]} df = pd.DataFrame(data) st.write(df) </code></pre> <p>streamlit writes dataframe with four decimals...
<python><pandas><dataframe><streamlit>
2023-02-01 12:41:13
1
5,771
Jamiu S.
75,310,294
7,800,760
Github Actions: poetry installs black but CI workflow does not find it
<p>I am setting up a python code quality workflow locally (pre-commit) and on Github Actions (GHA). Environment is managed with poetry.</p> <p>While the local precommit works fine, the remote GHA workflow fails, saying it does not find black, while looking at the workflow logs it seems it was installed just fine. Workf...
<python><continuous-integration><github-actions><python-poetry>
2023-02-01 12:37:26
1
1,231
Robert Alexander
75,310,213
1,472,474
Making certain matches impossible in assignment problem (Hungarian algorithm)
<h3>Motivation:</h3> <p>I'm using scipy's python implementation of hungarian algorithm (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html#scipy-optimize-linear-sum-assignment" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.optim...
<python><scipy><hungarian-algorithm><assignment-problem>
2023-02-01 12:29:33
0
5,587
Jan Spurny
75,310,173
5,784,323
AttributeError: 'OptionEngine' object has no attribute 'execute'
<p>SQLAlchemy v2.0.0 works in a different way - they have changed some of the api.</p> <p>Following investigation I found a solution. My code was simply:</p> <pre><code>s_settings_df = pd.read_sql_query(query, engine_cloud) </code></pre> <p>The error like the title, &quot;AttributeError: 'OptionEngine' object has no at...
<python><pandas><sqlalchemy>
2023-02-01 12:26:39
1
1,421
NAJ
75,310,169
7,209,497
Problem during Download of pdf file using Python
<p>From <a href="https://research.un.org/en/docs/ga/quick/regular/76" rel="nofollow noreferrer">https://research.un.org/en/docs/ga/quick/regular/76</a> I intend to download the first resolution (A/RES/76/307), which has the link (<a href="https://undocs.org/en/A/RES/76/307" rel="nofollow noreferrer">https://undocs.org/...
<python><pdf><download>
2023-02-01 12:26:29
2
314
Jan
75,310,143
1,901,071
Polars Adding Days to a date
<p>I am using Polars in Python to try and add thirty days to a date I run the code, get no errors but also get no new dates Can anyone see my mistake?</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( {&quot;start_date&quot;: [&quot;2020-01-02&quot;, &quot;2020-01-03&quot;,...
<python><datetime><duration><timedelta><python-polars>
2023-02-01 12:24:19
1
2,946
John Smith
75,310,122
6,218,173
NameError, name is not defined
<p>I wrote a simple code to check if a list is sorted or not. I have two questions: First, my result is wrong. I guess the issue is with following the line. Which one is correct?:</p> <pre><code>sorted_list = mylist[:].sort() sorted_list = list(mylist[:]).sort() </code></pre> <p>As second question, when I try to print(...
<python><python-3.x><list><nameerror>
2023-02-01 12:22:45
1
491
Majid
75,310,082
3,335,108
Accessing Exchange inbox using exchangelib from Python with oauth
<p>Since Microsoft has now dropped support for accessing an Exchange mailbox using basic authentication, I've had to upgrade some code to use oauth based access to the mailbox instead.</p> <p>I've setup an Azure AD app following these docs:</p> <ul> <li><a href="https://learn.microsoft.com/en-us/exchange/client-develop...
<python><oauth><smtp><exchangewebservices><exchangelib>
2023-02-01 12:18:07
2
380
Benjamin Gorman
75,310,047
5,881,804
python multithreading: how to ensure a thread is waiting and not currently joining?
<p>I have a thread A which permanently listens for events. When an event for a particular resource R1 arrives, it starts thread B and passes the job to B for processing. Thread A then continues to listen, while B waits for a job, receives the job from thread A and processes it. Additional events for resources R1 are al...
<python><multithreading><python-multithreading>
2023-02-01 12:15:25
2
732
Blindfreddy
75,309,924
1,417,053
Python Pathlib Strange Behaviour
<p>I can find all the files in the subfolders of a folder path with specific filetypes in this way:</p> <pre><code>list(Path(folder_path).glob('**/*.[jpg][jpeg][png]*')) </code></pre> <p>But if I change the code to try and find other filetypes (like <code>jfif</code> or <code>bmp</code>), with some filetypes the code w...
<python><glob><pathlib>
2023-02-01 12:04:48
2
2,620
Cypher
75,309,711
13,019,353
Calling python script from bash script and getting it's return value
<p>I've bash script doing some tasks but I need to manipulate on string obtained from configuration (for simplification in this test it's hardcoded). This manipulation can be done easily in python but is not simple in bash, so I've written a script in python doing this tasks and returning a string (or ideally an array ...
<python><bash>
2023-02-01 11:46:20
2
377
Aenye_Cerbin
75,309,660
3,812,928
Python: why is mock not called in this instance of loop?
<p>I have the following test code:</p> <pre class="lang-py prettyprint-override"><code>@pytest.mark.parametrize( &quot;any_recordings,any_transcriptions,returns_recording,duration,exception&quot;, [ ( True, True, True, 60, None ), ...
<python><unit-testing>
2023-02-01 11:41:37
1
665
NotoriousPyro
75,309,589
186,202
Django Admin - How to prefill add inline forms values sent through the querystring?
<p>I am able to prefill a form using query-string parameters in Django Admin.</p> <p>Let's say I have the following models:</p> <pre class="lang-py prettyprint-override"><code>class Book(models.Model): id = models.Autofield(primary_key=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) name ...
<python><django><django-admin><inline-formset>
2023-02-01 11:35:25
1
18,222
Natim
75,309,530
11,629,296
Python : Replace two for loops with the fastest way to sum the elements
<p>I have list of 5 elements which could be 50000, now I want to sum all the combinations from the same list and create a dataframe from the results, so I am writing following code,</p> <pre><code>x =list(range(1,5)) t=[] for i in x: for j in x: t.append((i,j,i+j)) df=pd.Dataframe(t) </code></pre> <p>The ...
<python><pandas><dataframe><for-loop><python-itertools>
2023-02-01 11:29:51
2
2,189
Kallol
75,309,443
7,541,421
Curve fitting with three unknowns Python
<p>I have a data set where from one <em>x</em> I can obtain the exponential function <code>f(x) = a*np.exp(-b*(x-c))</code> , defined in Python like this:</p> <pre><code>def func(x, a, b, c): return a*np.exp(-b*(x-c)) f = func(x, a, b, c) a = 1.6 b = 0.02 </code></pre> <p><em>a</em>, <em>b</em>, <em>c</em> are a...
<python><scipy><curve-fitting>
2023-02-01 11:22:10
1
788
PEBKAC
75,309,422
357,313
Slice MultiIndex by multiple tuples
<p>I have a DataFrame with multiple index levels. I define some subset by selecting multiple combinations of all levels but the last. Then I want to slice the original DataFrame with that subset, but I cannot find how. Best is to look at a simple example:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.Data...
<python><pandas><slice><multi-index>
2023-02-01 11:20:44
1
8,135
Michel de Ruiter
75,309,417
902,485
The distribution of p-values is not uniform when applying t-test to random coin flips from Python's random.randint(0,1)
<p>Theoretically, p-values <a href="https://stats.stackexchange.com/questions/10613/why-are-p-values-uniformly-distributed-under-the-null-hypothesis">are uniformly distributed under the null hypothesis</a>.</p> <p>Therefore, I would expect p-values from G-test or Chi-square test to test equal proportions to provide uni...
<python><random><statistics><p-value><bernoulli-probability>
2023-02-01 11:19:59
2
841
Niek Tax
75,309,406
20,646,427
How to connect 2 many to many fields in Django
<p>I have 2 many to many fields in models and i want to connect them to each other i mean if i connect user in Admin Model with Counter Party i cant see that in Counter Party admin</p> <p>How can i do that?</p> <p>When im trying to do that it shows only in 1 model</p> <p>models.py</p> <pre><code>class CustomUser(models...
<python><django>
2023-02-01 11:18:34
1
524
Zesshi
75,309,351
15,724,084
python tkinter cannot assign stringvar() set
<p>I wanted to create module based tkinter classes. I want to be able <code>var_text</code> variable to be able to print on <code>Label</code> text given to it.</p> <pre><code>from tkinter import * class Maincl(Tk): def __init__(self,xwidth,yheight): super().__init__() self.geometry(f'{xwidth}x{yhe...
<python><tkinter>
2023-02-01 11:13:43
2
741
xlmaster
75,309,237
21,124,805
read_sql_query() throws "'OptionEngine' object has no attribute 'execute'" with SQLAlchemy 2.0.0
<p>First of all, I'm a totally new guys in the dev world I'm currently taking courses in AI / Data Science and one of my work is to use a SQL Database to make prediction using Prophet, then use these predition to make a PowerBI But currently, I'm stuck with the Python code, I'm not a developer initially, so I have no c...
<python><pandas><sqlalchemy>
2023-02-01 11:02:34
8
541
Elu
75,309,138
8,849,071
Why mypy is not throwing an error if interface and implementation has a different argument name
<p>I have discovered today this bug in our code base (simplified example):</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod class Interface(ABC): @abstractmethod def method(self, variable: str) -&gt; str: pass class Implementation(Interface): def method(sel...
<python><mypy><python-typing>
2023-02-01 10:54:18
1
2,163
Antonio Gamiz Delgado
75,309,052
14,824,108
Calculating pairwise distances between entries in a `torch.tensor`
<p>I'm trying to implement a manifold alignment type of loss illustrated <a href="https://towardsdatascience.com/manifold-alignment-c67fc3fc1a1c" rel="nofollow noreferrer">here</a>.</p> <p>Given a tensor representing a batch of embeddings of shape <code>(L,N)</code> for example with L=256:</p> <pre><code>tensor([[ 0.01...
<python><machine-learning><pytorch><pairwise-distance>
2023-02-01 10:47:38
1
676
James Arten
75,308,996
1,096,660
How to prevent multiple queries by inlines in Django admin?
<p>I fought with this all day yesterday, but can't really find a way out. I've got three models where A is related to C through B. The A-admin inlines B which has the FK to C.</p> <p>The admin inlines are causing queries per item which is incredibly slow. Making the offending fields raw_id_only does help (readonly even...
<python><django><django-admin><python-3.8><django-database>
2023-02-01 10:43:04
0
2,629
JasonTS
75,308,944
1,901,071
Polars Case Statement
<p>I am trying to pick up the package <a href="https://www.pola.rs/" rel="nofollow noreferrer">polars</a> from Python. I come from an R background so appreciate this might be an incredibly easy question.</p> <p>I want to implement a case statement where if any of the conditions below are true, it will flag it to 1 othe...
<python><dataframe><python-polars>
2023-02-01 10:38:37
1
2,946
John Smith
75,308,928
4,865,723
Create a MultiIndex with set_index() transforms 0 and 1 into booleans
<p>I do use <code>DataFrame.set_index()</code> to transform two columns into a <code>MultiIndex</code>. The problem is that values with <code>0</code> and <code>1</code> are transformed into booleans <code>False</code> and <code>True</code>.</p> <p>This is the initial table. Please see the values in <code>idx2</code>.<...
<python><pandas>
2023-02-01 10:37:03
2
12,450
buhtz
75,308,894
262,667
How to type hint a method that returns a subclass?
<p>I have the setup</p> <pre class="lang-py prettyprint-override"><code>import typing class A: def get_b(self) -&gt; B: # &lt;- ERROR: B is not defined yet return b # &lt;- and instance of B here class B(A): # &lt;- subclass of A, defined after A is defined pass </code></pre> <p>Is there a clean way t...
<python><oop><python-typing>
2023-02-01 10:34:50
1
49,544
Olivier Verdier
75,308,879
10,590,609
How can I pass setup-code and processing-code to another process?
<p>I have a generic multiprocessing worker class that takes items from a queue to be processed. A user of the worker class would need to pass a function that processes each item. However, some processing functions need setup-code.</p> <p>The current implementation uses a generator function that has to be correctly impl...
<python><multithreading><multiprocessing>
2023-02-01 10:33:34
1
332
Izaak Cornelis
75,308,818
2,876,079
Pandas to_sql ignores foreign key constrains when appending to sqlite table?
<p>I use the pandas method <code>to_sql</code> to append a DataFrame to some sqlite table. The sqlite table has a foreign key constraints on a column <code>id_region</code> that pandas should consider. The available values for <code>id_region</code> are 1, 2.</p> <p>If the DataFrame contains a non-existing <code>id_re...
<python><pandas><sqlite><foreign-keys>
2023-02-01 10:29:01
1
12,756
Stefan
75,308,553
6,672,815
Implementing decorators in terms of closures with pyo3
<p>As a learning exercise I'm trying to implement a parameterised decorator function in pyo3 using closures. The pyo3 documentation contains an example of a (non-parameterised) decorator implemented as a class with a <code>__call__</code> method, and I've built on this and created a parameterised decorator using an out...
<python><rust><decorator><pyo3>
2023-02-01 10:10:24
2
830
virgesmith
75,308,496
10,134,422
How do I run uvicorn in a docker container that exposes the port?
<p>I am developing a fastapi inside a docker container in windows/ubuntu (code below). When I test the app outside the container by running <em>python -m uvicorn app:app --reload</em> in the terminal and then navigating to <em>127.0.0.1:8000/home</em> everything works fine:</p> <pre><code>{ Data: &quot;Test&quot; } <...
<python><docker><fastapi><uvicorn>
2023-02-01 10:07:00
1
460
Sanchez333
75,308,373
275,195
How do I keep the first entry from consecutive entries in a DataFrame?
<p>With the following DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import random random.seed(3) df = pd.DataFrame( data=[random.sample([&quot;A&quot;,&quot;B&quot;],1) for i in range(6)], columns=[&quot;category&quot;] ) </code></pre> <p>We get:</p> <p><a href="https://i.sstat...
<python><pandas><dataframe><group-by>
2023-02-01 09:56:37
1
2,338
Pascal
75,308,316
7,012,917
Pandas DataFrame.corr() doesn't give same results as Series.corr()
<p>I have two timeseries</p> <pre><code>jpm = pd.read_csv(...) # JPM GBI Global All Traded msci = pd.read_csv(...) # MSCI WORLD U$ </code></pre> <p>Together in a DataFrame they look like</p> <pre><code>df = jpm.merge(msci, how='outer', on='Date', sort=True) df </code></pre> <div class="s-table-container"> <table class...
<python><pandas><dataframe>
2023-02-01 09:51:10
1
1,080
Nermin
75,308,311
6,054,404
Getting the shortest path geometry using python networkx
<p>How do I get the path as a geometry from networkx?</p> <p>Below is my worked example which returns the <code>nx.shortest_path_length</code></p> <pre><code>import osmnx as ox import networkx as nx from shapely.geometry import Point def get_network(centre_point, dist): G = ox.graph_from_point(centre_point, dist=d...
<python><networkx><geopandas>
2023-02-01 09:50:47
1
1,993
Spatial Digger
75,308,263
4,614,499
Prevent Custom Renderer to render Exceptions in Django Rest Framework
<p>I have written a custom Renderer that allows rendering nested json data as flat Excel files.</p> <pre><code>class ExcelRenderer(renderers.BaseRenderer): &quot;&quot;&quot;Custom renderer for exporting XLS files&quot;&quot;&quot; media_type = &quot;application/xlsx&quot; format = &quot;excel&quot; r...
<python><excel><pandas><django-rest-framework><renderer>
2023-02-01 09:47:03
1
2,879
Marjan Moderc
75,308,137
10,545,426
Serialize and Deserialize a custom tensorflow model which can be loaded back to a python object
<p>I have a requirement of saving my custom tensorflow model which has a mix of python objects and tf tensors included within. I want something that can help serialize this custom tensorflow python class. Something like <code>pickle.dumps(custom_tf_python_class)</code> so that I can just load it like <code>custom_tf_py...
<python><tensorflow><pickle>
2023-02-01 09:36:21
0
399
Stalin Thomas
75,307,956
14,649,310
Can the GNU gettext module in Python fetch translations from cloud or from another container?
<p>This is more of an structural architectural question. I am using Python <a href="https://phrase.com/blog/posts/translate-python-gnu-gettext/" rel="nofollow noreferrer">gettext module</a> to fetch translations. But the way it works, as described in the link as well, the translations have to be in the same repo and po...
<python><docker><localization><gettext>
2023-02-01 09:21:04
1
4,999
KZiovas
75,307,944
3,923,078
Force data relocation between workers on Dask?
<p>I am working with Dask Arrays. The data is read from parquet files as Dask DataFrame and I need to transform the data into column-wise arrays to accelerate certain computation. However, after rechunking, the data is located in a single worker and not able to scale to the entire cluster.</p> <p>I read from other <a h...
<python><dask>
2023-02-01 09:19:58
0
597
Fontaine007
75,307,905
6,854,595
Python typing for a metaclass Singleton
<p>I have a Python (3.8) metaclass for a singleton as seen <a href="https://stackoverflow.com/a/6798042/6854595">here</a></p> <p>I've tried to add typings like so:</p> <pre class="lang-py prettyprint-override"><code>from typing import Dict, Any, TypeVar, Type _T = TypeVar(&quot;_T&quot;, bound=&quot;Singleton&quot;) ...
<python><mypy><python-typing><metaclass>
2023-02-01 09:16:30
2
540
alexcs
75,307,868
10,967,961
Multiprocessing uses python 2.7 even if I am in a python 3 env
<p>I am trying to run a code (confronting pairwise strings in a dict basically) using concurrent.futures. The code looks as follows (where masterprova is a dict of 100 elements):</p> <pre><code>import concurrent.futures from collections import defaultdict from itertools import combinations #import fuzz def process_chu...
<python><python-3.x><python-2.7><multiprocessing>
2023-02-01 09:14:06
0
653
Lusian
75,307,857
19,950,360
I want to make cloud run log when come to input
<p>when i receive input like url Then want to logging in cloud run</p> <p>I want to see my input with python</p>
<python><google-cloud-platform><google-cloud-run>
2023-02-01 09:13:27
1
315
lima
75,307,814
5,684,405
Error: Python packaging tool 'setuptools' not found
<p>I have a poetry project that is not using setuptools</p> <pre><code>[tool.poetry.dependencies] python = &quot;&gt;=3.9,&lt;3.11&quot; opencv-python = &quot;^4.7.0.68&quot; tensorflow-macos = &quot;^2.11.0&quot; tensorflow-metal = &quot;^0.7.0&quot; </code></pre> <p>but I keep getting this error in pycharm. Command f...
<python><pycharm><setuptools><python-poetry>
2023-02-01 09:09:21
4
2,969
mCs
75,307,709
18,744,117
Uvicorn + Quart yielding error 413 on post request
<p>I'm trying to setup a simple http server to receive ( potentially large ) JSON objects.</p> <pre><code>from quart import Quart, request import uvicorn app = Quart(__name__) @app.route( '/' , methods=[ 'POST' ] ) async def hello(): json = await request.json return ('',204) config = uvicorn.Config( app, ho...
<python><httpserver><uvicorn><quart><http-status-code-413>
2023-02-01 08:59:42
1
683
Sam Coutteau
75,307,652
13,762,083
Attribute error when trying to import scipy.interpolate
<p>I am trying to import <code>scipy.interpolate</code> using the following code:</p> <pre><code>from scipy.interpolate import interp1d </code></pre> <p>but I get the following error:</p> <pre><code>AttributeError: scipy.spatial.qhull is deprecated and has no attribute __pyx_capi__. Try looking in scipy.spatial instead...
<python><scipy><python-import>
2023-02-01 08:54:31
0
409
ranky123
75,307,639
8,124,392
Autoencoder outputs pixelated colorful predictions
<p>I am working on an autoencoder to remove motion blur from images. I am using a small dataset of 1816 blurry and 1816 sharp images.</p> <p>This is my autoencoder with 6 layers:</p> <pre><code>physical_devices = tf.config.list_physical_devices('GPU') if physical_devices: tf.config.experimental.set_memory_growth(phy...
<python><tensorflow><machine-learning><computer-vision><autoencoder>
2023-02-01 08:53:33
0
3,203
mchd
75,307,597
10,062,025
Response cannot post in python Requests
<p>I am trying to scrape all items from this website: <a href="https://www.sayurbox.com/category/vegetables-1-a0d03d59/sub-category/all" rel="nofollow noreferrer">https://www.sayurbox.com/category/vegetables-1-a0d03d59/sub-category/all</a></p> <p>Here's my code</p> <pre><code>#get all libraries import requests import...
<python><python-requests>
2023-02-01 08:50:36
0
333
Hal
75,307,544
2,277,833
Performing an assertion in a test written with pytest that should not have occurred
<p>Below is the full test code where each assertion is executed. This is unintuitive for me for one reason. If the value of the variable k is None then the function t throws an exception, and thus the code after calling t should not be executed and the exception should be caught by the context manager. However, this do...
<python><python-3.x><exception><pytest>
2023-02-01 08:46:22
2
364
Draqun
75,307,494
13,846,577
how to run the command "ps -eo pid,user,ppid,cmd,%mem,%cpu --sort=-%cpu | head" through python
<p>I want to run the command <code>ps -eo pid,user,ppid,cmd,%mem,%cpu --sort=-%cpu | head</code> to get the output through a python script.</p> <p>I tried making it with the subprocess library but i am not able to find the solution.</p>
<python><linux>
2023-02-01 08:40:54
1
509
Yasharth Dubey
75,307,473
3,172,556
How to read a SQLite database file using polars package in Python
<p>I want to read a SQLite database file (database.sqlite) using <code>polars</code> package. I tried following unsuccessfully:</p> <pre><code>import sqlite3 import polars as pl conn = sqlite3.connect('database.sqlite') df = pl.read_sql(&quot;SELECT * from table_name&quot;, conn) print(df) </code></pre> <p>Getting f...
<python><sqlite><python-polars>
2023-02-01 08:39:07
3
788
canon-ball
75,307,309
7,376,511
Subclass overriding attribute with subtype of parent's attribute
<pre class="lang-py prettyprint-override"><code>class B: pass class InheritsB1(B): pass class InheritsB2(B): pass class A: prop: list[B] class InheritsA1(A): prop: list[InheritsB1] class InheritsA2(A): prop: list[InheritsB2] </code></pre> <p>With this code mypy raises <code>Incompatibl...
<python><python-typing><mypy>
2023-02-01 08:23:12
1
797
Some Guy
75,306,929
952,257
Python groupby: Custom analysis of each group
<p>I have an excel file containing rank data. The columns are Id, date, and rank. I want to find the average time it takes to move from one rank to another. For this purpose, I want to group my dataframe by ID, then sort by time, and then for each pair of consecutive entries, calculate a triplet (rankA, rankB, timeDiff...
<python><group-by>
2023-02-01 07:39:53
2
1,069
Shaharg
75,306,914
16,950,492
How can I merge different Db Models into one?
<p>I have an old Django Project, which I started when I was a beginner. So far it worked but, due to some code refactoring I would like to do, I would like to change the original database models. Basically, I originally made many different models, each one for a user type.</p> <p>old models:</p> <pre><code>class Custom...
<python><django><django-models><django-inheritance>
2023-02-01 07:38:20
2
418
Giorgio Scarso
75,306,803
12,883,179
subset fail on np.meshgrid generated dataframe
<p>I generate a dataframe for lonlat like this</p> <pre><code>a=np.arange(89.7664, 89.7789, 1e-4) b=np.arange(20.6897, 20.7050, 1e-4) temp_arr=np.array(np.meshgrid(a, b)).T.reshape(-1, 2) np_df=pd.DataFrame(temp_arr, columns = ['lon','lat']) </code></pre> <p>and it create the dataframe I want</p> <p><a href="https://i....
<python><pandas><dataframe><numpy>
2023-02-01 07:24:16
1
492
d_frEak