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
78,711,482
4,162,811
pyinstaller won't package python-docx
<p><strong>Goal</strong> I want to package a simple python app (let's call it <em>wordy</em>), that creates a basic word document using the python-docx libary, into a <em><strong>single</strong></em> .exe file.</p> <p><strong>setup</strong> PyCharm project with poetry as the interpreter. python-docx installed after sel...
<python><pycharm><pyinstaller><docx><python-docx>
2024-07-05 12:31:11
1
349
woodduck
78,711,339
5,980,655
Set same scale in legend matplotlib
<p>I'm working with geospacial data and I have two pandas dataframes with two different regions, both have a column <code>geometry</code> with the (multi)polygons and a column <code>SCORE</code> with a value for each of the (multi)polygons I want to plot.</p> <p>For example, this is the plot for the provinces of Spain ...
<python><pandas><matplotlib><graphics><geopandas>
2024-07-05 11:57:18
2
1,035
Ale
78,711,242
11,082,866
merge columns with same name in pandas
<p>I have a dataframe which consists of a couple of columns with same name i.e.</p> <pre><code>items_group quanity items_group quanity KIT1259 0 KIT1260 0 KIT1261 0 KIT1151 1 KIT1198A 4 KIT1198D 5 KIT1243 ...
<python><pandas>
2024-07-05 11:37:06
2
2,506
Rahul Sharma
78,711,237
11,049,863
django.db.utils.DatabaseError: DPY-4027: no configuration directory to search for tnsnames.ora in my dockerized django application
<p>I am trying to connect my django application with an oracle database in vain.<br/> I added the TNS_ADMIN environment variable but the problem persists.<br/> Here is the content of my tnsnames.ora file:</p> <pre><code># tnsnames.ora Network Configuration File: C:\app\HP\product\21c\homes\OraDB21Home1\NETWORK\ADMIN\tn...
<python><django><oracle-database><docker>
2024-07-05 11:35:57
2
385
leauradmin
78,711,171
1,469,954
Get the most optimal combination of places from a list of places through graph algorithm
<p>We are having a networking situation where he have four nodes - say <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code>. The problem - <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code> are not fixed, but have a bunch of possibilities.</p> <p>Say <code>A</code> can have values <code>A1</...
<python><network-programming><graph><graph-theory>
2024-07-05 11:23:45
3
5,353
NedStarkOfWinterfell
78,711,030
5,221,078
How to use Params to set weight of optional property
<p>I want to use FactoryBoy to create some fake data with an optional property. I want to be able to override the probability that the property is <code>None</code>.</p>
<python><pytest><factory-boy>
2024-07-05 10:49:42
1
1,378
Greg Brown
78,710,901
10,855,529
Follow sort after a group_by in polars
<pre class="lang-py prettyprint-override"><code>import polars as pl # Sample data data = { 'Group': ['A', 'A', 'B', 'B', 'C', 'C'], 'Value': [10, 20, 15, 25, 5, 30], 'OtherColumn': [100, 200, 150, 250, 50, 300] } # Create DataFrame df = pl.DataFrame(data) # Group by 'Group' and sort within each group by ...
<python><group-by><python-polars>
2024-07-05 10:18:04
1
3,833
apostofes
78,710,691
3,367,091
Python object instance attribute not same as class, but still?
<p>This question is about the <code>id</code> method in Python and if a class method is the same instance for the class object itself and any object instances created from that class.</p> <p>Sample code:</p> <pre class="lang-py prettyprint-override"><code>class Person: def __init__(self, name: str) -&gt; None: ...
<python>
2024-07-05 09:30:14
0
2,890
jensa
78,710,643
14,739,428
werkzeug Local got unexpected value
<p>I may have a misunderstood with werkzeug.local</p> <p>Here is my simplified test code:</p> <pre><code>from flask import Flask, request from werkzeug.local import Local import threading app = Flask(__name__) local_data = Local() @app.route('/') def index(): if local_data.data: # I don't know why new r...
<python><gunicorn><werkzeug>
2024-07-05 09:16:16
0
301
william
78,710,603
10,548,486
CosmosDB with PyMongo replaces the array field in document with literal array filter subdocument
<p>I'm using the CosmosDB on Azure with MongoDbApi. In my Flask service I use pymongo. My collection consists of a documents similar to this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;file_name&quot;: &quot;foo&quot;, &quot;date&quot;: &quot;2024-05-07&quot;, &quot;count&quot;: 1, &q...
<python><mongodb><azure><azure-cosmosdb><pymongo>
2024-07-05 09:07:39
0
732
777moneymaker
78,710,457
9,032,335
List all available dataset-names contained in a hugginface datasets dataset
<p>I want to know which datasets are included in e.g. this collection of huggingface datasets: <a href="https://huggingface.co/datasets/autogluon/chronos_datasets" rel="nofollow noreferrer">https://huggingface.co/datasets/autogluon/chronos_datasets</a></p> <p>&quot;m4_daily&quot; and &quot;weatherbench_daily&quot; are ...
<python><huggingface-datasets>
2024-07-05 08:32:44
1
723
ivegotaquestion
78,710,413
6,631,639
plotly: AttributeError: 'NoneType' object has no attribute 'constructor'
<p>Using Plotly in Python I ran into the following, rather cryptic, error message, with a minimal reproducible example. The original plot was a lot more complex, as such it took me longer than I like to admit to debug this.</p> <pre class="lang-py prettyprint-override"><code>import plotly as px px.scatter(x=[1,2,3], y=...
<python><plotly>
2024-07-05 08:23:59
1
527
Wouter De Coster
78,710,347
759,352
PySpark join fields in JSON to a dataframe
<p>I am trying to pull out some fields from a JSONn string into a dataframe. I can achieve this by put each field in a dataframe then join all the dataframes like below. But is there some easier way to do this? Because this is just an simplified example and I have a lot more fields to extract in my project.</p> <pre><c...
<python><json><pyspark>
2024-07-05 08:05:24
1
1,757
thotwielder
78,710,310
13,903,626
I cannot import monsoon after installing Monsoon
<p>I try to install Monsoon and then use it in the script, but I cannot import this module after installing it.</p> <p>The Python version is 3.8.1; I also tried it in Python 3.11 and got the same issue.</p> <p>Install script:</p> <pre><code>pip install monsoon </code></pre> <p>Then</p> <pre><code>import monsoon.LVPM as...
<python><python-3.x><python-import>
2024-07-05 07:56:18
2
8,396
Vito Liu
78,710,295
569,711
Azure functions in Python - "Duplex option is required" error
<p>As part of my data engineering job, I inherited some Azure functions written in Python a while ago. I now have to update them to reflect changed credentials, but keep running into issues.</p> <p>When deploying, it fires off the below &quot;duplex option is required when sending a body&quot;.</p> <p><a href="https://...
<python><azure-functions>
2024-07-05 07:54:19
1
9,729
SchmitzIT
78,709,252
1,983,613
Recursive types in Python and difficulties inferring the type of `type(x)(...)`
<p>Trying to build recursive types to annotate a nested data structure, I hit the following.</p> <p>This code is correct according to mypy:</p> <pre><code>IntType = int | list[&quot;IntType&quot;] | tuple[&quot;IntType&quot;, ...] StrType = str | list[&quot;StrType&quot;] | tuple[&quot;StrType&quot;, ...] def int2str...
<python><mypy><python-typing>
2024-07-05 00:04:20
2
417
Winks
78,709,175
7,563,454
What is the most efficient way to detect when a moving 3D position entered a new area delimited by a fixed scale?
<p>Context: I have a CPU based raytracing engine written in Pygame, it works by having rays move 1 unit per loop in the direction of their velocity and detecting any voxel at that integer position. I recently added chunks to boost performance, voxels in each area are stored in a container of a fixed size which is read ...
<python><math><3d>
2024-07-04 23:08:12
0
1,161
MirceaKitsune
78,709,058
2,521,423
Subtracting pandas series from all elements of another pandas series with a common ID
<p>I have a pandas <code>series.groupby</code> objects, call it <code>data</code>. If I print out the elements, it looks like this:</p> <pre><code>&lt;pandas.core.groupby.generic.SeriesGroupBy object at ***&gt; (1, 0 397.44 1 12.72 2 422.40 Name: value, dtype: float64) (2, 3 398.88 4 6.4...
<python><pandas><dataframe><group-by>
2024-07-04 22:01:18
2
1,488
KBriggs
78,708,866
1,725,944
Is it possible to read metadata from a python model before creating an instance?
<p>I have python models which are created using a particular version of my module repository. As updates and changes are made to the repo, the models are not always backward compatible.</p> <p>I'm wondering if it's possible to store some sort of header info in the model which can be read before creating the Class inst...
<python><abc>
2024-07-04 20:42:42
0
481
P-Rod
78,708,817
1,072,352
Colab, Jax, and GPU: why does cell execution take 60 seconds when %%timeit says it only takes 70 ms?
<p>As the basis for a project on fractals, I'm trying to use GPU computation on Google Colab using the Jax library.</p> <p>I'm using <a href="https://gist.github.com/jpivarski/da343abd8024834ee8c5aaba691aafc7" rel="nofollow noreferrer">Mandelbrot on all accelerators</a> as a model, and I'm encountering a problem.</p> <...
<python><jupyter-notebook><google-colaboratory><jax>
2024-07-04 20:25:01
1
1,375
crazygringo
78,708,730
498,584
Django Nested Serializers witj Foreign Field
<p>I am trying to post this json request through postman</p> <pre><code>{ &quot;name&quot;:&quot;Someones order&quot;, &quot;date_due&quot;: &quot;2024-06-23T15:52:59Z&quot;, &quot;customer&quot;:3, &quot;orderItem&quot;:[{ &quot;item&quot;:1, &quot;count&quot;:1 }] } </code></pre> <...
<python><django><django-serializer>
2024-07-04 19:53:28
1
1,723
Evren Bingøl
78,708,667
15,452,898
Create subset and calculate sums in Python based on a condition
<p>I am currently doing some data manipulation procedures and have run into a problem of how to make subsets based on special conditions.</p> <p>My example (dataframe) is like this:</p> <pre><code>Name ID Debt DurationOfDelay CD A ID1 10 15 1 A ID1 15 30 ...
<python><pyspark><data-manipulation>
2024-07-04 19:25:38
0
333
lenpyspanacb
78,708,642
497,649
If multiple Python processes write data into InfluxDB, only parts are written
<p>I have multiple Python processes, running on a server (RPI5) by <code>cron</code>, which read data from web API's, and write it then into a common InfluxDB database - on the same bucket.</p> <p>However, some of the data is lost. The code to write into Influx is:</p> <pre><code>influxdb_client = InfluxDBClient(url=ur...
<python><cron><synchronous><influxdb-2><data-loss>
2024-07-04 19:18:18
1
640
lambruscoAcido
78,708,628
8,231,936
Iterate over divs to get tables using Selenium and Python
<p>I'm trying to get info from the following site, using python and selenium: <a href="https://conveniomarco.mercadopublico.cl/alimentos/marketplace/seller/profile/shop/797095-5800279" rel="nofollow noreferrer">https://conveniomarco.mercadopublico.cl/alimentos/marketplace/seller/profile/shop/797095-5800279</a></p> <p>I...
<python><pandas><selenium-webdriver><web-scraping>
2024-07-04 19:13:19
1
517
Cristian Avendaño
78,708,358
9,744,061
How to animate the title using FuncAnimation in Python?
<pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig = plt.figure() axis = plt.axes(xlim=(-4, 4), ylim=(-3, 3)) line, = axis.plot([], [],'r+', lw=2) plt.title('omega = {}') def init(): line.set_data([], []) return line, def animate(i): y = omega...
<python><animation><title>
2024-07-04 17:39:07
1
305
Ongky Denny Wijaya
78,708,244
1,115,833
pandas rolling mean and stacking previous values
<p>I have a pandas dataframe of shape (2000,1) and I would like to compute rolling means but also keep the previous values as a lagged variable.</p> <p>Assuming the Series:</p> <pre><code>1 2 3 4 5 6 7 8 9 10 </code></pre> <p>with a rolling window of 3, I would like:</p> <pre><code>1,2,3,mean(4,5,6) 4,5,6,mean(7,8,9) <...
<python><python-3.x><pandas>
2024-07-04 16:57:47
2
7,096
JohnJ
78,708,011
1,522,066
How to fully integrate QSystemTrayIcon with MacOS Sonoma Menu Bar?
<p>In Sonoma, the MacOS Menu Bar changes it's appearance automagically, depending on the Wallpaper, Accessibility Settings, and perhaps other events.</p> <p>The MacOS Sonoma menu bar can be black, white, or semi-transparent with the wallpaper color showing through. The OS seems to then pick whether the menu bar icon is...
<python><pyside6><macos-sonoma>
2024-07-04 15:50:54
1
552
Marcus
78,707,895
7,431,523
Type of iterator is Any in zip
<p>The following script:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Iterable, Iterator class A(Iterable): _list: list[int] def __init__(self, *args: int) -&gt; None: self._list = list(args) def __iter__(self) -&gt; Iterator[int]: return iter(self._lis...
<python><mypy><python-typing>
2024-07-04 15:20:24
2
650
hintze
78,707,674
2,249,312
More efficient iteration method
<p>I m looking for a better way of doing the following. The code below works but its very slow because I m working with a large dataset. I was trying to also use itertools but somehow I couldnt make it work. So here my very unpythonic starting point.</p> <p>Helper function:</p> <pre><code>def signalbin(x,y): if x &gt...
<python><pandas><python-itertools>
2024-07-04 14:31:29
1
1,816
nik
78,707,635
701,867
Connecting to Delta Lake hosted on MinIO from Dask
<p>I'm trying to connect to a DeltaLake table that is stored on MinIO rather than S3. I can do this directly with the <code>deltalake</code> Python package as follows:</p> <pre class="lang-py prettyprint-override"><code>storage_options = { &quot;AWS_ENDPOINT_URL&quot;: &quot;http://localhost:9000&quot;, &quot;A...
<python><dask><delta-lake><minio>
2024-07-04 14:23:23
1
1,258
James Baker
78,707,455
4,701,426
Trouble using the right module version installed in pipenv environment
<p>I'm trying to run some Python code in VS Code in an environment.</p> <ol> <li>Step one. Open cmd from the folder containing the environment, activate the environment, and run VS code <a href="https://i.sstatic.net/9nqdz6rK.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9nqdz6rK.jpg" alt="enter image ...
<python><python-3.x><numba><pipenv>
2024-07-04 13:46:04
1
2,151
Saeed
78,707,393
3,100,523
Customize populate_obj on Flask AppBuilder view
<p>Is there a way to override the population of an item from a form on edit and/or create on Flask AppBuilder?</p> <p>On Flask-Admin there is a method called <a href="https://flask-admin.readthedocs.io/en/latest/api/mod_model/#flask_admin.model.BaseModelView.update_model" rel="nofollow noreferrer">update_model</a> that...
<python><flask-appbuilder>
2024-07-04 13:29:39
1
7,968
Jundiaius
78,707,294
2,359,027
Python: Logging to a single file when having a ProcessPoolExecutor within Process workers, using QueueHandler
<p>I want to add logs to a single file from different Processes, which contain a ProcessPoolExectuor.</p> <p>My application has the following strcture:</p> <ul> <li>Main Process</li> <li>Secondary Process with a pool of processes: ProcessPoolExecutor</li> </ul> <p>Both the secondary process and the pool of processes ar...
<python><multiprocessing><python-multiprocessing>
2024-07-04 13:04:32
1
1,133
laurapons
78,707,235
19,648,465
How to Implement a Guest Login in Django REST Framework
<p>I currently have a backend setup where users can register by providing an email, name, and password. These fields are required for registration. I want to implement a guest login feature where a guest account is deleted when the browser is closed or the guest logs out.</p> <p>How should I proceed to create a guest a...
<python><django><authentication><django-rest-framework><user-accounts>
2024-07-04 12:51:05
1
705
coder
78,706,921
13,806,869
Why does plotting errors vs actual via PredictionErrorDisplay result in a value error?
<p>I have trained a random forest regression model using sklearn, and used it to make some predictions on a test dataset. Naturally there are errors where the values predicted by the model are not the same as the actual values; in this case, the model's Mean Average Error and Mean Squared Error are quite high.</p> <p>I...
<python><matplotlib><scikit-learn>
2024-07-04 11:44:16
1
521
SRJCoding
78,706,895
3,737,484
Send coins/jettons on TON blockchain using Python
<p>How can I send coins/Jettons (for example, Notcoin) from one TON blockchain wallet to another using Python?</p> <p>No one SDK has a working example. 😞</p>
<python><blockchain><ton>
2024-07-04 11:39:09
2
336
veaceslav.kunitki
78,706,741
9,627,166
How should I deal with multiple imports having the same name
<p>I have a repository that contains multiple programs:</p> <pre><code>. └── Programs    ├── program1    │   └── Generic_named.py    └── program2    └── Generic_named.py </code></pre> <p>I would like to add testing to this repository.</p> <p>I have attempted to do it like this:</p> <pre><code>. ├── Programs │  ...
<python><python-3.x><python-unittest>
2024-07-04 11:06:54
1
489
Programmer S
78,706,728
3,299,432
Flask app errors on all other endpoints except for root - what am I missing
<p>I've developed a Flask app that runs perfectly on my laptop - all endpoints work perfectly and I've also created several HTML pages that interact with the Flask API endpoints.</p> <p>The next step is to deploy this (permanently) to AWS EC2 (Ubuntu). I've followed this tutorial about creating a Flask app <a href="htt...
<python><flask>
2024-07-04 11:04:48
1
547
cmcau
78,706,701
11,749,309
FastAPI/Poetry Docker Deployment on Digital Ocean App Platform/Droplet
<p>I have a <a href="https://github.com/humblFINANCE/humblAPI" rel="nofollow noreferrer">FastAPI Project </a> that I am trying to deploy on Digital Ocean's App Platform. I am using a base CPU instance, which is not the issue because I have tested on larger images with more RAM and CPUs.</p> <p>I have a Dockerfile for m...
<python><docker><pip><digital-ocean><python-poetry>
2024-07-04 10:59:47
1
373
JJ Fantini
78,706,696
3,556,110
How do I add a prefetch (or similar) to a django queryset, using contents of a JSONField?
<h2>Background</h2> <p>I have a complex analytics application using conventional relational setup where different entities are updated using a CRUD model.</p> <p>However, our system is quite event driven, and it's becoming a real misery to manage history, and apply data migrations respecting that history.</p> <p>So we'...
<python><json><django><postgresql><jsonfield>
2024-07-04 10:59:10
1
5,582
thclark
78,706,565
10,349,175
Pass system env variable to self-hosted github-runner
<p>I have a self-hosted runner based on Mac OS Ventura 13.6.5. Mac has installed Python using Homebrew:</p> <pre><code>brew install python </code></pre> <p>and Path for python variable in .<code>zshrc</code></p> <pre><code>export PATH=&quot;$(brew --prefix python)/libexec/bin:$PATH&quot; </code></pre> <p>In the workflo...
<python><github-actions><cicd><github-actions-self-hosted-runners>
2024-07-04 10:30:59
0
432
AShX
78,706,456
287,297
Opposite results between `bool(x)` and `x.__bool__()` after patching
<p>In this simple little test case, I monkey patch the <code>__bool__</code> method of an instance, but am surprised to see that calling <code>bool(x)</code> and <code>x.__bool__()</code> give opposite results afterwards. What is the explanation for this behavior? Is it a bug or a feature of the language? Thanks.</p> <...
<python><boolean><monkeypatching>
2024-07-04 10:10:54
0
6,514
xApple
78,706,369
10,470,463
Insert values in a dataframe depending on the date
<p>I want to put the results of many pivot tables in a dataframe where the dates in the pivot table are the same as the dates in the another dataframe.</p> <p>I do not wish to simply replace all nan values. The nan values will be important later.</p> <p>The code below does what I want to do, but I read, for-loops are n...
<python><pandas>
2024-07-04 09:54:10
0
511
Pedroski
78,706,174
3,121,975
Non-iterable value used in iterating context in Pydantic validator
<p>I have a Pydantic DTO that looks like this:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import AfterValidator, model_validator, BaseModel class Bid(BaseModel): start_block: Annotated[DateTime, AfterValidator(block_validator)] end_block: Annotated[DateTime, AfterValidator(block_valida...
<python><pydantic><pylint>
2024-07-04 09:18:29
1
8,192
Woody1193
78,706,156
21,348,174
Auto complete for Python files in VS Code does not work for sub directories
<p><strong>End goal</strong></p> <p>Setting up autocomplete for my self wrriten lib in VS Code for python files that will eventually run in Autodesk Revit.</p> <p><strong>Project Structure</strong></p> <pre><code>├── my_directory │ ├── script1.py │ └── subdirectory │ └── script2.py └── lib ├── __init__.py...
<python><visual-studio-code><environment-variables>
2024-07-04 09:15:20
0
435
IdoBa
78,706,105
6,049,429
Python Set Context precision for Decimal field
<pre><code>from decimal import Decimal, setcontext, getcontext class MyNewSerializer(serializers.Serializer): total_value_base = serializers.SerializerMethodField() total_outgoing_value_base = serializers.DecimalField( max_digits=38, decimal_places=8, source=&quot;value_sent&quot;, ...
<python><python-3.x><django><decimal>
2024-07-04 09:04:25
1
984
Cool Breeze
78,706,072
11,233,365
Python: Have multiprocessing pools start and run their own multiprocessing pools
<p>I am in the process of processing a list of arrays, and this is a workflow that could be parallelised at multiple points: One sub-process for each dataset in the list, and multiple sub-processes each to handle the different slices in the array.</p> <p>I've read that process daemons are generally not allowed to spawn...
<python><multiprocessing>
2024-07-04 08:56:57
0
301
TheEponymousProgrammer
78,706,027
9,974,205
Optimizing DataFrame Processing for User Login Intervals with Pandas
<p>I'm working on a function that processes the login times of users on a website. These times are stored in a Pandas DataFrame where the first column indicates a time interval, and the rest indicate if a user was logged in during that interval. My program acts on this DataFrame and groups users, creating as many colum...
<python><pandas><dataframe><optimization><python-itertools>
2024-07-04 08:49:46
1
503
slow_learner
78,706,017
15,948,240
Change style of DataTable in Shiny for Python
<p>I would like to set a background color in a Shiny for Python DataTable</p> <pre><code>from palmerpenguins import load_penguins from shiny import render from shiny.express import ui penguins = load_penguins() ui.h2(&quot;Palmer Penguins&quot;) @render.data_frame def penguins_df(): return render.DataTable( ...
<python><py-shiny>
2024-07-04 08:48:33
1
1,075
endive1783
78,705,533
3,798,964
Create overloaded functions ignoring irrelevant parameters in the signature
<p>How can I change the signature of the overloads to signal to type checkers that only a single parameter is responsible for the return type, ignoring all the other parameters?</p> <p>Starting from this code (neither <code>mypy</code> nor <code>pyright</code> complains yet):</p> <pre><code>from typing import Literal, ...
<python><mypy><python-typing><pyright>
2024-07-04 07:09:35
1
4,485
johnson
78,705,531
1,831,695
upload file to Sharepoint using python
<p>I try to upload a csv file to a Sharepoint. I came so far with my script:</p> <pre><code>from office365.runtime.auth.client_credential import ClientCredential from office365.sharepoint.client_context import ClientContext import msal import os import requests sharepoint_site_url = &quot;https://companyname.sharepoint...
<python><csv><sharepoint><upload>
2024-07-04 07:09:22
0
563
Ele
78,705,438
6,666,008
How to handle relative resource paths while using pyinstaller / auto py to exe?
<p>I have python script that saves the log file and another csv to a relative resource path. The pyinstaller throws file not found error. The file structure of code is.</p> <pre><code>-ProjectFolder |-common | |- commom.py |-src | |- main.py | |- anotherclass.py |-resources | |-output.logs | |-result.csv </co...
<python><pyinstaller><auto-py-to-exe>
2024-07-04 06:44:46
1
682
ss301
78,704,955
9,630,700
Avoiding additional null string using Pandas date_range
<p>I was trying to obtain a formatted list of dates Pandas date_range and obtained an extra null string. This is using Pandas v2.2.2.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; pd.date_range('2000-01-01','2000-01-03').format('%Y-%m-%d') &lt;stdin&gt;:1: FutureWarning: DatetimeIndex.format is deprecate...
<python><pandas>
2024-07-04 03:44:45
1
328
chuaxr
78,704,879
4,778,587
Using requests I get a 401 but urllib3 and curl work
<p>The following urllib code works to connect to the using the :</p> <pre class="lang-py prettyprint-override"><code>import urllib3 import json # Initialize a PoolManager instance http = urllib3.PoolManager() # Define the URL, headers, and data url = &quot;https://&lt;url&gt;&quot; headers = { &quot;Authorizatio...
<python><curl><python-requests><urllib3>
2024-07-04 03:06:13
1
695
doom4
78,704,811
11,462,274
I need Selenium WebDriver Firefox return the same response as using requests, is there any way?
<p>I have code all assembled to work on this response:</p> <pre class="lang-python prettyprint-override"><code>response = requests.get(url).text soup = BeautifulSoup(response, 'html.parser') </code></pre> <p>But I will need to use <code>Selenium WebDriver</code> instead of <code>requests</code>, I tried to use it this ...
<python><selenium-webdriver><python-requests><selenium-firefoxdriver>
2024-07-04 02:28:19
1
2,222
Digital Farmer
78,704,660
3,458,191
How to format the dataframe into a 2D table
<p>I have following issue with formatting a pandas dataframe into a 2D format. My data is:</p> <pre><code>+----+------+-----------+---------+ | | Jobs | Measure | Value | |----+------+-----------+---------| | 0 | Job1 | Temp | 43 | | 1 | Job1 | Humidity | 65 | | 2 | Job2 | Temp | 48 ...
<python><pandas><dataframe><numpy>
2024-07-04 01:04:05
2
1,187
FotisK
78,704,600
11,793,491
Using lambda with conditional in pandas chain
<p>I have this dataset:</p> <pre class="lang-py prettyprint-override"><code>thedf = pd.DataFrame({'a':[10,20,0],'b':[9,16,15]}) thedf a b 0 10 9 1 20 16 2 0 15 </code></pre> <p>And I want to create a new column using assign in a pandas chain. To avoid a division by zero, I put a conditional inside a lam...
<python><pandas>
2024-07-04 00:15:39
1
2,304
Alexis
78,704,554
17,800,932
Displaying QStandardItemModel from Python in a QML TableView
<p>I am trying to display very simple 2D data in Qt Quick using a QML <code>TableView</code> and Qt for Python / PySide6. Here is an example of what I am looking to create:</p> <p><a href="https://i.sstatic.net/p4A58ofg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/p4A58ofg.png" alt="enter image descri...
<python><qt><qml><pyside><qtquick2>
2024-07-03 23:43:16
1
908
bmitc
78,704,542
395,857
Exporting a Bert-based PyTorch model to CoreML. How can I make the CoreML model work for any input?
<p>I use the code below to export a Bert-based PyTorch model to CoreML.</p> <p>Since I used</p> <pre><code>dummy_input = tokenizer(&quot;A French fan&quot;, return_tensors=&quot;pt&quot;) </code></pre> <p>the CoreML model only works with that input when tested on macOS. How can I make the CoreML model work for any inpu...
<python><machine-learning><bert-language-model><coreml><coremltools>
2024-07-03 23:39:36
1
84,585
Franck Dernoncourt
78,704,484
3,825,495
Pandas DataFrame - find if row matches all values in dictionary
<p>I'm doing an analysis along a pipeline, modeling points along segments, with some physical parameters. I need to keep track of the progress so, when the model hangs due to connectivity issues, etc., I can pick back up without starting from scratch.</p> <p>I'm storing the completed parameters in a dictionary, buildi...
<python><pandas><dataframe>
2024-07-03 23:00:28
1
616
Michael James
78,704,322
20,591,261
Summing Values Based on Date Ranges in a DataFrame using Polars
<p>I have a DataFrame (<code>df</code>) that contains columns: <code>ID</code>, <code>Initial Date</code>, <code>Final Date</code>, and <code>Value</code>, and another DataFrame (<code>dates</code>) that contains all the days for each ID from <code>df</code>.</p> <p>On the <code>dates</code> dataframe i want to sum the...
<python><dataframe><datetime><python-polars>
2024-07-03 21:50:47
2
1,195
Simon
78,704,099
21,152,416
How to make override decorator mandatory?
<p>I came across new <a href="https://docs.python.org/3/whatsnew/3.12.html#pep-698-override-decorator-for-static-typing" rel="nofollow noreferrer">override decorator</a> for Python 3.12 and it looks like an extremely good practice.</p> <p>I'm wondering if there is a way to make it &quot;mandatory&quot; to use? Perhaps ...
<python><mypy><python-typing>
2024-07-03 20:32:54
1
1,197
Victor Egiazarian
78,704,004
1,285,061
Django accounts custom AuthenticationForm failing as invalid
<p>Why is this giving <code>form invalid</code>? My username password input is correct.</p> <p>forms.py</p> <pre><code>class CustomAuthForm(AuthenticationForm): username = forms.CharField(required=True, max_length = 50, widget=forms.EmailInput(attrs={&quot;placeholder&quot;: &quot;Email&quot;, &quot;class&quot;:&q...
<python><python-3.x><django><django-forms>
2024-07-03 19:56:45
1
3,201
Majoris
78,703,950
12,436,050
Explode multiple columns in pandas dataframe
<p>I am trying to explode below dataframe based on a delimiter '|'.</p> <pre><code> preferred_title_symbol mim_number MDR_code MDR_term 0 17-BETA HYDROXYSTEROID DEHYDROGENASE III 264300.0 10037122 pseudohermaphroditism 1 2,4-DIENOYL-CoA REDUCTASE DEFICIENCY 616034....
<python><pandas><explode>
2024-07-03 19:37:29
1
1,495
rshar
78,703,910
8,057,872
How to Resolve ArgumentParser Conflict with -h/--help in Subcommands?
<p>I'm developing a Python command-line tool using argparse with multiple modules, each having its own set of arguments. I'm using separate classes to define each module's arguments and integrate them into a main script. However, I'm encountering an issue where the <code>-h/--help</code> argument is conflicting when ru...
<python><argparse>
2024-07-03 19:25:51
1
548
Mahdi Baghbanzadeh
78,703,837
13,834,264
Unable to parse JSON string obtained from attribute in a HTML tag in Python
<p>I am making an AJAX call to an endpoint (I didn't create this API) where the response is in JSON form. Within the JSON there is an a key called <code>content</code> of type <code>string</code>. This content appears to me to be HTML data which contains some JSON inside. I want to be able to parse this JSON which is c...
<python><json><beautifulsoup>
2024-07-03 19:05:01
2
965
knowledge_seeker
78,703,690
8,547,986
'pipx' using the latest Python 3.12 instead of the system default
<p>I am using <code>pyenv</code> for managing a Python installation in my system. Using <code>pyenv</code>, I have installed <code>python3.11.9</code> and set it as default with <code>pyenv global 3.11.9</code>, I have also added recommended commands by <code>pyenv</code> in my <em><a href="https://wiki.debian.org/Zsh#...
<python><python-3.x><homebrew><pyenv><pipx>
2024-07-03 18:21:20
2
1,923
monte
78,703,688
18,769,241
How to train yolov8 to recognize one additional image
<p>So I want to train yolov8 with a dataset containing one annotated image ( using roboflow ) to add the label to the current model so that the yielded trained model will recognize the new image.</p> <p>First I get the one-image-dataset annotated in roboflow like so:</p> <pre><code>dataset = version.download(model_form...
<python><machine-learning><deep-learning><yolov8><roboflow>
2024-07-03 18:21:02
0
571
Sam
78,703,567
169,252
Can I use a python script to run as a daemon with async libs or do I need to use subprocess?
<p>I need to run a quick experiment with python. However, I am stuck with an async issue. I am not very familiar with python async programming, so please bear with me.</p> <p>What I want is to run a script which starts different daemons at different ports, and then waits for connections to be established to it.</p> <p>...
<python><asynchronous><async-await><daemon>
2024-07-03 17:50:52
1
6,390
unsafe_where_true
78,703,543
5,838,180
Get the errorbars to bins of a dataset by using bootstrapping
<p>I have some data called <code>variable</code> that I can simulate in the following way:</p> <pre><code>import pandas as pd import numpy as np from scipy.stats import bootstrap random_values = np.random.uniform(low=0, high=10, size=10000) df = pd.DataFrame({&quot;variable&quot;: random_values}) </code></pre> <p>I wa...
<python><pandas><scipy><bootstrapping><errorbar>
2024-07-03 17:43:53
2
2,072
NeStack
78,703,540
3,486,684
What determines that a given Python type is coercible into a given pyarrow datatype?
<p>For example:</p> <ul> <li>I know a dictionary can be coerced into a struct; what else can be coerced into a struct? What determines whether a Python type is coercible into a <code>pyarrow</code> datatype? Convention? Documentation? Subclassing?</li> <li>on subclassing: can I make a custom class a subclass of some <c...
<python><pyarrow>
2024-07-03 17:42:46
0
4,654
bzm3r
78,703,537
11,163,122
Why does Python not allow Generics with isinstance checks?
<p>Running the below code with Python 3.12.4:</p> <pre class="lang-py prettyprint-override"><code>from typing import Generic, TypeVar T = TypeVar(&quot;T&quot;) class Foo(Generic[T]): def some_method(self) -&gt; T: pass isinstance(Foo[int](), Foo[int]) </code></pre> <p>It will throw a <code>TypeError: Su...
<python><generics><python-typing><isinstance>
2024-07-03 17:41:57
2
2,961
Intrastellar Explorer
78,703,500
3,486,684
Ways of creating a struct directly?
<p>I know I can create a Polars struct &quot;scalar&quot; indirectly using dictionaries as elements when building a series. But is there any way in which I can directly create a Polars struct scalar directly? (Not in a series, or a dataframe.)</p> <p>For reasons I am not clear on, people think this question might be si...
<python><python-polars>
2024-07-03 17:32:11
1
4,654
bzm3r
78,703,489
6,622,697
Validating POST parameters with serializers in Django
<p>I'm trying to implement a simple validator for my POST parameters</p> <p>My input looks like this:</p> <pre><code>{ &quot;gage_id&quot;: &quot;01010000&quot;, &quot;forcing_source&quot;:&quot;my_source&quot;, &quot;forcing_path&quot;:&quot;my_path&quot; } </code></pre> <p>I have the following Serializer:</p> <...
<python><django><validation><django-rest-framework><django-serializer>
2024-07-03 17:28:19
1
1,348
Peter Kronenberg
78,703,478
3,486,684
Ways of creating a `pyarrow.StructScalar` directly?
<p>I know I can create a <code>pa.StructScalar</code> by casting:</p> <pre><code>import pyarrow as pa import pyarrow.compute as pac struct_scalar = pac.cast( {&quot;hello&quot;: &quot;greetings&quot;, &quot;world&quot;: 5}, target_type=pa.struct([(&quot;hello&quot;, pa.string()), (&quot;world&quot;, pa.int16()...
<python><pyarrow>
2024-07-03 17:26:47
1
4,654
bzm3r
78,703,443
3,486,684
Infer `pyarrow.DataType` from Python type?
<p>Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any, get_type_hints import pyarrow as pa import pyarrow.compute as pac ArrowTypes = { int: pa.int64(), str: pa.string(), } class StructLike: __attr_types__: dict[str, Any] = {} __attr_annotations_...
<python><pyarrow>
2024-07-03 17:15:30
0
4,654
bzm3r
78,703,347
3,748,377
Invalid argument value. SQLSTATE=HY009 SQLCODE=-99999 with executemany() using Python
<p>I want to insert records in batches in DB using <strong>executemany()</strong> using python. I have a below code</p> <pre><code> def find_data(db_string): json_str = '[\\&quot;{\\&quot;NAME\\&quot;:\\&quot;Aman\\&quot;,\\&quot;EMAIL\\&quot;:\\&quot;aman@gmail.com\\&quot;,\\&quot;SALARY\\&quot;:785674}\\&quo...
<python><db2>
2024-07-03 16:50:01
0
380
ankit
78,703,317
5,525,901
Difference between .scalars().all() and list(...scalars()) in SQLAlchemy
<p>Are there any significant differences (performance, or otherwise) between the following two ways of getting a list of results?</p> <pre class="lang-py prettyprint-override"><code>users: Sequence[User] = session.execute(select(User)).scalars().all() </code></pre> <pre class="lang-py prettyprint-override"><code>users:...
<python><sqlalchemy>
2024-07-03 16:44:02
1
1,752
Abraham Murciano Benzadon
78,703,313
4,332,644
segment_anything causing error with numpy.uint8
<p>I am trying to run <a href="https://github.com/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb" rel="nofollow noreferrer">https://github.com/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb</a> locally, on an M2 MacBook with Sonoma 14.5. However, I keep ru...
<python><numpy><machine-learning><pytorch><segment-anything>
2024-07-03 16:43:17
1
3,201
LNI
78,703,282
1,126,944
Example Needed for "Directories With A Common Name Hiding Modules"
<p>When I read Python 3's documentation for modules, in <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="nofollow noreferrer">6.4 Packages</a>, it said (emphasis mine):</p> <blockquote> <p>The <code>__init__.py</code> files are required to make Python treat directories containing the file as pack...
<python>
2024-07-03 16:33:48
1
1,330
IcyBrk
78,703,240
2,153,235
pyplot.plot uses markerfacecolor while pyplot.scatter uses facecolor
<p>I come from a Matlab background, which is an inspiration for <code>matplotlib</code> (or so I understand, rightly or wrongly).</p> <p>I was surprised to find that similar options for the different plots use different option names. For example, <code>pyplot.plot</code> uses <code>markerfacecolor</code> while <code>p...
<python><matplotlib>
2024-07-03 16:24:27
1
1,265
user2153235
78,703,168
2,746,401
Annotate JSON schema properties in Python with msgspec (or pydantic)
<p>In the JSON schema produced from a <code>msgspec</code> Struct, I'm wanting to output to the schema some text descriptions of the properties held within the Struct in the same way as the docstring of the Struct shows up in the JSON schema.</p> <p>This little toy example (cut down from <a href="https://jcristharif.co...
<python><json><pydantic><msgspec>
2024-07-03 16:08:13
2
3,496
user2746401
78,703,154
6,622,697
Usage of OneToOneField in Django
<p>I am very confused about the usage of the <code>OnetoOneField</code>. I thought it was for a case where a given record can only have 1 reference to another table. For example, a Child has 1 Parent.</p> <p>But it seems that Django makes the field that is defined as OneToOne a primary key of your table, meaning it h...
<python><django><django-models><one-to-one>
2024-07-03 16:06:22
1
1,348
Peter Kronenberg
78,703,101
2,153,235
Prevent Spyder editor from opening on startup
<p>Is there any way to prevent the editor from opening when Spyder starts?</p> <p><a href="https://stackoverflow.com/questions/48500051">This Q&amp;A</a> is about opening files on startup <em>if</em> those files were open when Spyder was last closed. In my case, usually have the editor closed when I quit Spyder.</p> <...
<python><spyder>
2024-07-03 15:52:58
0
1,265
user2153235
78,703,076
5,269,892
PyCharm unresolved attribute reference
<p>When inverting a boolean mask, PyCharm shows an inspection warning <em>Unresolved attribute reference 'sum' for class 'int'</em>. It seems it does not know that the inverted boolean mask maintains the <em>sum()</em> method.</p> <p><strong>Questions:</strong> What is the reason for this behavior in this specific case...
<python><pandas><pycharm><code-inspection>
2024-07-03 15:46:46
1
1,314
silence_of_the_lambdas
78,702,950
2,153,235
Bring Spyder plot window to the front on Windows 10
<p>I am following <a href="https://stackoverflow.com/a/53669049">this answer</a> to bring plot windows to the front by choosing a different graphics backend:</p> <pre><code>Tools &gt; Preferences &gt; Ipython &gt; Graphis &gt; backend </code></pre> <p>The options are <code>Inline</code>, <code>Automatic</code>, <code>Q...
<python><matplotlib><spyder>
2024-07-03 15:19:51
1
1,265
user2153235
78,702,466
23,483,136
About the iterator protocol
<p>Why in Python is the iterator exhaustion fixed by calling <code>StopIteration</code>, and not by implementing the <code>IsDone()</code> method on the iterator, as written in GoF Design Patterns? Raising an exception is still a rather expensive operation.</p>
<python>
2024-07-03 13:43:59
0
354
Pavel
78,702,337
3,146,304
Tensorflow/Keras model raises output shape errors when loaded in another system
<p>I have a tf.keras lstm model that I trained on Google Colab and I want to load it on my laptop so I can run it to do inference. I created a Python virtual environment on my laptop with the same versions of Tensorflow/Keras as Google Colab (2.15) and the same version of Python (3.10). Despite this, when I load the mo...
<python><tensorflow><keras>
2024-07-03 13:14:54
0
389
Vitto
78,702,312
16,613,735
Python pandas-market-calendars
<p>Question on calendar derivation logic in the Python module <a href="https://pypi.org/project/pandas-market-calendars/" rel="nofollow noreferrer">https://pypi.org/project/pandas-market-calendars/</a>. Does this module depend on any third party API's to get the calendars or the calendars are derived based on <strong>r...
<python><pandas><calendar>
2024-07-03 13:10:29
1
335
Dinakar Ullas
78,702,278
652,460
Why does readthedocs require authorisation to write commits when connecting to github?
<p>I'm trying to use readthedocs with a github repo that stores a Python project. When I try to connect it to my github profile, I am asked to authorise the following:</p> <blockquote> <p>This application will be able to read and write commit statuses (no direct code access).</p> </blockquote> <p>It shouldn't need to c...
<python><github><read-the-docs>
2024-07-03 13:03:42
1
834
mtanti
78,702,193
6,622,697
Automatically updated created_by/updated_by with Django authenticated user
<p>I have a BaseModel that looks like this:</p> <pre><code>class BaseModel(models.Model): updated_by = models.ForeignKey(get_user_model(), related_name='+', on_delete=models.RESTRICT, db_column='updated_by') updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(get_user_model(), re...
<python><django><authentication>
2024-07-03 12:49:10
0
1,348
Peter Kronenberg
78,702,014
1,285,061
How to get the current domain name in Django template?
<p>How to get the current domain name in Django template? Similar to {{domain}} for auth_views. I tried <code>{{ domain }}</code>, <code>{{ site }}</code>, <code>{{ site_name }}</code> according to below documentation. It didnt work.</p> <pre><code>&lt;p class=&quot;text-right&quot;&gt;&amp;copy; Copyright {% now 'Y' %...
<python><python-3.x><django><django-templates>
2024-07-03 12:15:46
2
3,201
Majoris
78,701,694
1,509,264
How to manually generate fixtures for Django Polymorphic Models?
<p>I have some <a href="https://django-polymorphic.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer">Django Polymorphic</a> models:</p> <pre class="lang-python prettyprint-override"><code>import uuid from django.db import models from polymorphic.models import PolymorphicModel class Fruit(PolymorphicModel)...
<python><django><django-fixtures><django-polymorphic>
2024-07-03 11:12:55
1
172,539
MT0
78,701,537
2,071,807
What's the difference between Pint's "Quantity" and "PlainQuantity"?
<p>My IDE (type-checking provided by the Pyright language server) doesn't like me passing <code>pint.Quantity</code> instances to functions type-hinted with <code>pint.Quantity</code>:</p> <pre class="lang-py prettyprint-override"><code>from pint import Quantity def get_units(quantity: Quantity): return quantity.un...
<python><python-typing><pyright><pint>
2024-07-03 10:39:32
1
79,775
LondonRob
78,701,509
4,732,111
How to replace a specific field inside a JSON string in each row of a csv file in Python with a random value?
<p>I have a CSV file named <em><code>input.csv</code></em> with the following columns:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: left;">row_num</th> <th style="text-align: center;">start_date_time</th> <th style="text-align: right;">id</th> <th style="text-align: rig...
<python><pandas><python-polars>
2024-07-03 10:32:22
3
363
Balaji Venkatachalam
78,701,495
16,327,154
What is the default accuracy scoring in cross_val_score() in sklearn?
<p>I have a regression model made using random-Forest. I made pipelines using scikit-learn to process data and now have used <code>RandomForestRegressor</code> to predict. I want to get the accuracy of model. because of the problem of over-fitting I decided to use the <code>cross_val_score</code> function to get rid of...
<python><scikit-learn>
2024-07-03 10:29:52
2
327
Mehan Alavi
78,701,305
1,735,184
pandas string selection
<p>I would like to extract rows containing a particular string - the string can be a part of a larger, space-separated string (which I would want to count in), or can be a part of another (continuous) string (which I would NOT want to count in). The string can be either at start, middle or end of the string value.</p> ...
<python><pandas><string><selection>
2024-07-03 09:52:16
1
1,708
branwen85
78,701,277
1,474,073
Streamlit app spams DEBUG logs despite loglevels are set correctly
<p>I have a streamlit app. I correctly set its log level to INFO, however I get tons of debug messages like this:</p> <pre><code>[2024-07-03T09:42:03+0000 | DEBUG |inotify_buffer |watchdog.observers.inotify_buffer]: in-event &lt;InotifyEvent: src_path=b'/app/streamlit/logs/myapp.log', wd=3, mask=IN_MODIFY, cookie...
<python><streamlit>
2024-07-03 09:46:54
0
8,242
rabejens
78,701,097
9,458,268
How to dynamically create type annotations in Python?
<p>Normally, one can define a class with some type-annotated fields as follows:</p> <pre><code>class A: a: str </code></pre> <p>How to do this dynamically using <code>type</code> function?</p> <p>I know the case when <code>a</code> is assigned to a value, i.e., in the case that</p> <pre class="lang-py prettyprint-o...
<python><metaprogramming>
2024-07-03 09:14:17
1
350
Clément Dato
78,701,013
113,586
Replacing pkg_resources `Distribution.run_script()`
<p>As pkg_resources is deprecated but the official migration guides don't offer migration paths for all of its API I'm seeking a replacement for <a href="https://setuptools.pypa.io/en/latest/pkg_resources.html#imetadataprovider-methods" rel="nofollow noreferrer"><code>Distribution.run_script()</code></a>.</p> <p>As far...
<python><pkg-resources>
2024-07-03 08:55:10
1
25,704
wRAR