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,553,793
4,159,193
Use Pybind11 library created with MSYS2,CMake and Make in Python
<p>I have just created a library with Pybind11 from the C++ side: I did it with MSYS2 and CMake and Make. (I have GCC, Make, CMake and Pybind11 installed with the commands)</p> <pre><code>pacman -S mingw-w64-x86_64-gcc pacman -S mingw-w64-x86_64-cmake pacman -S mingw-w64-x86_64-make pacman -S mingw-w64-x86_64-pybind11 ...
<python><cmake><pip><python-module><pybind11>
2024-05-30 08:29:05
2
546
flori10
78,553,768
2,071,807
Running multiple "after" model validators in Pydantic raises only one ValidationError
<p>If a model has more than one failing <code>@model_validator(&quot;after&quot;)</code>, then only one (the first?) is raised.</p> <p>Is it possible to tell Pydantic to run all model validators? Are multiple model validators even supported? The docs seem to be silent on this question.</p> <p>In the below example, I wo...
<python><pydantic>
2024-05-30 08:25:27
0
79,775
LondonRob
78,553,761
10,750,541
Unexpected behaviour in seaborn subplots when the x axis is being shared
<p>I am having trouble using the <code>sharex=True</code> when I create two graphs with <code>seaborn</code> that should share the same horizontal axis.</p> <p>I have my example hereafter and even with <code>sharex=False</code> I get a warning that I cannot interpret.</p> <p>I print below the xticklabels and they are n...
<python><seaborn><subplot>
2024-05-30 08:24:44
0
532
Newbielp
78,553,628
8,480,460
Displaying sites every 10 seconds with Python and Selenium from a CSV
<p>I am doing an automation with Python. This automation should take a list of websites from a .csv file and perform click activities on them, which are working correctly, so I will omit parts of the code.</p> <p>I adjusted a line of code which is this one:</p> <pre><code>if time.time() - start_time &gt; 10: print(...
<python><csv><selenium-chromedriver><rpa>
2024-05-30 07:59:15
1
1,094
claudiopb
78,553,590
241,552
Can I add abbreviations for imports to PyCharm?
<p>There is a number of industry-accepted import abbreviations, such as <code>import pandas as pd</code>, and there's a number of abbreviation conventions on our project. Is there a way to add them to PyCharm, so that I could type, say <code>mm.Schema</code>, command-click on the <code>mm</code> and have PyCharm add <c...
<python><pycharm>
2024-05-30 07:50:45
0
9,790
Ibolit
78,553,427
19,356,117
How to select data in xarray Dataset with multiple slices once?
<p>I have a xarray dataset which looks like this:</p> <pre><code>Dimensions: (time: 24, longitude: 701, latitude: 701) Coordinates: * time (time) datetime64[ns] 192B 2023-06-01 ... 2023-06-01T23:00:00 * longitude (longitude) float32 3kB 70.0 70.1 70.2 70.3 ... 139.8 139.9 140.0 * latitude (latitude) f...
<python><gis><python-xarray>
2024-05-30 07:16:31
1
1,115
forestbat
78,553,412
8,934,639
How to create a datadog gauge metric in python Lambda?
<p>We have a Lambda written in Python, and we use datadog-lambda library to report metrics to datadog. Is there a way to create a gauge metric using the above library?</p>
<python><aws-lambda><datadog>
2024-05-30 07:13:25
1
301
Chedva
78,553,269
451,878
Use "with" in all CRUD functions
<p>We have some issues with FastAPI (reading and &quot;lost&quot; data from database), so we use <code>with</code> instead of <code>Depends</code>.</p> <p>Is it a good practice?</p> <pre><code>with SessionManager() as db: @router.get(&quot;/{id}&quot;, response_model=...) async def get_by_id(id: UUID) -&gt; JS...
<python><fastapi><crud>
2024-05-30 06:39:23
2
1,481
James
78,553,180
7,717,176
List of values of a key in Qdrant
<p>I have a collection named <code>Docs</code> in the qdrant database. There are multiple points in this collection. Each point has metadata including the title of the document. I want to extract a list of titles. I tried to do it but it returned none. How can I do it?</p> <pre><code>from qdrant_client import QdrantCli...
<python><vector-database><qdrant><qdrantclient>
2024-05-30 06:16:43
2
391
HMadadi
78,553,026
395,857
How can I save a tokenizer from Huggingface transformers to ONNX?
<p>I load a tokenizer and Bert model from Huggingface transformers, and export the Bert model to ONNX:</p> <pre><code>from transformers import AutoTokenizer, AutoModelForTokenClassification import torch # Load the tokenizer tokenizer = AutoTokenizer.from_pretrained(&quot;huawei-noah/TinyBERT_General_4L_312D&quot;) # ...
<python><huggingface-transformers><onnx><huggingface-tokenizers>
2024-05-30 05:28:12
1
84,585
Franck Dernoncourt
78,552,892
2,155,026
KeyError in nx.algorithms.approximation.traveling_salesman_problem()
<p>I have written a code which generates 10 random graphs and solve the traveling salesman problem using NetworkX. I am getting <code>KeyError: 1</code>.</p> <p>Following is my code.</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt import numpy as np import time import csv import pandas as pd # Fun...
<python><graph><networkx><traveling-salesman><jsnetworkx>
2024-05-30 04:41:55
1
1,144
Omar Shehab
78,552,821
1,107,474
Simple example of C++ calling Python using Pybind11 and CMake
<p>I have a simple C++ main.cpp file with two vectors I'd like to pass to a Python function:</p> <pre><code>#include &lt;vector&gt; int main() { std::vector&lt;double&gt; vec1; std::vector&lt;double&gt; vec2; } </code></pre> <p>python.py:</p> <pre><code>def python_function(list_1, list_2): # Code </code></...
<python><c++><cmake><pybind11>
2024-05-30 04:09:18
1
17,534
intrigued_66
78,552,745
424,957
Why are the results different by Google Maps and Matplotlib?
<p>I plotted a kml file using matplotlib and showed it on Google Maps, but the line is different. Can anyone tell me why? How can I plot it just like in Google Maps?</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;kml xmlns=&quot;http://www.open...
<python><matplotlib><geopandas><kml>
2024-05-30 03:27:31
1
2,509
mikezang
78,552,650
270,043
PySpark dataframes not matching the headers
<p>I have a bunch of parquet files written over a period of 6 months, partitioned by the date and hour when they were created. Over these 6 months, the headers have changed, so the data schema for the parquet files created on Jan 1 is different from the files created on May 1.</p> <p>I'm trying to read the parquet file...
<python><dataframe><pyspark><parquet>
2024-05-30 02:36:31
1
15,187
Rayne
78,552,507
12,834,785
CORS violation only on Apple Silicon Macs in Flask app
<p>I have reproduced this error with the following python backend api using flask.</p> <pre class="lang-py prettyprint-override"><code>from flask import Flask, jsonify, request from flask_cors import CORS app = Flask(__name__) CORS(app) # Enable CORS for all routes and origins @app.route('/api/hello', methods=['GET'...
<python><cors><apple-silicon>
2024-05-30 01:26:26
1
340
Duncan Britt
78,552,467
968,132
Why does VS Code show inline comments as part of environment variables from .env file?
<p>VS Code is showing the inline comments and quotes from my .env file when importing environment variables and I can't figure out why. It does not happen if I run the script from terminal, only within VS Code -&gt; Run. Also</p> <p>dotenv is quite forgiving per <a href="https://pypi.org/project/python-dotenv/" rel="no...
<python><visual-studio-code><dotenv>
2024-05-30 01:03:23
2
1,148
Peter
78,552,387
8,452,243
Optimizing node placement in a 2D grid to match specific geodesic distances
<p>I'm working on a problem where I need to arrange a set of nodes within a 2D grid such that the distance between pairs of nodes either <em>approximate</em> specific values as closely as possible or <em>meet a minimum threshold</em>.</p> <p>In other words, for some node pairs, the distance should be approximately equa...
<python><optimization><or-tools><cp-sat>
2024-05-30 00:18:13
2
1,363
solub
78,552,380
8,458,083
How to solve problem of circular reference when defining a tree in python 3.12?
<p>I try to follow this <a href="https://wickstrom.tech/2024-05-23-statically-typed-functional-programming-python-312.html" rel="nofollow noreferrer">tutoriel</a>. I am using python 3.12 as required</p> <p>I try to run this code:</p> <pre><code>from dataclasses import dataclass from typing import Callable type RoseTr...
<python><python-3.12>
2024-05-30 00:13:44
1
2,017
Pierre-olivier Gendraud
78,552,374
19,429,024
Issues with threading and hotkeys using pynput in Python (Infinite Loop and Responsiveness)
<p>I'm trying to use the <code>pynput</code> library to listen for hotkeys and start a thread when the <code>F12</code> key is pressed. The thread prints a message in an infinite loop to the console. Pressing <code>ESC</code> should stop the application. My <code>Example</code> class extends <code>Thread</code> and ove...
<python><multithreading><pynput>
2024-05-30 00:11:49
2
587
Collaxd
78,552,358
424,957
How to plot LinsString in gpd.GeoDataFrame?
<p>I have a kml file that has LinrString and Polygon, I can plot polygon, but I am not sure how to plot LineString, I tried <code> polys.boundary.plot(ax=axs, facecolor=color, color=color, label=legend, zorder=3)</code>, that seems like not work, how can I plot LineString in gpd.GeoDataFrame?</p> <pre><code>myPolys = g...
<python><matplotlib><geopandas>
2024-05-29 23:55:10
1
2,509
mikezang
78,552,276
8,121,824
How to use duplicate rows of input forms for dash app?
<p>I am new to Dash and working on a personal finance app, which will include spending tracking. I'd ideally like to have multiple rows of input forms so the user can add multiple transactions, or split out one receipt if they'd like. Does each input need to have a distinct id, or is there an easier way to go about thi...
<python><input><plotly-dash>
2024-05-29 23:08:29
1
904
Shawn Schreier
78,552,242
2,687,317
Polar contour plot with irregular 'bins'
<p>So I have sky data in azimuth and elevation (imported from matlab) that is 'binned' in 3 deg x 3 deg samples. So the matrix is 30 x 120 (3x30=90 deg of el, 3x120=360 of az). Each elevation, 0, 3, 6, ..., 87, has 120 azimuth values associated with it...</p> <p>However, as you get closer to the zenith you really don't...
<python><matplotlib><contour>
2024-05-29 22:44:43
1
533
earnric
78,551,987
11,039,749
Python Selenium execute from cronjob linux and shell script
<p>I have a shell script that executes a python script through a cronjob.</p> <p>If I run the shell script or python script it executes without any issues.</p> <p>It only has issues when I execute it from a cronjob.</p> <p>Shell Script</p> <pre><code>!/bin/bash # Set environment variables export XDG_RUNTIME_DIR=/run/...
<python><linux><bash><selenium-webdriver><cron>
2024-05-29 21:19:17
1
529
Bigbear
78,551,953
1,922,531
Why does python not find regex that regex101 does?
<p>I have this <a href="https://regex101.com/r/rwTrEf/1" rel="nofollow noreferrer">regex</a>, which works perfectly in regex101, but will not work in actual python. The find string exists in the test string, but python will not find it.</p> <pre><code>find_str = r'^([\s\S]*)(?&lt;=\n\n)([ \n-]+Once in a Lifetime Values...
<python><regex>
2024-05-29 21:06:52
1
1,493
lukehawk
78,551,949
2,641,576
Python TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid
<p>I am getting the following error:</p> <pre class="lang-none prettyprint-override"><code>TypeError: cannot concatenate object of type '&lt;class 'str'&gt;'; only Series and DataFrame objs are valid Traceback (most recent call last): File &quot;/var/task/etd.py&quot;, line 77, in lambda_handler data = pd.concat...
<python><pandas><dataframe>
2024-05-29 21:06:27
1
15,081
Matt
78,551,946
1,303,577
Python use delimited string to access element in nested dictionary
<p>I'm trying load a yaml file and access elements from it by a <code>/</code> delimited string.</p> <p>Sample yaml file:</p> <pre><code>foo: bar: baz: qux corge: waldo </code></pre> <p>I'm loading that file with:</p> <pre><code>import yaml data = yaml.load(open(yamlfile), Loader=yaml.FullLoader) </code></pre> ...
<python><dictionary>
2024-05-29 21:04:32
0
1,945
Rusty Lemur
78,551,846
2,153,235
pandas: Access column-like results from "groupby" and "agg"?
<p>I am using <code>groupby</code> and <code>agg</code> to summarize groups of dataframe rows. I summarize each group in terms of its <code>count</code> and <code>size</code>:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame([ [ 1, 2, 3 ], [ 2, 3, 1 ], [ 3, 2, 1 ], [ 2, 1, 3 ],...
<python><pandas><group-by>
2024-05-29 20:35:07
1
1,265
user2153235
78,551,793
3,817,456
swig - calling char const * [] from python
<p>I have C code with a standard <code>main</code> of the form</p> <pre><code>int mymain(int argc, const char *argv[]); </code></pre> <p>I managed to get through the swig 'pythonizing' process to be able to call this from python. When I import my module and try to call mymain I get</p> <pre><code>&gt;&gt;&gt;mymodule....
<python><c><swig><argv><argc>
2024-05-29 20:18:53
1
6,150
jeremy_rutman
78,551,766
23,260,297
Use groupby and aggregate functions to reshape dataframe
<p>I have a dataframe that looks like this:</p> <pre><code>A B C D E F foo s HO 02/01/24 100 20.0 foo s HO 02/01/24 200 20.0 foo b HO 02/01/24 100 20.0 foo b HO 02/01/24 200 20.0 bar s HO 02/01/24 100 20.0...
<python><pandas>
2024-05-29 20:12:36
1
2,185
iBeMeltin
78,551,694
6,606,057
Transfering NaN's to Dummy Variables While Using One Hot Encoder
<p>I am using OneHotEncoder to create a series of dummy variables based on a categoric variable. The problem I encounter is that any missing values are not transfered to the available dummy variables.</p> <pre><code>oh = OneHotEncoder(min_frequency = 0.0001, sparse_output = False) ### df_experience_level data = oh.fit...
<python><pandas><nan><one-hot-encoding>
2024-05-29 19:55:55
1
485
Englishman Bob
78,551,304
5,994,782
Getting scrapy and pytest to work with AsyncioSelectorReactor
<h2>To reproduce my issue</h2> <ul> <li>python 3.12.1</li> <li>scrapy 2.11.2</li> <li>pytest 8.2.1</li> </ul> <p>In <em>bookspider.py</em> I have:</p> <pre class="lang-py prettyprint-override"><code>from typing import Iterable import scrapy from scrapy.http import Request class BookSpider(scrapy.Spider): name = ...
<python><scrapy><pytest><python-asyncio><twisted>
2024-05-29 18:11:40
1
305
Henry Dashwood
78,551,302
6,703,592
pandas cannot set a value for MultiIndex
<p>It is not allowed to set a value for a MultiIndex. It works for the single index. Maybe becaause of the version of pandas.</p> <pre><code>import pandas as pd df = pd.DataFrame() df.loc[('a', 'b'), 'col1'] = 1 print(df) </code></pre> <blockquote> <p>KeyError: &quot;None of [Index(['a', 'b'], dtype='object')] are in ...
<python><pandas>
2024-05-29 18:11:04
1
1,136
user6703592
78,551,082
1,185,242
How do you parallelize access to a shared array in python using concurrent.futures?
<p>I have the following piece of code to illustrate my problem:</p> <p>Each thread calculates a value <code>locs</code> and then updates the <code>result</code> array, assume that that update (<code>result[locs] += mask[locs]</code> ) is a very slow operation, how can I parallelize it so it can be threaded too?</p> <pr...
<python><parallel-processing><concurrent.futures>
2024-05-29 17:21:58
1
26,004
nickponline
78,550,940
2,336,081
How to get all HTML tags from a page content using BeautifulSoup?
<p>I'm trying to retrieve a tag text from a HTML page but I notice that BeautifulSoup is not &quot;reading&quot; all HTML elements, e.g:</p> <p>This is the part that I'm working on, the <a href="https://www.tibia.com/community/?subtopic=characters&amp;name=Aliance%20Bombao" rel="nofollow noreferrer">full page</a> have ...
<python><beautifulsoup>
2024-05-29 16:53:35
1
656
Rafa Acioly
78,550,725
5,171,169
how to resolve InputText key error in this simple PySimpleGUI script
<p>I do not see why i am getting this error: Traceback (most recent call last): File ....\play_download.py&quot;, line 55, in url = values['-url-'] ~~~~~~^^^^^^^^^ KeyError: '-url-'</p> <p>This error appears when I click on radio button <strong>download_video_with_yt_dlp</strong> <a href="https://i.sstatic.net/tCEeE9d...
<python><pysimplegui>
2024-05-29 16:02:17
1
5,696
LetzerWille
78,550,600
845,210
How to fix Pydantic "Default value is not JSON serializable" warning when using third-party annotated type? [non-serializable-default]
<p>Pydantic supports <a href="https://jrdnh.github.io/posts/pydantic-with-third-party-types/" rel="nofollow noreferrer">annotating</a> <a href="https://docs.pydantic.dev/latest/concepts/types/#handling-third-party-types" rel="nofollow noreferrer">third-party types</a> so they can be used directly in Pydantic models and...
<python><json><jsonschema><pydantic><pydantic-v2>
2024-05-29 15:34:26
1
3,331
bjmc
78,550,495
2,641,576
Error AttributeError: 'DataFrame' object has no attribute 'append', tried pd.concat but causing error also
<p>Getting the error <code>AttributeError: 'DataFrame' object has no attribute 'append</code></p> <p>When trying to run the following:</p> <pre><code>for idx, day_row in ecurr.iterrows(): avlm, relm= lma(dtd, dr['fc'], dr['tc'], dr['od']) ndf.append({'od': dr['od'], 'fc': dr['fc'], 'tc': dr['tc'], 'r': dr['r'], '...
<python><python-3.x><dataframe>
2024-05-29 15:12:50
1
15,081
Matt
78,550,418
5,138,332
SQLModel in FastAPI : NoForeignKeysError
<p>I separately created a Postgresql database with a schema named &quot;geog&quot; and two tables named projections (id, epsg_code, unit_id) and units (id, name).</p> <p>So in my code I have:</p> <ul> <li>units.py</li> </ul> <pre><code>... class Unit(SQLModel, table=True): __tablename__ = &quot;units&quot; meta...
<python><foreign-keys><fastapi><sqlmodel>
2024-05-29 15:00:18
1
314
FloCAD
78,550,382
3,973,269
binary(16) PK from mysql query cannot convert to integer
<p>In my mysql query, executed from a python script, I get a column that is stored as field type binary(16). Unfortunately, when I try to get the integer value from the column, I get <code>invalid literal for int() with base 10: '171099\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'</code> (Since the value is 171099)</p> <p>...
<python><mysql><pandas>
2024-05-29 14:55:25
1
569
Mart
78,550,332
12,821,675
Django - Aggregate of an Aggregation
<p>I am working with DRF and am having issues defining my queryset for use in my view class. Suppose I have three models like so:</p> <pre><code>class ExchangeRate(...): date = models.DateField(...) rate = models.DecimalField(...) from_currency = models.CharField(...) to_currency = models.CharField(...)...
<python><django><django-rest-framework>
2024-05-29 14:46:46
1
3,537
Daniel
78,550,325
269,867
type error while creating custom dataset using huggingface dataset
<p>To generate custom dataset</p> <pre><code>from datasets import Dataset,ClassLabel,Value features = ({ &quot;sentence1&quot;: Value(&quot;string&quot;), # String type for sentence1 &quot;sentence2&quot;: Value(&quot;string&quot;), # String type for sentence2 &quot;label&quot;: ClassLabel(names=[&quot;not_equ...
<python><huggingface-datasets>
2024-05-29 14:46:07
1
4,092
user269867
78,550,308
501,557
Is there a Python f-string equivalent of C++’s std::quoted?
<p>In C++, the <code>std::quoted</code> stream manipulator produces a quoted and escaped version of a string:</p> <pre class="lang-cpp prettyprint-override"><code>std::string dirPath = &quot;C:\\Documents\\Oval Office Recordings\\Launch Codes.txt&quot;; std::cout &lt;&lt; dirPath &lt;&lt; endl; // C:\Documents\Oval Of...
<python><quotes><f-string>
2024-05-29 14:43:46
2
375,379
templatetypedef
78,550,197
5,306,861
How to see the value of a variable in WinDbg when debugging pyx?
<p>I compiled <code>pyx</code> according to the instructions <a href="https://stevedower.id.au/blog/debugging-cython-with-windbg" rel="nofollow noreferrer">here</a>, So that it can be debugged in <code>WinDbg</code>, I am now able to put a breakpoint inside the code, but the values ​​in the Locals panel do not help muc...
<python><debugging><cython><windbg>
2024-05-29 14:22:43
0
1,839
codeDom
78,550,171
788,349
Using github app to install private repos across organizations?
<p>Apologizes if this is a duplicate. I have found different variations of this all over the internet but am still having issues. See the below scenario.</p> <p>I have two github organizations.</p> <p><strong>Org1</strong> - has private <strong>Repo1</strong></p> <p><strong>Org2</strong> - has a repo that has a depende...
<python><github><pip><github-actions><github-app>
2024-05-29 14:19:11
0
513
acmisiti
78,550,109
6,379,197
Compute SHAP Value for a systems of model using shap.DeepExplainer
<p>I have trained a two-stage ML model training for binary classification. In the first stage, I applied an autoencoder model consisting of encoder and decoder. The encoder model has reduced the dimension of the input feature from 1000 to 32. The decoder reconstructs the input by increasing the input feature from 32 to...
<python><deep-learning><pytorch><shap>
2024-05-29 14:08:51
0
2,230
Sultan Ahmed
78,550,028
2,707,590
How to use XComArg in the BigQueryInsertJobOperator `params` when creating dynamic task mappings?
<p>So i have been dealing with this issue for a while now without any light... I have a DAG that queries data from BigQuery, and depending on the results some Dynamic Task Mappings are created to insert an entry in another BigQuery table using <code>BigQueryInsertJobOperator</code>...</p> <p>For Example:</p> <pre class...
<python><google-bigquery><airflow>
2024-05-29 13:54:30
0
1,146
user2707590
78,549,980
3,861,330
Create a blank page and add text content using PyPDF2: module 'PyPDF2' has no attribute 'pdf'
<p>Using this method to add create a blank page, add text to it and then append the page to a pdf.</p> <pre class="lang-py prettyprint-override"><code>def add_text_to_blank_page(pdf_writer, text): # Create a new blank page page = PyPDF2._pdf.PageObject.create_blank_page(width=612, height=792) # Standard US Let...
<python><python-3.x><pdf><pypdf>
2024-05-29 13:48:29
1
645
Dhruv
78,549,952
10,126,955
Injecting additional code in the `console_scripts` executable stub
<p>Let's say I have a pip package with an executable (<code>console_scripts</code> in <code>entry_points</code>).</p> <p>I can decide to install it in a random directory by using <code>pip install --target &lt;DIR&gt; &lt;PKG&gt;</code>.</p> <p>If I am also using a Python interpreter in a non-standard location, like fo...
<python><pip>
2024-05-29 13:43:59
0
3,610
Criminal_Affair_At_SO
78,549,723
5,170,442
why is python's zip strictness only enforced when the object is used, not created
<p>In the following example, why is the ValueError only raised on the last line rather than when <code>Z</code> is created?</p> <pre class="lang-py prettyprint-override"><code>l1 = [3] l2 = [1,2] Z = zip(l1, l2, strict=True) Zlist = list(Z) </code></pre>
<python>
2024-05-29 13:02:33
0
653
db_
78,549,656
9,494,140
docker-python error : ModuleNotFoundError: No module named '_distutils_hack'
<p>i'm running a python/django app using docker and apache2 and it was working great ,, but suddnle when I try to run again am getting this error :</p> <pre><code> Traceback (most recent call last): File &quot;&lt;frozen site&gt;&quot;, line 201, in addpackage File &quot;&lt;string&gt;&quot;, line 1, in &lt;mo...
<python><python-3.x><linux><docker><ubuntu>
2024-05-29 12:50:50
0
4,483
Ahmed Wagdi
78,549,567
9,506,773
How to extract document page associated to each chunk extracted from PDF in custom WebApiSkill
<p>I have the following <a href="https://learn.microsoft.com/en-us/azure/search/cognitive-search-custom-skill-web-api" rel="nofollow noreferrer">custom WebApiSkill</a>:</p> <pre class="lang-py prettyprint-override"><code>@app.route(route=&quot;CustomSplitSkill&quot;, auth_level=func.AuthLevel.FUNCTION) def CustomSplitS...
<python><azure-functions><azure-cognitive-services><azure-cognitive-search>
2024-05-29 12:33:28
1
3,629
Mike B
78,549,448
832,490
Langchain with Redis responding only to the previous question
<p>I am using Langchain with Redis as the persistence layer. It works, but kind of—I have a strange behavior which is as follows:</p> <p>I send a message, and it always responds to the previous prompt's message.</p> <p>I don't know what's wrong; I followed the official documentation and also looked at other code, and i...
<python><langchain><large-language-model>
2024-05-29 12:09:56
1
1,009
Rodrigo
78,549,178
12,890,458
TimestampedGeoJson with marker showing heading
<p>I want to animate a boat travelling on a route. At the moment I can show the route as a line and the boat as a circle using TimestampedGeoJson:</p> <pre><code># circle with following line features = [ { 'type': 'Feature', 'geometry': { 'type': 'LineString', 'coordinates': ...
<javascript><python><leaflet><folium>
2024-05-29 11:20:30
1
460
Frank Tap
78,549,152
12,846,524
Single log file from multiple modules with the same timestamp
<p>I know that there are many other similar questions to mine, but I have not found one that deals specifically with a log file having a timestamp as a part of its name.</p> <p>I have 4 modules (currently) that I want to implement logging within. I also have a <code>base_logger.py</code> script that I am using to creat...
<python><logging><config><python-logging>
2024-05-29 11:16:44
0
374
AlexP
78,549,141
6,145,729
Python XLSWINGS - Cannot access read-only document
<p>I'm opening an Excel file for data entry using Python Pandas &amp; Xlswings. Everything works fine as long as the Excel file is in an editable state (i.e. not opened by another user).</p> <p>Firstly, has anyone overcome the 'Cannot access read-only document' when it is being used or locked by another user? or got an...
<python><xlwings>
2024-05-29 11:14:40
0
575
Lee Murray
78,549,100
16,525,263
How to select items inside a python list and add it to a dataframe
<p>I have a pyspark dataframe with below columns</p> <pre><code>Dataframe: httpClient [capacity: string, version: string] </code></pre> <p>and I have a list of columns declared as <code>httpClient_fields = [&quot;capacity&quot;, &quot;`httpClient.install`&quot;, &quot;date&quot;]</code></p> <p>I need to check the dataf...
<python><pyspark>
2024-05-29 11:05:56
2
434
user175025
78,549,040
4,465,708
How to access the actual tab widget of ttk.Notebook?
<p>I need to access the actual tab widget that <code>ttk.Notebook</code> creates when some other widget (usually a frame) is added to it (and then called a &quot;tab&quot; in a Tkinter parlance).</p> <p>I pictured the exact thing needed below to avoid any confusion: <a href="https://i.sstatic.net/KnorFhuG.png" rel="nof...
<python><tkinter><tabs><widget><ttk>
2024-05-29 10:57:56
1
3,746
z33k
78,548,882
1,651,598
Kivy - Images appear pixelated
<p>I am using a <code>Rectangle()</code> <code>Instruction</code> added to a <code>Canvas()</code> to display a rather large .png which results in the image looking quite pixelated.</p> <p>Here is the original and the rendered version in kivy.</p> <p>Am i missing something obvious that would make the scaling &quot;this...
<python><kivy>
2024-05-29 10:25:45
0
13,598
Gung Foo
78,548,534
12,201,164
Bluetooth BTLE: how to connect reliably to device
<p>Problem: Connecting to a BTLE device succeeds about 1 out of 10 times. How can I improve this and reliably connect to the device?</p> <p>I have a <a href="https://sensirion.com/products/catalog/SHT4x-Smart-Gadget/" rel="nofollow noreferrer">Sensirion SHT41x</a> that I want to access via Bluetooth from my Windows lap...
<python><bluetooth><iot><btle><python-bleak>
2024-05-29 09:23:22
0
398
Dr-Nuke
78,548,388
232,831
force_authenticate and middlewares
<p>I'm trying to write tests using APITestCase and the provided <code>self.client</code>.</p> <p>I'm using <code>self.client.force_authenticate</code> to authenticate a user. It looks like it's handled in <code>rest_framework.request.Request</code> constructor, itself created from <code>rest_framework/views.py(391)init...
<python><django-rest-framework>
2024-05-29 08:54:26
0
12,036
Julien Palard
78,548,374
1,169,096
extract individual files from concatenated gzipped files
<p>I know that we can easily concatenate multiple gzipped files to create one big (valid) gzip file that contains all the data:</p> <pre class="lang-bash prettyprint-override"><code>gzip -c A &gt; A.gz gzip -c B &gt; B.gz cat A.gz B.gz &gt; AB.gz </code></pre> <p>If I then unzip the resulting <code>AB.gz</code>, I get ...
<python><sh><extract><gzip>
2024-05-29 08:53:03
2
32,070
umläute
78,548,098
13,987,643
Chunking text with bounding box values
<p>I have used the Azure OCR service to extract text from PDFs. For each page in a PDF, the OCR output contains a list of text lines along with the bounding box values for that line. My original approach to chunk the text in each page was to firstly combine the strings in the list of texts using &quot;\n&quot; and use ...
<python><text><nlp><langchain>
2024-05-29 07:54:48
0
569
AnonymousMe
78,547,989
11,971,720
Best way to propagate cache-control policy in a FastAPI application?
<p>Using <code>FastAPI</code> and <code>FastAPICache</code>, we can use the <code>Cache-Control</code> header to allow the API response to be force-computed or allowed to returned from a cache.</p> <p>For the endpoint as a whole, when the Cache-Control policy allows it, if the same request object is seen again, it can ...
<python><fastapi><cache-control>
2024-05-29 07:34:15
0
376
angryweasel
78,547,930
6,867,099
Show count in each histplot bin
<p>As explained in <a href="https://stackoverflow.com/questions/72206187/seaborn-histplot-print-y-values-above-each-bar">seaborn histplot - print y-values above each bar</a>, counts can be displayed on each bar in a 1-d histogram by using <code>.bar_label(ax.containers[0])</code>.</p> <p>I'm struggling to figure out ho...
<python><matplotlib><seaborn><histplot>
2024-05-29 07:23:37
2
1,950
Peter Thomassen
78,547,325
17,889,492
VS Code not selecting correct conda environment for py but works for ipynb
<p>I have a workspace with a <code>.py</code> and a <code>.ipynb</code> file. After I've selected the correct conda environment (<code>py39llm</code> ) VS Code keeps working with the base conda environment in the case of <code>.py</code> but switches to the selected python environment for <code>ipynb</code>:</p> <p>Exe...
<python><visual-studio-code><conda>
2024-05-29 04:32:37
1
526
R Walser
78,547,237
461,887
Fixing Future Warning Concat on excel files
<p>I am using glob to retrieve a list of csv files and combine them to append to excel.</p> <p>When I run the process I receive a future warning.</p> <blockquote> <p>FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty ...
<python><pandas>
2024-05-29 03:53:20
1
7,188
sayth
78,546,847
21,709,774
How do you get the StringVar (not the text value, the StringVar itself) of an Entry?
<p>I'm trying to get the StringVar object associated with an Entry widget, but I can't figure out how.</p> <p>I found this question: <a href="https://stackoverflow.com/questions/56271721/get-stringvar-bound-to-entry-widget/56272010#56272010">get StringVar bound to Entry widget</a> but none of the answers work for me. B...
<python><tkinter><tkinter-entry><ttk>
2024-05-29 00:06:42
2
308
Choosechee
78,546,844
25,091,707
Why is it vscode python could not find debugpy path when running without debugging?
<p><a href="https://i.sstatic.net/1qo8tX3L.png" rel="noreferrer"><img src="https://i.sstatic.net/1qo8tX3L.png" alt="screenshot of error message" /></a></p> <p>I'm relatively new to platforms like vscode, and I seem to run into problems whenever I try to run a python program without debugging (Ctrl + F5). A window pops ...
<python><visual-studio-code>
2024-05-29 00:05:58
2
343
Matt
78,546,774
7,846,884
How to add the filename into a new column using Polars scan_csv
<p>I'm reading multiple files with Polars, but I want to add filename as identifier in a new column.</p> <pre><code>#how to add filenames to polars lazy_dfs = (pl.scan_csv(&quot;data/file_*.tsv&quot;, separator=&quot;\t&quot;, has_header=False).fetch(n_rows= 500)) </code></pre>
<python><dataframe><csv><python-polars>
2024-05-28 23:19:04
2
473
sahuno
78,546,594
395,857
If a PyTorch model can be converted to onnx, can it always be converted to CoreML?
<p>If a PyTorch model can be converted to ONNX, can it always be converted to CoreML?</p>
<python><pytorch><coreml><onnx>
2024-05-28 22:03:10
0
84,585
Franck Dernoncourt
78,545,969
3,570,187
R workspace not loading correctly across two laptops
<p>I have recently got a new mac and I am using dropbox to sync files. I am using the online version of dropbox and I could not get the same workspace I see in my old mac. I tried downloading and it still shows the same. But when I open my old mac I get a pop up that python quit unexpectedly but I can see the:</p> <pre...
<python><r><rstudio>
2024-05-28 19:03:39
0
1,773
user3570187
78,545,940
9,135,031
Error while launching Optuna Dashboard in python
<p>I am trying to launch optuna ( <code>optuna-dashboard sqlite:///db.sqlite3</code> ) dashboard but I am receiving this error</p> <pre><code>optuna-dashboard : The term 'optuna-dashboard' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path...
<python><optuna>
2024-05-28 18:53:40
1
1,007
DrGenius
78,545,895
3,570,187
R studio unable to load properly
<p>My R studio does not load properly. When I open it I get this error.</p> <p>Any suggestions on how to handle this?</p> <pre><code> sh: line 1: 5719 Abort trap: 6 '/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4' -E -c 'import platform; print(platform.python_version())' 2&gt;&amp;1 sh: lin...
<python><r><rstudio>
2024-05-28 18:41:06
0
1,773
user3570187
78,545,846
2,463,655
Find streak of hot days based on values in another column
<p>I have a dataframe as below and I want to find streak ofh hot days.</p> <pre><code>dates = pd.date_range(start ='1-1-2018', end ='1-10-2018', freq ='1D') np.random.seed(42) temp = np.random.randint(60, 80, size=10) df = pd.DataFrame({'dates': dates, 'temp':temp}) df[&quot;is_hot&quot;] = np.where(df[&quot;temp&quot;...
<python><pandas><dataframe>
2024-05-28 18:29:14
2
2,051
rAmAnA
78,545,812
2,778,405
Verify jwt token using only hashlib
<p>I find pyJWT and other auth libraries are overly complex and, as a result, are often broken. Not to mention providers tend to add their own special steps quite often. As a result, I want to start dealing with JWT's without 3rd party libraries.</p> <p>Here is a JWT I want to verify, using only crypto libraries. It ...
<python><jwt><rsa>
2024-05-28 18:20:55
0
2,386
Jamie Marshall
78,545,774
10,765,629
Why scipy checks abs(q1) < abs(q0) before for loop in Secant method?
<p><code>scipy.optimize.newton</code> for the Secant method in <a href="https://github.com/scipy/scipy/blob/44e4ebaac992fde33f04638b99629d23973cb9b2/scipy/optimize/_zeros_py.py#L360C1-L361C1" rel="nofollow noreferrer">this line</a> checks the condition:</p> <pre><code>if abs(q1) &lt; abs(q0): p0, p1, q0, q1 = p1, p...
<python><scipy><scipy-optimize><newtons-method>
2024-05-28 18:08:54
0
710
z_tjona
78,545,763
223,201
Using the platform_release environment marker
<p>I'm developing a Python package that has an optional dependency that is incompatible with certain versions of macOS.</p> <p>Since the dependency is optional, I want my (wheel-based) package installation to succeed even on systems that have the incompatible OS.</p> <p>To achieve this, I have the following in my requi...
<python><python-3.x><bazel><python-packaging>
2024-05-28 18:05:17
0
19,362
Tom
78,545,754
1,444,609
Storing and retreiving data with Milvus and Langchain
<p>I'm trying to create a vector DB which will be populated with embeddings of articles from my employer's blog.</p> <p>I've got a Milvus instance up and running and am able to follow <a href="https://python.langchain.com/v0.1/docs/integrations/vectorstores/milvus/" rel="nofollow noreferrer">the walkthrough on the Lang...
<python><python-3.x><langchain><py-langchain><milvus>
2024-05-28 18:02:46
2
23,519
I wrestled a bear once.
78,545,622
2,016,632
Upgraded numpy and now I am overwhelmed by RuntimeWarning
<p>Just upgraded numpy to the latest intel conda's, I am at pandas 2.2.1, numpy 1.24.3 and numexpr 2.10.0</p> <p>If I try something simple like</p> <pre><code>df = pd.DataFrame(index=[0, 1, 2, 3]) df[&quot;A&quot;] = [1, 2, np.NaN, 3] print(df) </code></pre> <p>then I get five run time warnings.</p> <pre><code>RuntimeW...
<python><pandas><numpy>
2024-05-28 17:28:38
1
619
Tunneller
78,545,619
14,386,187
Redis lock is stuck on acquiring
<p>I'm trying to perform a sanity check on Redis Locks (async version):</p> <pre class="lang-py prettyprint-override"><code>import redis.asyncio as redis import tqdm import asyncio r = redis.Redis(decode_responses=True) async def update(): lock = r.lock(&quot;lock&quot;) await lock.acquire(blocking=True) ...
<python><redis><locks>
2024-05-28 17:28:15
0
676
monopoly
78,545,378
1,272,072
How to synchronise async runtimes
<p>We have a Python application that is implemented with the async runtime. Now we want to integrate a C library (with Cython) that runs its own event loop (e.g. <code>epoll</code>).</p> <p>How can we integrate these two different runtime mechanisms. Is there a general pattern to synchronise these two codebases?</p> <p...
<python><c><asynchronous><rust><epoll>
2024-05-28 16:26:47
0
963
woodtluk
78,545,368
1,422,096
How can I exclude the base directory from a recursive glob in Python?
<p>When using <code>glob.glob(&quot;D:/TEST/*&quot;)</code>, we don't get <code>D:/TEST/</code> in the result.</p> <p>With <code>glob.glob(&quot;D:/TEST/**&quot;)</code>, idem.</p> <p>But when doing <code>glob.glob(&quot;D:/TEST/**&quot;, recursive=True)</code> we get all the files and subdirectories recursively, as d...
<python><glob>
2024-05-28 16:24:00
1
47,388
Basj
78,545,208
7,307,824
Lambda layer Pandas (numpy) causing dependency error
<p>I have the following Lambda function:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def lambda_handler(events, context): d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) print(df) </code></pre> <p>I have pandas (and dependencies) included as a layer. I can see nu...
<python><pandas><numpy><aws-lambda><aws-lambda-layers>
2024-05-28 15:47:54
1
568
Ewan
78,545,168
3,348,261
Finding unused variables after minimizing
<p>After minimization (Python/scipy), I would like to know how to find unused variables in the result. Here is a simple example where the third variable is left untouched. Apart comparing initial value vs result, is there a better way to identify such variable?</p> <pre><code>from scipy.optimize import minimize def ob...
<python><scipy>
2024-05-28 15:39:53
1
712
Nicolas Rougier
78,544,956
3,628,240
Clicking a button with Selenium and Python until no longer exists
<p>I'm trying to scrape this site:<a href="https://www.vertexconnects.com/find-atc" rel="nofollow noreferrer">https://www.vertexconnects.com/find-atc</a></p> <p>I can't seem to get the while loop to continue to click the &quot;Load More&quot; button after you put in any zipcode. The code seems to be failing on the loca...
<python><selenium-webdriver><web-scraping>
2024-05-28 14:58:21
1
927
user3628240
78,544,791
9,022,641
AttributeError: Can't get attribute 'CustomActionMaskedEnvironment.observation_space' in RLlib with PettingZoo environment
<p>I have this very basic custom parallel multi agent environment written in <code>PettingZoo</code>.</p> <pre class="lang-py prettyprint-override"><code>import functools import random from copy import copy import numpy as np from gymnasium.spaces import Discrete, MultiDiscrete from pettingzoo import ParallelEnv cl...
<python><reinforcement-learning><rllib><multi-agent-reinforcement-learning><pettingzoo>
2024-05-28 14:30:45
0
734
Lukas
78,544,774
1,612,986
Update value of a nested dictionary of varying depth and same key appearing at different levels
<p>If I have a situation like:</p> <pre><code>dictionary1 = { &quot;level11&quot;: { &quot;level12&quot;: {&quot;levelA&quot;: 0, &quot;levelB&quot;: 1} } &quot;level21&quot;: { &quot;level22&quot;: { &quot;level23&quot;: {&quot;levelA&quot;: 0, &quot;levelB&quot;: 1}, ...
<python>
2024-05-28 14:27:06
2
1,415
user1612986
78,544,729
11,635,654
How to digitize large set of 3D points in 2D and compute the mean in 3rd axis to get a 2D image
<p>Here is a working Python snippet that get some 3D points (see <code>pts</code> array) and project them on a 2D image Npix x Npix keeping on the &quot;j,i&quot; pixel the mean of the third axis of all &quot;pts&quot; that are collected to that pixel. The code is probably clear.</p> <p>I have bored the way by googling...
<python><arrays><numpy>
2024-05-28 14:19:20
0
402
Jean-Eric
78,544,678
1,618,893
SQLAlchemy - Delete model classes
<p>I'm dynamically creating model classes in my unit tests using pytest, like so:</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import Column ... obj_args = { &quot;__tablename__&quot;: f&quot;t_{name}&quot;, &quot;__table_args__&quot;: {&quot;extend_existing&quot;: True}, &quot;id&q...
<python><sqlalchemy><pytest>
2024-05-28 14:10:51
1
962
Roman Purgstaller
78,544,673
10,992,342
Is there a way of creating multiple stratified samples at once?
<p>Let say I have this input dataset with the Ids: a, b, c</p> <p>I need to order it by packages of +-100 rows each sample with the same distribution of Ids as the input entire population.</p> <p>What would be the best way to do that?</p> <p><a href="https://i.sstatic.net/pi8I5pfg.png" rel="nofollow noreferrer"><img sr...
<python><statistics><sample>
2024-05-28 14:09:54
1
511
luisvenezian
78,544,510
8,040,928
Gemini API Interaction/Tutorial Setup Errors
<p>I'm trying to go through jupyter notebook tutorial: <a href="https://ai.google.dev/gemini-api/docs/get-started/tutorial?l&amp;lang=python" rel="nofollow noreferrer">https://ai.google.dev/gemini-api/docs/get-started/tutorial?l&amp;lang=python</a></p> <p>When i run Google Colab notebook everything is ok, like it shoul...
<python><jupyter-notebook><anaconda><google-colaboratory><google-gemini>
2024-05-28 13:42:52
1
603
Janek Podwysocki
78,544,319
2,123,706
search for elements of a list as substring in another list python
<p>I have 2 lists. I want to find the elements in <code>ls2</code> where any element of <code>ls1</code> is a substring. I would like to return a list of <code>ls2</code> elements along with the substring that was searched and found from <code>ls1</code></p> <pre><code>ls1 = ['apple','banana','pear'] ls2 = ['strawberry...
<python><list-comprehension>
2024-05-28 13:08:29
1
3,810
frank
78,544,277
8,329,213
Failed to display Jupyter Widgets
<p>I have installed Anaconda on my new laptop and I can't use the library <code>ipywidgets</code> any more. Just an example snippet of the code which I ran for test purposes -</p> <pre><code>import ipywidgets as widgets from IPython.display import display w = widgets.IntSlider() display(w) </code></pre> <p>I got the fo...
<python><jupyter-notebook><anaconda><ipywidgets>
2024-05-28 13:01:11
0
7,707
cph_sto
78,544,143
1,349,673
What is the proper way to handle mypy [attr-defined] errors, due to transitions dynamically adding is_* attributes?
<h1>MRE</h1> <pre><code>from transitions import Machine class TradingSystem: def __init__(self): self.machine = Machine(model=self, states=['RUNNING'], initial='RUNNING') def check_running(self) -&gt; None: if self.is_RUNNING(): print(&quot;System is running&quot;) <...
<python><mypy><python-typing><pytransitions>
2024-05-28 12:36:03
2
8,126
James Hirschorn
78,543,909
2,180,332
How can I constrain a type to be a union of subclasses in Python?
<p>I have a class, <code>Foobar</code>, with several subclasses, say <code>FoobarAlpha</code> and <code>FoobarBeta</code>.</p> <p>I know how to define a type <code>AnyFoobar = TypeVar(&quot;AnyFoobar&quot;, bound=Foobar)</code> that will match any subclass of <code>Foobar</code>.</p> <p>However, how can I define a type...
<python><mypy><python-typing>
2024-05-28 11:46:15
1
4,656
azmeuk
78,543,883
3,502,079
PyQt: transparent background but keep the frame
<p>I want to have the following: a PyQt application with a transparent background, but with the &quot;frame&quot; still visible. With frame I mean a border which you can use to resize, the titlebar and also the close and minimize button. With transparent I mean that you can see &quot;through&quot; the application, i.e....
<python><python-3.x><qt><pyqt><transparency>
2024-05-28 11:40:56
0
392
AccidentalTaylorExpansion
78,543,852
13,944,524
Description for APIRouter in FastAPI?
<p>Suppose I have the following sample code:</p> <pre class="lang-py prettyprint-override"><code>from fastapi import APIRouter, FastAPI router_one = APIRouter(tags=[&quot;users&quot;]) router_two = APIRouter(tags=[&quot;products&quot;]) app = FastAPI(description=&quot;## Description for whole application&quot;) @rou...
<python><swagger><fastapi><openapi>
2024-05-28 11:33:51
1
17,004
S.B
78,543,502
9,472,819
Pyinstaller unable to load a DLL dynamically at runtime
<p>I'm building an application that requires loading a software specific DLL at runtime. The application is built using <code>Pyinstaller</code>, but since the DLL must be loaded at runtime (depending on the user's machine, licensing), I'm unable to bundle the dll when building the application. To load the DLL, I'm doi...
<python><dll><pyinstaller><ctypes>
2024-05-28 10:29:56
0
749
tomas-silveira
78,543,163
1,860,805
Python3 stripping last binary chars
<p>There is a byte stream from socket and it comes likes this</p> <blockquote> <p>b&quot;8=FIXT.1.1\x019=000076\x0135=A\x0149=ABCD\x0156=0109\x01&quot;</p> </blockquote> <p>I need to strip the last \x01 (or \\x01)</p> <p>So here is the sample python script to demo my requirement</p> <pre><code>#!/usr/bin/python test=b&...
<python><python-3.x>
2024-05-28 09:27:30
2
523
Ramanan T
78,543,129
3,932,615
pyodbc connect to sql server with TrustServerCertificate
<p>I'm trying to connect to a SQL server instance using python and pyodbc.</p> <pre><code>cnxn = pyodbc.connect(&quot;Driver={ODBC Driver 18 for SQL Server};Server=192.168.0.1;Database=Db;User Id=Too;Password=Easy&quot;) </code></pre> <p>When I run this, I get the below error:</p> <blockquote> <p>('08001', '[08001] [Mi...
<python><sql-server><pyodbc>
2024-05-28 09:22:31
1
3,240
Neil P