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
⌀
77,606,361
12,281,892
Legend in matplotlib jumps around with minimal change to bbox_to_anchor parameters
<p>I have this issue in matplotlib that drives me crazy. I want to position the legend within the plot to be in a certain position, for example, in this case, in the top left corner (matching the corner of the plot). I do not want to use the <code>loc</code> parameter as it doesn't give me the exact location I want. To...
<python><matplotlib><legend>
2023-12-05 12:55:36
1
2,550
My Work
77,606,224
5,238,639
Snowflake : vectorized Python UDTFs with pandas dataframe as input with variable number of columns
<p>I have a usecase where the i need to create a vectorized UDTF on a pandas dataframe. This dataframe can have different columns from time to time as it is preprocessed data.</p> <p>I was looking at the example in <a href="https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-tabular-vectorized#example-c...
<python><snowflake-cloud-data-platform><user-defined-functions>
2023-12-05 12:33:43
1
4,503
prashanth
77,606,194
521,347
Snyk reporting vulnerabilities in Apache-Beam 2.52.0
<p>We have Snyk integrated with our Python repository to identify any vulnerabilities in any of the libraries we are using. I am trying to add the dependency of apache-beam 2.52.0 (latest version) to pyproject.toml file. However, Synk is reporting a vulnerability during the build process in pyarrow 11.0.0 which Apache...
<python><google-cloud-dataflow><apache-beam><snyk>
2023-12-05 12:29:22
1
1,780
Sumit Desai
77,605,960
19,369,310
Comparing value of one column with the next row in another column in pandas dataframe
<p>I have the following large dataset recording the result of a math competition among students in descending order of date: So for example, student 1 comes third in Race 1 while student 3 won Race 2, etc.</p> <pre><code>Race_ID Date adv C_k 1 1/1/2023 2.5 2.7 1 ...
<python><python-3.x><pandas><dataframe><group-by>
2023-12-05 11:50:06
1
449
Apook
77,605,928
3,745,149
TypeError: cannot pickle '_thread.lock' object when wrapping Pytorch Distributed Data Parallel in a class
<p>Here is a minimal code:</p> <pre><code>import threading import torch class DistributedMission: def __init__(self): self.lock = threading.Lock() self.world_size = 8 def start(self): torch.multiprocessing.spawn(self.worker, args=(), nprocs=self.world_size, join=True) def worker(sel...
<python><multithreading><pytorch><spawn><multi-gpu>
2023-12-05 11:46:02
0
770
landings
77,605,926
9,196,760
Does nest js provide anything that runs after saving, updating or deleting, like how django signals provides?
<p>I am running a project with nest js and prisma orm. Suppose I am creating a post record like following:</p> <pre><code> // Query the database to create post ------------------------------------------------------- try { post = await this.prisma.post.create({ data: { ...
<python><django><nestjs><prisma><django-signals>
2023-12-05 11:45:38
1
452
Barun Bhattacharjee
77,605,641
963,165
How do I Configure and Initialize Python.NET in a C# Console App on Linux containerized with Docker?
<p>I am trying to run a C#/.NET console application that uses the Python.NET library to interpret Python scripts at runtime. I want this app to run on Linux with a Docker container.</p> <p>The problem I am having is that Python.NET requires you to initialize the <code>Runtime.PythonDLL</code> property with the path to ...
<python><c#><linux><docker><python.net>
2023-12-05 10:55:59
0
552
Jim Noble
77,605,480
3,973,269
Color around the figure in python plot (matplotlib)
<p>I have a matlab 3d barplot and within the grid, I understand that there is a background color. However, that color seems to extend outside the grid aswell forming a gray-ish square. I would like to get rid of that since it doesn't make sense and ht is odd with the text around it. Especially around the right side, th...
<python><matplotlib><plot><3d>
2023-12-05 10:30:08
1
569
Mart
77,605,418
13,919,925
How to get JWK URL for epic fhir resources?
<p>Im using open epic documentation (<a href="https://fhir.epic.com/Documentation?docId=oauth2" rel="nofollow noreferrer">https://fhir.epic.com/Documentation?docId=oauth2</a>) I'm able to create application But in bottom it asked me upload public key and also add jwk url (which is not required) but for accessing the pu...
<python><hl7-fhir><jwk><smart-on-fhir>
2023-12-05 10:21:50
1
302
sandeepsinghnegi
77,605,362
12,415,855
How to get HTML when requesting this website?
<p>I try to parse the HTML content using the following code:</p> <pre><code>import requests from bs4 import BeautifulSoup url = &quot;https://www.thespruce.com/christmas-village-display-ideas-8407777&quot; page = requests.get(url) soup = BeautifulSoup (page.content, 'lxml') print(soup.prettify()) </code></pre> <p>But ...
<python><web-scraping><beautifulsoup><python-requests>
2023-12-05 10:13:45
1
1,515
Rapid1898
77,605,326
5,763,590
Streamlit pdf file cannot be opened after downloading with st.download_button
<p>I want to download a pdf on button click in my streamlit application. I am using <a href="https://docs.streamlit.io/library/api-reference/widgets/st.download_button" rel="nofollow noreferrer"><code>st.download_button</code></a>, like this:</p> <pre><code>st.download_button( label=&quot;Download&quot;, ...
<python><pdf><download><streamlit>
2023-12-05 10:06:12
1
10,287
mrk
77,605,270
7,425,726
Find the closest distance between points following a set of LineStrings
<p>I have two datasets of Point coordinates (representing electrical installations) and would like to find the closest match between the two datasets following a given set of LineStrings (representing the cables). As an example let's take the following situation:</p> <pre><code>points1 = gpd.GeoDataFrame({'geometry' : ...
<python><geopandas><shapely>
2023-12-05 09:57:38
2
1,734
pieterbons
77,605,261
14,430,730
What if a Typer command returns a value
<p>I'm using <a href="https://typer.tiangolo.com/" rel="noreferrer">Typer</a> to implement a CLI tool. For testing purpose, I'd like some commands return some value, but I'm not sure whether it's safe. I didn't find anything related in its <a href="https://typer.tiangolo.com/" rel="noreferrer">user guide</a>.</p> <p>As...
<python><typer>
2023-12-05 09:55:42
2
336
XuanInsr
77,605,089
8,087,322
__init__ in overridden classmethod
<p>I have a small class hierarchy with similar methods and <code>__init__()</code>, but slightly different static (class) <code>read()</code> methods. Specifically will the child class need to prepare the file name a bit before reading (but the reading itself is the same):</p> <pre class="lang-py prettyprint-override">...
<python><class-method>
2023-12-05 09:31:03
1
593
olebole
77,605,033
9,827,719
Python 3.12 does not support the package cloud-sql-python-connector on Windows 11
<p>I have upgraded from Python 3.11 to Python 3.12. After I have upgraded I am unable to install the package &quot;cloud-sql-python-connector&quot;.</p> <p>My colleague confirmed that he can install it on Python 3.11, but not 3.12.</p> <p><strong>requirements.txt</strong></p> <pre><code>cloud-sql-python-connector flask...
<python>
2023-12-05 09:21:31
1
1,400
Europa
77,604,957
22,538,132
How to measure inner dimensions of noisy bin box using histogram
<p>I have a bin box where the orientation is considered to be zero in all directions, and I want to measure the inner dimensions of the box using histograms of x, y , and z.</p> <p><a href="https://i.sstatic.net/KjtQK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KjtQK.png" alt="box" /></a></p> <p><a h...
<python><numpy><histogram><measure>
2023-12-05 09:04:36
1
304
bhomaidan90
77,604,930
9,974,205
Problem specifying an objective function in optimization problem
<p>I have the following optimization problem written in Python</p> <pre><code>from pulp import LpProblem, LpVariable, lpSum, LpMaximize # Person i in group j x = {(i, j): LpVariable(cat=&quot;Binary&quot;, name=f&quot;x_{i}_{j}&quot;) for i in result_sum.index for j in result_sum.index} # group j exists y = {j: LpV...
<python><matrix><optimization><compiler-errors><pulp>
2023-12-05 08:59:58
1
503
slow_learner
77,604,929
832,490
How to call asynchronous functions in cascade?
<p>Given the following code, I would like to know if there is a way to reduce it to a single line without using parentheses to resolve the promise.</p> <pre><code>context = await browser.new_context( viewport={ &quot;width&quot;: 1600, &quot;height&quot;: 1200, }, device_scale_factor=2, ) p...
<python><python-asyncio>
2023-12-05 08:59:41
1
1,009
Rodrigo
77,604,841
4,451,521
Finding equal intervals for two divided ranges
<p>I have been scratching my head trying several approaches without success. I have four values <code>min1,max1,min2,max2</code> and the condition is that <code>min2&gt;max1</code></p> <p>This values can be negatives, can be floats.</p> <p>I want to subdivide these into subintervals with the conditions:</p> <ol> <li>th...
<python><numpy>
2023-12-05 08:45:12
0
10,576
KansaiRobot
77,604,743
7,158,719
Is there a way to access pysparks executors and send jobs to them manually via Jupyter or Zeppelin notebook?
<p>Probably just a pipe dream, but is there a way to access pysparks executors and send jobs to them manually in a Jupyter or Zeppelin notebook?</p> <p>It probably goes against all pyspark convention as well, but the idea is to access a running EMR clusters executors(workers) and send them python scripts to run. Sort o...
<python><apache-spark><pyspark><jupyter-notebook>
2023-12-05 08:29:15
2
547
Ranald Fong
77,604,519
7,988,415
How to reload a class imported from a module in python console?
<p>The way I imported it:</p> <pre class="lang-py prettyprint-override"><code>from my_package.my_module import My_Class </code></pre> <p>Here, <code>my_package</code> is a subdirectory in my current project with an empty <code>__init__.py</code> in it.</p> <p>Then I edited <code>My_Class</code> and wanted to reload it ...
<python><class><import><module>
2023-12-05 07:37:59
0
1,054
Alex
77,604,473
12,875,947
Ubuntu is not serving Static files from Django project. Getting Permission issue
<p>[Updated status]: It has been resolved by Updating the permission of root folder. update the user in nginx.conf with user can be option but I have not tried this one.</p> <p>===== Actual Question============</p> <p>I have a django project deployed on Ubuntu 23.04 and using nginx and gunicorn to serve the website. St...
<python><django><ubuntu><nginx><gunicorn>
2023-12-05 07:28:15
1
1,886
Narendra Vishwakarma
77,604,377
2,587,904
Harmonizing data spread over multiple rows with duplicate values for some keys
<p>I face data spread over multiple columns.</p> <p>Some rows hold duplicate data for a key. Some semantically similar data Others new fresh data (sometimes only for different keys - however sometimes also for the same key)</p> <p>What could be a great strategy to make this data accessible? I want to have one row for t...
<python><apache-spark><nested><primary-key><data-cleaning>
2023-12-05 07:07:51
1
17,894
Georg Heiler
77,604,022
13,803,549
Is it possible to have a conditional statement distinguish which model a Python variable is coming from?
<p>In my Django view I have 3 models and I want to execute some code based condition from where a variable is coming from.</p> <p>I have tried...</p> <pre class="lang-py prettyprint-override"><code> if (type(variable)) is ModelA: do this... </code></pre> <p>If I do <code>print(type(variable))</code> I am ex...
<python><sql><django>
2023-12-05 05:39:03
1
526
Ryan Thomas
77,603,720
9,536,653
How can I retreive the main body of a question using the StackExchange API? I can only retreive the title of a question
<pre><code>import requests, openai # Set your Stack Exchange API key stack_exchange_api_key = 'your_stack_exchange_api_key' # Set your OpenAI API key openai.api_key = 'your_openai_api_key' # Step 1: Retrieve new unanswered questions with the Python tag from Stack Exchange API # Set parameters for Stack Exchange API...
<python><json><python-requests><openai-api>
2023-12-05 03:52:24
1
566
Derek M. D. Chan
77,603,409
13,882,618
How can I put an action that applied on every exception in python?
<p>I wrote something similar to the following code, and there is duplicated code (process_error) on every exception. But there are duplications.</p> <pre><code>try: do_something() ... except KeyError: process_error() ... except ValueError: process_error() ... except: process_error() ... ...
<python><exception><code-duplication>
2023-12-05 01:45:21
0
401
jolim
77,603,135
3,170,530
How can I roll a matrix in Tensorflow but set a different roll value for each index?
<p>Suppose I have the following matrix in tensorflow:</p> <pre><code>[[0, 1, 2], [3, 4, 5], [6, 7, 8]] </code></pre> <p>I would like to roll the matrix by <code>[0, 1, 2]</code> along axis 1, meaning the result matrix should be:</p> <pre><code>[[0, 1, 2], # row 0 rolled by 0 - unchanged [5, 3, 4], # row 1 rolle...
<python><tensorflow><matrix>
2023-12-04 23:47:31
0
448
user3170530
77,603,017
252,464
How can I extract certain qualified nodes from a yaml document and add to a new document using PyYAML?
<p>I'm new with both Python and YAML (great with Javascript and JSON) and I need to construct a subset of a YAML file. In particular, I want to generate a .yaml file that can be used to create a new deployment in openshift/kubernetes, gleaning the needed information from running pods/deployments. The YAML file will hav...
<python><kubernetes><openshift><pyyaml>
2023-12-04 23:06:53
1
1,969
svenyonson
77,603,014
4,431,535
How do I use mypy to annotate a numpy array containing a custom dtype?
<p>I have a custom numpy dtype that will be used in numpy arrays. How should I annotate the array variable in a function declaration in order to capture the type constraint? I'm guessing I need to better annotate the dtype declaration itself, but am not sure how.</p> <p>As an example, please consider this script:</p> <...
<python><arrays><numpy><mypy><dtype>
2023-12-04 23:05:51
0
514
pml
77,602,906
11,850,322
Jupyter run all - then pause for choice to continue
<p>I want to add some Dropdown widgets in my jupyternotebook, then Run all. The program should pause at the Dropdown widgets to wait for me to choose and confirm before it can continue to run</p> <p>I want to do this rather than keep pressing Shift+Enter</p> <p>The structure is something like this:</p> <p><code>cell1</...
<python><python-3.x><jupyter-notebook>
2023-12-04 22:32:08
0
1,093
PTQuoc
77,602,904
7,563,454
Python: Import script in a way that doesn't require writing its name before the class name
<p>I have a python file called <code>lib.py</code> which contains custom types I use in my project, for example an x + y + z vector registered as <code>vec3</code>:</p> <pre><code>class vec3: def __init__(self, x: float, y: float, z: float): self.x = x self.y = y self.z = z </code></pre> <p>...
<python><python-3.x>
2023-12-04 22:31:57
1
1,161
MirceaKitsune
77,602,885
1,519,058
Merge dataframe using common keys
<p>I've been trying to merge two dataframes so that:</p> <ul> <li>data with common keys will get updated =&gt; new column added with the additional value</li> <li>data with no common keys will be added as new rows (see sample below)</li> </ul> <p>I have been testing with both <code>merge</code> and <code>concat</code> ...
<python><python-3.x><pandas><dataframe><merge>
2023-12-04 22:26:06
3
4,963
Enissay
77,602,632
8,232,290
Why does 101010 return `True` when the expression`str(000) in str(101010)` is evaluated in Python?
<p>I'm working on <a href="https://leetcode.com/problems/largest-3-same-digit-number-in-string/?envType=daily-question&amp;envId=2023-12-04" rel="nofollow noreferrer">this LeetCode problem here</a>, and I'm implementing a brute force approach as well as an iterative approach. The iterative approach works fine, but my b...
<python><in-operator>
2023-12-04 21:22:19
3
503
AndreasKralj
77,602,598
19,130,803
python: return list from generator function
<p>I have simple function that I am trying to convert into generator that return batch output. Here is code</p> <pre><code># Simple function, working but too slow once get big list def compute_add(): data = range(5) cases = list(itertools.permutations(data, 2)) print(f&quot;{cases=}&quot;) result = ...
<python>
2023-12-04 21:14:31
2
962
winter
77,602,568
8,372,455
compile Python code to WebAssembly for non-web environments
<p>I'm currently exploring if I can use a Python-based BACnet stack due to its reliability and effectiveness in conjunction with the possibility of leveraging Rust for its WebAssembly (WASM) capabilities, particularly in a non-web browser environment for IoT purposes <a href="https://webassembly.org/docs/non-web/" rel=...
<python><rust><iot><webassembly><bacnet>
2023-12-04 21:08:02
0
3,564
bbartling
77,602,463
885,650
pip install can't find a package during build even though it's installed
<p>During pip install of a local package, which uses custom code for building, I am getting the following error:</p> <pre><code>python3 -m pip install -vvv . ... Created temporary directory: /tmp/pip-unpack-g_w7p_yj Building wheels for collected packages: mypackagename Created temporary directory: /tmp/pip-wheel-2p3...
<python><python-3.x><pip>
2023-12-04 20:46:35
1
2,721
j13r
77,602,318
2,031,442
How can I use python and selectolax to extract multiple CSS tags with the same name
<p>I'm trying to learn basic web-scraping and have came across an issue I can't figure out out. Basically I found a site that lists a retail price, and sale price but the both have the class of &quot;price&quot;</p> <p>Looking for some pointers to get me back on track. Thanks.</p> <p>What I would like to do is be abl...
<python><web-scraping><beautifulsoup>
2023-12-04 20:14:06
1
685
digital_alchemy
77,602,160
3,458,788
Using map with pd.DataFrame
<p>I am writing a function that I would like to return a <code>pd.DataFrame()</code> and I would then like to use this function with <code>map</code>. I would then like to join these DataFrames to have one big DataFrame. Here's an example (note that this is not my problem I'm trying to solve, but just a toy problem):</...
<python><pandas><dataframe>
2023-12-04 19:41:38
0
515
cdd
77,601,975
2,990,266
How to make Pandas bar char add X axis labels to transposed dataframe?
<p>I bar chart that I am creating with Pandas. The plot display the label on the X axis. How do I get the chart to display the expected labels?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd metrics_1_csv = Path(&quot;/tmp/metrics_2.csv&quot;) print(&quot;reading&quot;, metrics_1_csv) df = pd....
<python><pandas><charts>
2023-12-04 19:05:46
1
2,025
Aage Torleif
77,601,763
9,032,335
Error when reading a parquet file with polars which was saved with pandas
<p>I'd like to read a parquet file with polars (0.19.19) that was saved using pandas (2.1.3).</p> <pre><code>test_df = pd.DataFrame({&quot;a&quot;:[10,10,0,100,0]}) test_df[&quot;b&quot;] = test_df.a.astype(&quot;category&quot;) test_df.to_parquet(&quot;test_df.parquet&quot;) test_pl_df = pl.read_parquet(&quot;test_df...
<python><dataframe><parquet><python-polars>
2023-12-04 18:21:22
1
723
ivegotaquestion
77,601,287
4,465,454
"No parameter named table" in SQLModel
<p>The SQLModel <a href="https://sqlmodel.tiangolo.com/tutorial/insert/" rel="nofollow noreferrer">documentation</a> tells us that we should define a mapped table as follows:</p> <pre><code>from typing import Optional from sqlmodel import Field, SQLModel class Hero(SQLModel, table=True): id: Optional[int] = Fiel...
<python><sqlalchemy><pydantic><sqlmodel>
2023-12-04 17:07:10
1
1,642
Martin Reindl
77,601,218
12,596,824
Llama Index custom embeddings - difference between getting text embeddings vs query embeddings?
<p>I'm looking here at the Llama index documentation to create custom embeddings: <a href="https://docs.llamaindex.ai/en/stable/examples/embeddings/custom_embeddings.html" rel="nofollow noreferrer">https://docs.llamaindex.ai/en/stable/examples/embeddings/custom_embeddings.html</a></p> <p>I'm confused at the documentati...
<python><nlp><llama-index>
2023-12-04 16:56:57
1
1,937
Eisen
77,601,217
12,016,688
Shouldn't importing print_function change the keyword.kwlist in python2?
<p>In <code>python-2.7</code>, shouldn't the <code>keyword.kwlist</code> be updated after importing <code>print_function</code> from <code>__future__</code>?</p> <pre class="lang-py prettyprint-override"><code>Python 2.7.18 (default, Feb 1 2021, 00:00:00) [GCC 10.2.1 20201125 (Red Hat 10.2.1-9)] on linux2 Type &quot;...
<python><python-2.x><keyword>
2023-12-04 16:56:40
0
2,470
Amir reza Riahi
77,601,164
9,974,205
Looking for ways of clustering data acording to distance
<p>I have a pandas dataframe defined as</p> <pre><code> Alejandro Ana Beatriz Jose Juan Luz Maria Ruben Alejandro 0.0 0.0 1000.0 0.0 1037.0 1014.0 100.0 0.0 Ana 0.0 0.0 15.0 0.0 100...
<python><pandas><optimization><cluster-analysis><heuristics>
2023-12-04 16:47:42
1
503
slow_learner
77,600,799
3,336,423
Python how to run unit tests from different packages?
<p>Here is my folder structure:</p> <pre><code>src/ src/package1 src/package1/package1 src/package1/package1/__init__.py src/package1/package1/class_package1.py src/package1/package1/test_package1.py src/package2 src/package2/package2 src/package1/package2/__init__.py src/package2/package2/class_package1.py src/package...
<python><python-unittest>
2023-12-04 15:49:28
0
21,904
jpo38
77,600,625
7,563,454
Python, tkinter: How do I snap the mouse pointer to the center of a window?
<p>I need to create a window in Python, the best way by far is tkinter so I went with that. Mouse looking is going to be used: I need to make it so my mouse cursor is always snapped to the center of this window after calculating movement. I looked at every solution but can't get this seemingly simple thing to work. I p...
<python><python-3.x><tkinter><tk-toolkit>
2023-12-04 15:25:39
2
1,161
MirceaKitsune
77,600,509
1,014,217
validation error for RetrievalQA retriever value is not a valid dict (type=type_error.dict)
<p>I am trying to create a custom filtered retriever to solve: <a href="https://github.com/langchain-ai/langchain/issues/14227" rel="nofollow noreferrer">https://github.com/langchain-ai/langchain/issues/14227</a></p> <p>So my code is:</p> <pre><code>class FilteredRetriever: def __init__(self, retriever, title): ...
<python><langchain>
2023-12-04 15:09:56
0
34,314
Luis Valencia
77,600,448
14,175,601
Efficient way to list parquet file partitions in python
<p>I have a partitioned parquet file that I want to read each partition iteratively.</p> <p>However, I want to get the list of partitions first.</p> <p>In this example I would like to get the list <code>[1, 2]</code>:</p> <pre><code>myparquet.parquet - /partition_col=1/file1 - /partition_col=2/file2 </code></pre> <p>Fo...
<python><pandas><parquet><pyarrow>
2023-12-04 15:01:04
2
1,653
ronkov
77,600,270
4,451,521
Finding a point close enough to a point
<p>I have a problem with some peculiar characteristics.</p> <p>I have:</p> <ul> <li><p>a point P (well in reality it is an array of points <code>ArrayP</code>, but the function I want to write is applied to each and every point, so it receives each time <em>one</em> point)</p> </li> <li><p>an array of other points (whi...
<python><euclidean-distance><closest-points>
2023-12-04 14:36:09
1
10,576
KansaiRobot
77,600,048
13,641,064
Azure function - Logging to Azure blob with python
<p>I have an Azure function where I tried multiple ways to write/log, my python script logs to an Azure blob. However, I can't seem to make it work, even <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=asgi%2Capplication-level&amp;pivots=python-mode-decorators#logging" r...
<python><azure><logging><azure-functions>
2023-12-04 14:05:31
2
442
Collega
77,599,954
4,470,831
Django capture traces of Open Telemetry
<p>I am a newbie to Open Telemetry and trying to see how traces are captured for a Django app. I am assuming that OTel should be able to provide traces of all invoked functions for a particular Django Request. E.g.I have a very basic Django app with a views.py as</p> <pre><code> def log_console(): print(&quot;Print...
<python><django><open-telemetry><open-telemetry-collector>
2023-12-04 13:51:29
0
552
H D
77,599,953
1,613,749
Malformed node in ast.literal_eval call
<p>It is my understanding that <code>ast.literal_eval</code> works with literals, so why does this give me an error?</p> <pre class="lang-py prettyprint-override"><code>import ast ast.literal_eval(&quot;1+2&quot;) </code></pre> <p>The error:</p> <pre><code>Traceback (most recent call last): File &quot;/snap/pycharm-...
<python><python-3.x><eval>
2023-12-04 13:51:28
2
4,166
SamuelNLP
77,599,944
6,653,602
Speeding up INSERT Query of a Pandas Dataframe into MySQL Database
<p>I am using simple <code>to_sql</code> pandas method to save dataframe into MySQL database:</p> <pre><code>engine = create_engine('mysql+mysqlconnector://xxxx:xxxxx@localhost:3306/db_qa') df.to_sql('my_table', con=engine, if_exists='replace', index=False, chunksize=120, method='multi') </code></pre> <p>However, this...
<python><mysql><pandas><google-cloud-platform>
2023-12-04 13:50:09
1
3,918
Alex T
77,599,671
1,821,450
Is there a way to mass-identify typos in methods in VS Code?
<p>I noticed that, when typing a method from a different class in VS Code, if you type in an incorrect method name or a missing method, VS Code will highlight it in white. If the method is yellow that means that the method name is correct.</p> <p>Is there any way to do this on a project scale so you can catch any error...
<python><visual-studio-code>
2023-12-04 13:09:16
1
2,185
Dr. Chocolate
77,599,660
832,490
How to obtain a user's profile picture using only their @handler
<p>I have a Python bot for Telegram, and the idea, to summarize, is that given a user input containing mentions, I would like to obtain either the photo of the mentioned user or their user.id. I have a code that works for users without a handler, but I would like to find a way that works for all users.</p> <pre><code>e...
<python><telegram><python-telegram-bot>
2023-12-04 13:07:24
1
1,009
Rodrigo
77,599,646
1,213,934
Field in Document possible being a list and and object
<p>I have some legacy MongoDB collection that has a particular field that can be null, a list (<code>[]</code>) and an object with a particular list of fields. I'm trying to implement the basic Document that allows this behavior.</p> <p>I tried using this approach:</p> <pre class="lang-py prettyprint-override"><code>cl...
<python><mongoengine>
2023-12-04 13:05:23
1
3,452
logoff
77,599,639
13,550,050
Data dependencies and caching
<p>I have a complex python function which computes a level based on various sub functions and data dependencies.</p> <p>What are the best ways to control the data dependencies and have reproducible calculations?</p> <p>The data can come from external data bases and data sources, so potentially they can change when the ...
<python><dependency-injection><functional-programming><dependencies>
2023-12-04 13:03:31
1
369
crixus
77,599,318
3,155,966
Generate static/complete `.rst` files with autodoc
<p>is there a way to make <code>sphinx-apidoc</code> (by using the <code>autodoc</code> extension) generate fully static <code>.rst</code> files with the complete documentation content (docstrings) directly embedded in them?</p> <p>For example, given a <code>foo.py</code> module with one fuction:</p> <pre class="lang-p...
<python><python-sphinx><autodoc><sphinx-apidoc>
2023-12-04 12:07:27
0
347
Low Yield Bond
77,599,292
9,020,273
How to get a list of mounted sub applications from a FastAPI app?
<p>I have a FastAPI app with a few mounted <a href="https://fastapi.tiangolo.com/advanced/sub-applications/" rel="nofollow noreferrer">sub applications</a>, and would like to know if there is a <code>app.subapps()</code> or similar method to give me the instances of sub applications mounted to the main app.</p> <p>Than...
<python><fastapi><starlette>
2023-12-04 12:03:39
1
1,315
Jamie J
77,599,120
18,360,265
How to get api req as cURL and print on terminal using python?
<p>I am trying to scrap a website by intercepting http network calls using <code>playwright</code> python module.</p> <p>I want to get the cURL from network call.</p> <p>something like this, we do it manually. To copy the cURL of API call.</p> <p><a href="https://i.sstatic.net/2ONDz.png" rel="nofollow noreferrer"><img ...
<python><web-scraping><playwright-python>
2023-12-04 11:38:06
1
409
Ashutosh Yadav
77,598,964
18,904,265
How do I effectively share the database engine between different instances of a DB class?
<p>Preamble: Not sure if this kind of question belongs to stackoverflow or Software Engineering, please tell me if I'm at the wrong place.</p> <h2>The issue</h2> <p>I am working on a DB-wrapper for a CLI-app. For using that wrapper (a class), I want to instantiate it only once for each table I want to map. The version ...
<python><sqlalchemy><orm><sqlmodel>
2023-12-04 11:12:23
1
465
Jan
77,598,864
243,031
Secure connection between django and mysql
<p>We have Django application and we are configuring <code>ssl</code> in the <code>DATABASES</code> settings in <code>settings.py</code>.</p> <p><strong>settings.py</strong></p> <pre><code>DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' DATABASES['default']['NAME'] = 'database' DATABASES['default']['HOST'] ...
<python><mysql><django><insecure-connection>
2023-12-04 10:52:24
0
21,411
NPatel
77,598,815
10,353,865
tf-neural network not working - pytorch does
<p>I have created a tiny dataset where an exact linear relationship holds. The code is as follows:</p> <pre><code>import numpy as np def gen_data(n, k): np.random.seed(5711) beta = np.random.uniform(0, 1, size=(k, 1)) print(&quot;beta is:&quot;, beta) X = np.random.normal(size=(n, k)) y = X.dot(bet...
<python><tensorflow><neural-network>
2023-12-04 10:46:42
1
702
P.Jo
77,598,668
12,415,863
convert list into list of lists: each sublist is a different length, and method of filling sublists is different
<p>input I have:</p> <p><code>big_list = [1,2,3,4,5,6,7,8]</code></p> <p>output I want:</p> <p><code>list_of_lists = [[1],[2,5][3,6,8],[4,7]]</code></p> <p>I have manually defined the output I need as a list-of-lists as the following:</p> <ul> <li>1st sublist length = 1</li> <li>2nd sublist length = 2</li> <li>3rd subl...
<python><list>
2023-12-04 10:23:10
1
301
abra
77,598,619
17,136,258
Create waterfall chart
<p>I have a problem. I want to create a waterfall chart. But Unfortunately it does not look correctly what I want. For example the numbers are not correctly placed and the text is missing at the end. And beside it want to create a line, that it shows more the waterfall.</p> <p>How can I create the waterfall chart more ...
<python><pandas><dataframe><matplotlib><seaborn>
2023-12-04 10:14:52
3
560
Test
77,598,509
12,978,930
JAX-metal error: 'anec.reshape' op failed: input tensor dimensions are not supported on ANEs
<p>I just tested <a href="https://developer.apple.com/metal/jax/" rel="nofollow noreferrer"><code>jax-metal</code></a> on my M1 Max MacBook Pro. However, I already get a warning when loading the MNIST dataset as follows.</p> <pre class="lang-py prettyprint-override"><code>import gzip import os import struct import urll...
<python><tensorflow><metal><jax>
2023-12-04 09:55:03
0
12,603
Hericks
77,598,507
6,394,722
How to make ElementTree parse XML without changing namespace declarations?
<p>I have next xml:</p> <p><strong>data3.xml:</strong></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;feed xmlns=&quot;http://www.w3.org/2005/Atom&quot;&gt; &lt;entry&gt; &lt;content&gt; &lt;ns2:executionresult xmlns:ns2=&quot;http://jazz....
<python><xml><elementtree><xml-namespaces>
2023-12-04 09:54:37
1
32,101
atline
77,598,018
4,640,936
odoo 16 create a link that opens in set company
<p>what i am trying to do is create link that will open a set company. now when i create the url using base_url with a link to a record it tries to open in the current company and so gives an access error.</p> <p>Thank you for your suggestions.</p> <pre><code> def make_record_link(self, record='', action='', menu=''): ...
<python><odoo><odoo-16>
2023-12-04 08:14:01
1
740
Moaz Mabrok
77,597,847
684,883
How to declare Enum and Custom classes in numba jitclass spec?
<p>I am trying out numba (v0.56.4), I have a python enum Color, I want to declare it in @jitclass spec for class Paint. Can you please let me know the right way to declare it?</p> <pre><code>class Color(Enum): RED = 1 BLUE = 2 GREEN = 3 spec = [('name': types. String), ('color': Color)] @jitclass(spec) cl...
<python><numba>
2023-12-04 07:41:06
1
1,355
Yogesh
77,597,489
1,080,517
Extract trigger words from safetensors file
<p>With many <code>.safetensors</code> files associated to different LoRA authors sometimes specify &quot;trigger words&quot;. I've been trying to extract find the way to extract them from <code>.safetensors</code> file but I cannot find them. They are not present in metadata section and according to documentation I ca...
<python><safe-tensors>
2023-12-04 06:08:27
1
2,713
sebap123
77,597,141
17,800,932
MyPy not ignoring `valid-type` error code for type aliases
<p>Python 3.12 added support for type aliases as defined in <a href="https://peps.python.org/pep-0695/" rel="nofollow noreferrer">PEP 695</a>. MyPy does not support this, as discussed in <a href="https://github.com/python/mypy/issues/15238" rel="nofollow noreferrer">https://github.com/python/mypy/issues/15238</a>. Howe...
<python><mypy><python-typing><python-3.12>
2023-12-04 03:52:13
0
908
bmitc
77,596,665
5,775,965
Calling Python code in Swift Callback from Python called from Swift
<p>Pardon the confusing title but I am doing something truly cursed.</p> <p>I have a large project written in Python that I want to write a GUI in Swift for. I'm able to use PythonKit to call my Python code from Swift just fine.</p> <p>The only problem is that the Python program deals with laying out the UI elements si...
<python><swift><ffi><swift-pythonkit>
2023-12-04 00:23:11
0
1,159
genghiskhan
77,596,649
6,379,348
Validation errors for LLMChain when use langchain/openai for text generation
<p>I just started learning langchain. I was trying to use langchain and openai for text generation. Codes below. (I use python 3.10):</p> <pre><code>#openai==1.3.5 #langchain==0.0.345 from transformers import pipeline from langchain import PromptTemplate, LLMChain, OpenAI import os os.environ['OPENAI_API_KEY'] = '**...
<python><openai-api><langchain><py-langchain>
2023-12-04 00:17:02
1
11,903
zesla
77,596,591
1,476,044
Is MLPClassifier Appropriate for Binary Classification?
<p>I've written a program that uses MLPClassifier to solve a binary classification problem. It sort of works but I am not convinced this is the right model to use.</p> <p>I have 1300 hextuples of integers to put into one of two classes: class 0 and class 1. A potential issue is that in my training data, 98% are in clas...
<python><machine-learning><scikit-learn>
2023-12-03 23:53:22
0
397
user1476044
77,596,485
13,497,079
'anyio' has no attribute 'start_blocking_portal'
<p>One of my fast api endpoints is supposed to return a csv response. I try to check this endpoint but I get this error</p> <pre><code>self = &lt;starlette.testclient.TestClient object at 0x7f834a5f6ec0&gt; @contextlib.contextmanager def _portal_factory( self, ) -&gt; typing.Generator[anyio.abc.Blo...
<python><pytest><fastapi><starlette><anyio>
2023-12-03 23:01:12
1
534
Potis23
77,596,388
295,930
Loading a Python pickle slows down in a for loop
<p>I have a 25GB pickle of a dictionary of numpy arrays. The dictionary looks like the following:</p> <ul> <li>668,956 key-value pairs.</li> <li>The keys are strings. Example key: <code>&quot;109c3708-3b0c-4868-a647-b9feb306c886_1&quot;</code></li> <li>The values are numpy arrays of shape <code>200x23</code>, type <co...
<python><pickle>
2023-12-03 22:25:49
1
486
The Salt
77,596,323
10,749,925
How do I run the following Python and Boto3 code?
<p>I'm trying to explore machine learning models from AWS. AWS recently released a Bedrock service, and I would like to setup an environment to do that. I would also need to interact with S3, Langchain and Vector databases (e.g.Pinecone). There's a bit of an idea here on what i'd likely be playing with and i'd try to f...
<python><amazon-web-services><machine-learning><boto3><aws-cli>
2023-12-03 22:03:30
0
463
chai86
77,596,284
17,800,932
How do I document a type alias defined using `type` in Python?
<p>Python 3.12 has the <a href="https://docs.python.org/3/reference/simple_stmts.html#type" rel="noreferrer"><code>type</code></a> statement. How do I document the type alias properly?</p> <p>I tried:</p> <pre><code>type Number = int | float &quot;&quot;&quot;Represents a scalar number that is either an integer or floa...
<python><python-typing><docstring><type-alias><python-3.12>
2023-12-03 21:45:27
1
908
bmitc
77,596,283
15,804,190
python regex failing to find all matches
<p>My regex is failing to capture all groups when I run in python, and I'm at a loss why...</p> <p>I'm trying to pull out the sequences of numbers.</p> <pre class="lang-py prettyprint-override"><code>import re my_string = '467..114..' re.search(r'(?:(\d+)(?:\.*))*',my_string).groups() # outputs ('114',) </code></pre> ...
<python><regex><regex-group>
2023-12-03 21:45:27
2
3,163
scotscotmcc
77,596,091
4,980,705
Run df.merge, df.apply in batches for big dataframe
<p>I have a dataframe with around 500k rows and need to run several <code>df.merge</code>, <code>df.apply</code> and requests to the Google Maps API. After applying the changes on the columns I want to write to a <code>.csv</code> file.</p> <p>I've tried to run the code several times but it crashes all the time and tak...
<python><pandas><dataframe>
2023-12-03 20:38:35
1
717
peetman
77,595,969
4,348,400
How to provide a type hint for parameters whose arguments should be ordered and hashable?
<p>I want a type hint which indicates that the arguments are ordered and hashable.</p> <pre class="lang-py prettyprint-override"><code>def foo(bar: OrderedHashable) -&gt; None: ... </code></pre> <p>Here is my work in progress.</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Hashable ...
<python><python-typing>
2023-12-03 20:00:35
1
1,394
Galen
77,595,878
6,245,473
How to add price column to dataframe based on date column already present in yahooquery?
<p>The following code is being used to create the output below it:</p> <pre><code>from yahooquery import Ticker # Fetching data for AAPL aapl = Ticker('AAPL') types = ['asOfDate', 'TangibleBookValue', 'ShareIssued'] financial_data = aapl.get_financial_data(types, trailing=False) # Dropping specific columns columns_to...
<python><pandas><dataframe><stock><yfinance>
2023-12-03 19:33:58
1
311
HTMLHelpMe
77,595,820
1,473,517
How to define types for a numba dict
<p>I want to convert a python dict to a numba dict for speed reasons. Here is my non-working MWE:</p> <pre><code>import numba import numpy as np mat = np.random.normal(size=(3,3)) pyth_dict = {&quot;A&quot;: 2, &quot;B&quot;: mat} @numba.njit() def numbaize(pyth_dict): numba_dict = {} for key in pyth_dict.k...
<python><numba>
2023-12-03 19:19:42
0
21,513
Simd
77,595,758
3,861,775
Efficient copying of an ensemble in JAX
<p>I have an ensemble of models and want to assign the same parameters to each of the models. Both the models' parameters as well as the new parameters have the same underlying structure. Currently I use the following approach that uses a for-loop.</p> <pre><code>import jax import jax.numpy as jnp model1 = [ [jnp....
<python><jax>
2023-12-03 19:00:01
1
3,656
Gilfoyle
77,595,614
1,798,704
Equivalnet of C# or Python even rounding in Javascript
<p>There is a discrepancy between how C# or Python rounds a decimal number and how Javascript handles it. I've already found this answer <a href="https://stackoverflow.com/questions/3108986/gaussian-bankers-rounding-in-javascript#comment135873096_49080858">banker-rounding</a>, but this solution does not work in my case...
<javascript><python><c#>
2023-12-03 18:19:38
1
589
Mohammad
77,595,297
451,878
Bi directionnal relation many-to-many (on same table) with sqlAlchemy, python and pydantic (fastapi)
<p>I wonder, if it's possible to have a many to many relation <em>on the same table</em> without extra table (with IDs) ?</p> <p>I've basicly this one :</p> <pre><code>from sqlalchemy import Column, Integer, String, ForeignKey, Table, text from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped fro...
<python><sqlalchemy><pydantic><alembic>
2023-12-03 17:00:57
1
1,481
James
77,595,276
5,801,127
Bash script to execute python program if its not running
<p>I have the following bash script to check if my python script miner_nbeats.py is currently running and if not, then re-run because sometimes my python script gets killed due to out of memory error. So I have this bash script below, which works and executed the program at the beginning. However, I noticed that it’s n...
<python><linux><bash><pid>
2023-12-03 16:54:02
1
1,011
PutsandCalls
77,595,180
1,682,470
List all files containing a string between two specific strings (not on the same line)
<p>I'd like to recursively find all <code>.md</code> files of the current directory that contain the “Narrow No-Break Space” <code>U+202F</code> Unicode character between the two strings <code>\begin{document}</code> and <code>\end{document}</code>, possibly (and in fact essentially) not on the same line as <code>U+202...
<python><regex>
2023-12-03 16:31:18
4
674
Denis Bitouzé
77,595,178
17,523
Setting node size in `pyvis`
<p>I use <a href="https://pyvis.readthedocs.io/en/latest/tutorial.html" rel="nofollow noreferrer">pyvis</a> to visualize graphs. Everything works well, except for the fact that the node labels are super small, and I need to perform extreme zoom-in in order to see them (see the screenshot)</p> <p>Is there a way to make ...
<python><visualization><pyvis>
2023-12-03 16:30:59
1
32,057
Boris Gorelik
77,595,150
22,407,544
Should I use chunks() or save() to save files in Django?
<p>I'm a little confused. When saving an uploaded file in Django should I save it using FileSystemStorage( fs.save() ) or should I use chunks? I just want to ensure that I use chunking to save files that are large so that they don't impact performance. But I'm also reading <a href="https://www.reddit.com/r/django/comme...
<python><django><file>
2023-12-03 16:25:27
0
359
tthheemmaannii
77,595,129
18,494,333
Python importlib.resources.files() throws UnicodeDecodeError: invalid continuation byte
<p>I am creating a Python package that needs certain data files in order to work. I've been looking for a way to include these data files with the package installation. I found a way using <code>importlib.resources.files()</code>. However, I'm receiving an error when I try to decode the objects I am returned.</p> <p>I'...
<python><python-unicode><python-importlib><data-files>
2023-12-03 16:21:53
0
387
MillerTime
77,594,973
1,497,139
Handling UnknownTimezoneWarning in Python's dateutil for Various Timezone Abbreviations
<p>I'm encountering multiple UnknownTimezoneWarning errors when parsing dates with Python's dateutil.parser. The warnings are for various timezone abbreviations like UT, PDT, EDT, EST, PST, CEDT, EET, EEST, CES, and MET. The warning suggests using the tzinfos argument for timezone-aware datetime parsing. How can I effe...
<python><datetime><pendulum>
2023-12-03 15:39:24
1
15,707
Wolfgang Fahl
77,594,717
1,818,443
WeasyPrint Python module not found
<p>I installed WeasyPrint on MacOS Ventura 13.4.1 using Homebrew. It seems to have installed properly,</p> <pre><code>which weasyprint \usr\local\weasyprint </code></pre> <p>When I try to load the Python module however, I get the error,</p> <pre><code>python3 weasytest.py ... ModuleNotFoundError: No module named 'weas...
<python><python-3.x><macos><macos-ventura><weasyprint>
2023-12-03 14:30:09
0
1,272
Lukas Bystricky
77,594,625
10,089,200
How can I fix my perceptron to recognize numbers?
<p>My exercise is to train 10 perceptrons to recognize numbers (0 - 9). Each perceptron should learn a single digit. As training data, I've created 30 images (5x7 bmp). 3 variants per digit.</p> <p>I've got a perceptron class:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def unit_step_func(x...
<python><numpy><machine-learning><neural-network><perceptron>
2023-12-03 14:03:49
3
693
Shout
77,594,590
1,481,986
Streamlit controlling sidebar title
<p>I have a streamlit app with multiple pages which I run from <code>minimal_example.py</code></p> <p>This is the file content -</p> <pre><code>import streamlit as st def main(): page_config = st.set_page_config( page_title=&quot;my demo&quot;, ) if __name__ == &quot;__main__&quot;: main() </code...
<python><streamlit>
2023-12-03 13:55:19
2
6,241
Tom Ron
77,594,060
20,920,790
Can't import Swifter for python
<p>I got installed Pandas 2.1.3 and Swifter 1.4.0. When I try import swifter I got:</p> <pre><code> AttributeError: module 'pandas.core.strings' has no attribute 'StringMethods' </code></pre> <p>That's is going wrong? This version of Pandas not compatible with swifter?</p>
<python><pandas><swifter>
2023-12-03 11:24:51
1
402
John Doe
77,593,997
10,623,444
Efficiently compute item colaborating filtering similarity using numba, polars and numpy
<p><strong>Disclaimer</strong> The question is part of a thread including those two SO questions (<a href="https://stackoverflow.com/q/77567521/10623444">q1</a>, <a href="https://stackoverflow.com/a/77558612/10623444">q2</a>)</p> <p>The data resemble movie ratings from the ratings.csv <a href="https://drive.google.com/...
<python><dataframe><numpy><numba><python-polars>
2023-12-03 11:09:06
1
1,589
NikSp
77,593,852
125,673
fpdf2 write - how to get new lines printed instead of '\n'?
<p>I want to print some text in my pdf as follows;</p> <pre><code>text = self.dict_text_for_pdf[category] self.pdf.write(_c.text_line_height, text) </code></pre> <p>Inside the text I have some line break characters. But instead of a new line being printed I actually get &quot;\n&quot; printed instead. According to the ...
<python><fpdf>
2023-12-03 10:21:34
0
10,241
arame3333
77,593,648
14,037,975
How to split 100 million (18.5 GB) csv rows into 50k each small excel files
<p>I am trying to split a large CSV file into 50k rows Excel files. I tried using pandas but unfortunately it is getting crashed. So I switched to polar. It is working but the problem is it is only creating single files of 100k rows. How can I generate 50k rows excel files from 100 million (18.5 GB) csv file?</p> <p>Fi...
<python><python-polars>
2023-12-03 09:14:00
3
321
Indratej Reddy
77,593,276
5,165,649
pyspark to aggregate a column based on the column
<p>I have a dataframe like below <a href="https://i.sstatic.net/7StDL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7StDL.png" alt="enter image description here" /></a></p> <p>and I want like below <a href="https://i.sstatic.net/Td6Dp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Td6Dp...
<python><pyspark>
2023-12-03 06:45:56
1
487
viji