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
79,468,638
10,964,685
plotly histogram with filtering toolbar - python
<p>I'm trying to generate a plotly histogram that can be filtered by values with a df column. Below, in dataset, I want to be able to filter the values in item to show the distribution of values for each unique value.</p> <p>However, all I am able to display is one single value. I can't change values to show the result...
<python><plotly>
2025-02-26 05:41:08
1
392
jonboy
79,468,372
2,031,794
ValueError: Must have equal len keys and value when setting with an iterable when setting value on group
<p>I have a pandas dataframe with a timestamp index, I am grouping to get only hourly values and after a series of operations on the values of that hour I need to re-write the results to the original DF:</p> <pre><code>for name, group in df.groupby(pd.Grouper(freq=&quot;1H&quot;)): if group.shape[0] &gt; 0: ...
<python><pandas><group-by>
2025-02-26 02:41:19
1
1,326
Hakim
79,468,240
24,718
How can I send an alexa notification via proactive events ask_sdk_core python?
<p>I'm trying to send a notification from my skill to Alexa using proactive events through the <code>ask_sdk_model</code> python interface.</p> <p>At the moment I'm trying to test with the Alexa developer console. I've retrieved my client id/secret from the Alexa developer console, and managed to determine the user_id...
<python><alexa-skills-kit><ask-sdk>
2025-02-26 00:46:21
0
44,070
monkut
79,468,013
2,940,920
How to run DeepSeek model locally
<p>I am trying to run DeepSeek locally according to their instructions but it does not work with some silly error (I will show it later). This is what I am doing.</p> <ol> <li>Download the smallest model (3.5GB) from here <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B" rel="nofollow noreferre...
<python><docker><machine-learning><large-language-model><deepseek>
2025-02-25 22:14:20
1
618
Zlelik
79,467,972
13,151,915
Calling Multiple Functions on Multiple Rows of a Tensor in Parallel
<pre><code>import torch x = torch.ones(3, 3) factors = [lambda x: 2*x, lambda x: 3*x, lambda x: 4*x] indices = torch.tensor([0, 1, 2]) def multiply_row_by_factor(row, idx): return factors[idx](row) result = torch.vmap(multiply_row_by_factor, in_dims=(0, 0))(x, indices) # Original Tensor # tensor([[1., 1., 1.],...
<python><pytorch><transformation><tensor>
2025-02-25 21:53:31
2
412
gfdb
79,467,962
15,559,986
Combining multiple selections in Altair with the 'empty' property
<p>Consider the following MRE:</p> <pre><code># create data df = pd.DataFrame() df['x'] = [0, 1, 2] * 3 df['y'] = [0] * 3 + [1] * 3 + [2] * 3 # create selections click_select = alt.selection_point(name='_click_select_', toggle='true', encodings=['x','y'], empty=False, clear=False) box_select = alt.selection_interval(n...
<python><altair>
2025-02-25 21:47:56
1
304
fitzme
79,467,944
9,893,725
Comparing dataframes
<p>The goal is to compare two pandas dataframes considering a margin of error.</p> <p>To reproduce the issue:</p> <h3>Importing pandas</h3> <pre><code>import pandas as pd </code></pre> <h3>Case one - same data dataframes</h3> <pre><code>df1 = pd.DataFrame({&quot;A&quot;: [1,1,1], &quot;B&quot;: [2,2,2], &quot;C&quot;: ...
<python><pandas><numpy>
2025-02-25 21:39:03
3
899
Paulo Marques
79,467,759
4,470,052
How to perform two session.write_pandas transactionally on snowflake?
<p>When working with adding df1, and df2 into two different tables, I want to ensure that df1 doesn't write if df2 fails or any of the middle steps fail. But this doesn't work when using &quot;write_pandas&quot; function to write pandas DF to table.</p> <pre><code>session.sql(&quot;commit&quot;).collect() session.write...
<python><pandas><snowflake-cloud-data-platform>
2025-02-25 20:06:41
1
692
Flyn Sequeira
79,467,683
5,049,813
What is the correct type hint for `os.path.dirname`?
<p>When I hover over the function, Pylance tells me the type of the parameter it takes is <code>PathLike[AnyStr@dirname]</code>. What does this mean? Is it just a Union of string and PathLike?</p> <p>Right now my code looks like this:</p> <pre class="lang-py prettyprint-override"><code>def make_path(filename: os.PathLi...
<python><python-typing>
2025-02-25 19:27:15
0
5,220
Pro Q
79,467,589
918,417
Relative imports in local python module
<p>Our application started as a simple FastAPI application, while working on it we used relative paths for the imports.</p> <p>Now we need to create another application that extends the existing one. So our new code structure looks like this (there are many more files, this is just to show the issue):</p> <pre><code>pr...
<python>
2025-02-25 18:45:27
0
1,791
Matan Kadosh
79,467,524
11,342,139
Unable to read the full response coming over rs-485 from a Modbus device
<p>I have been trying to communicate with a <code>I-7000</code> IO module device that supports Modbus. In general I am able to successfully send commands such as writing to a coil or reading a coil but I face one issue - I am unable to read the response coming from the IO module device, at least not every time. I am us...
<python><serial-port><pyserial><modbus><rs485>
2025-02-25 18:15:42
2
1,046
Angel Hadzhiev
79,467,440
9,112,151
What right values for cafile, capath, cadata?
<p>There is code for ssl context creation:</p> <pre><code>import ssl ssl_context = ssl.create_default_context(cafile=..., capath=..., cadata=...) </code></pre> <p>Also there is a docker container with certs:</p> <pre><code>$ pwd /app/cert $ ls ca.pem cert.pem key.pem </code></pre> <p>What values will be for <code>ca...
<python><ssl><openssl>
2025-02-25 17:41:02
0
1,019
Альберт Александров
79,467,265
12,881,307
Openpyxl unable to save workbook with file path
<p>I want to append data from a Pandas <code>DataFrame</code> to both an existing excel sheet and an excel table (<code>ListObject</code>). I'm using <code>openpyxl</code> to do so.</p> <p>I'm now writing the code for writing to a sheet. I have the following:</p> <pre class="lang-py prettyprint-override"><code>def _app...
<python><pandas><openpyxl>
2025-02-25 16:34:57
1
316
Pollastre
79,467,167
4,543,870
Python jsonschema with definitions
<p>I'm validating a JSON schema, but the schema uses &quot;Definitions&quot;, as in the example below. Using schema validation sites everything is ok, but in code with jsonschema I have the error:</p> <pre><code>PointerToNowhere: '/definitions/ipv4_pattern' does not exist inside {} </code></pre> <p>Does jsonschema not ...
<python><jsonschema>
2025-02-25 16:07:33
3
423
devops-db
79,467,071
9,640,238
Adjacency matrix not square error from square dataframe with networkx
<p>I have code that aims to generate a graph from an adjacency matrix from a table correlating workers with their manager. The source is a table with two columns (Worker, manager). It still works perfectly from a small mock data set, but fails unexpectedly with the real data:</p> <pre class="lang-py prettyprint-overrid...
<python><pandas><dataframe><networkx><graph-theory>
2025-02-25 15:27:18
2
2,690
mrgou
79,466,868
14,282,714
Merged cells return NaN in load_workbook openpyxl
<p>I need to read an excel file using <code>load_workbook</code> from <code>openpyxl</code>. Some cells are merged in this file. This will return NaN values to some of the merged cells. I would like to have all merged cells the same value of the file. Here I tried to create a reproducible example from this simple excel...
<python><openpyxl>
2025-02-25 14:22:13
1
42,724
Quinten
79,466,568
4,403,732
How to create a literal TypeGuard in Python?
<p>I'd like to have a <code>TypeGuard</code> of property names in Python. The source values come from 3rd party source, so I need to validate them effectively.</p> <p>To simplify, let's say I' making an app listing people's dogs. Each dog has just 3 properties:</p> <ol> <li><code>name</code></li> <li><code>birth_date</...
<python><python-typing><typeguards>
2025-02-25 12:33:42
0
23,062
Robo Robok
79,466,513
353,337
Indent, but leave empty lines as-is
<p>I would like to use <a href="https://github.com/Instagram/LibCST" rel="nofollow noreferrer">LibCST</a> for indenting code. Wrapping a body in an <code>cst.IndentedBlock</code> works, but gives whitespace in empty lines.</p> <p>MWE:</p> <pre class="lang-py prettyprint-override"><code>import libcst as cst s = cst.par...
<python><libcst>
2025-02-25 12:13:20
1
59,565
Nico Schlömer
79,466,367
9,793,316
Applying `vmap` to a model with `torch.utils.checkpoint.checkpoint`
<p>I need to use <code>vmap</code> to calculate gradient with respect to a model that uses <code>torch.utils.checkpoint.checkpoint</code>.</p> <p>I got the following error</p> <blockquote> <p>RuntimeError: You tried to vmap over _NoopSaveInputs, but it does not have vmap support. Please override and implement the vmap ...
<python><pytorch>
2025-02-25 11:15:38
0
3,053
Raven Cheuk
79,466,300
16,906,505
Playwright exception: no description
<p><a href="https://i.sstatic.net/TSko5dJj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TSko5dJj.png" alt="exception" /></a></p> <p>I have a strange error with no description when I try to use async playwright</p> <p>This is a FastApi app and I am on Windows</p> <p>In the docs there is a mention that ...
<python><python-asyncio><fastapi><playwright-python>
2025-02-25 10:59:16
0
500
RheinmetallSkorpion
79,466,178
3,070,181
How to place Tkinter PanedWindow sash correctly on a Notebook tab?
<p>Issue with PanedWindow Sash Placement in a Notebook Tab.</p> <p>I am trying to create a Notebook tab that contains a PanedWindow with four panes.</p> <p>However, when I attempt to position the sashes manually, the third sash does not appear at the expected position.</p> <p><strong>Expected Behavior:</strong></p> <p>...
<python><tkinter>
2025-02-25 10:27:26
1
3,841
Psionman
79,465,862
1,835,603
WebSocket Server in Python Not Receiving All Messages While Node.js Does
<p>I am running a WebSocket server behind Nginx, and I have two different implementations: one in Node.js and one in Python. The Node.js WebSocket server receives all messages correctly, but the Python server <strong>misses one of the messages</strong>.</p> <h3><strong>WebSocket Message Flow:</strong></h3> <ol> <li>Cli...
<python><websocket><python-asyncio>
2025-02-25 08:27:54
0
523
MKM
79,465,837
16,869,946
Creating new columns for the estimated "utilities" and predicted probabilities in xlogit
<p>I was trying to use the <code>xlogit</code> package in python to fit a mixed logit model:</p> <p><a href="https://xlogit.readthedocs.io/en/latest/notebooks/mixed_logit_model.html#Car-Dataset" rel="nofollow noreferrer">https://xlogit.readthedocs.io/en/latest/notebooks/mixed_logit_model.html#Car-Dataset</a></p> <pre><...
<python><pandas>
2025-02-25 08:16:39
0
592
Ishigami
79,465,836
12,935,622
local package shows in pip list but not recognized when imported
<p>I have file structure as follows</p> <pre class="lang-none prettyprint-override"><code>- project - LLaVA-NeXT - llava - __init__.py - ... - playground - models - script.py </code></pre> <p>In <code>script.py</code>, I did <code>from llava.model.builder import load_pretrained_model</code> but I g...
<python><pip>
2025-02-25 08:16:22
1
1,191
guckmalmensch
79,465,662
17,328
Rendering streamed Markdown chunks in IPython/Jupyter
<p>The context is that I'm streaming LLM tokens from a model, and they're in Markdown, so I want to repeatedly append to the rendered Markdown.</p> <p>This is roughly the code I'm using with bare text:</p> <pre class="lang-py prettyprint-override"><code>async for chunk in response.receive(): print(chunk.text, end='')...
<python><jupyter-notebook><markdown><ipython>
2025-02-25 07:07:46
0
8,365
Mark McDonald
79,465,562
11,277,878
Pybind11 - Multiple definition of PyInit_module_name
<p>Solved! - Please check the <a href="https://stackoverflow.com/a/79465870/11277878">answer</a>.</p> <p>I wrote a library where headers and python bindings are auto-generated. For example <code>dummy_bind.cpp</code> for <code>dummy_message.h</code> and each <code>_bind.cpp</code> file has <code>PYBIND11_MODULE</code> ...
<python><c++><pybind11>
2025-02-25 06:14:39
2
614
no more sigsegv
79,465,553
13,097,857
How to limit google maps auto complete to only one country?
<p>I have tried everything so my search input only gives autocomplete options from the Dominican Republic but I have not been able to achieve it, does anyone here know how to do this?</p> <pre class="lang-html prettyprint-override"><code>&lt;input type=&quot;text&quot; id=&quot;searchInput&quot; class=&q...
<javascript><python><django><google-maps-api-3><maps>
2025-02-25 06:09:24
1
302
Sebastian Nin
79,465,547
705,086
How to set up same SSLContext in Python 3.8 through 3.13?
<p>My code so far:</p> <pre class="lang-py prettyprint-override"><code> def _ssl_context(self, ca: str | None) -&gt; ssl.SSLContext: # NOTE: ssl.create_default_context() doesn't allow setting the context.protocol in a way # that's the same across Python 3.8 and 3.10 onwards. Whip the context up by ha...
<python><security><ssl><python-3.8><tls1.3>
2025-02-25 06:05:59
1
11,856
Dima Tisnek
79,465,431
16,382,765
Get only user email address with Google OAuth in Python
<p>I am working on a <code>Python</code> web backend. And I have successfully implemented <code>Google OAuth</code> functionality using the following page.</p> <p><a href="https://developers.google.com/identity/protocols/oauth2/web-server#python" rel="nofollow noreferrer">https://developers.google.com/identity/protocol...
<python><rest><google-oauth>
2025-02-25 04:41:07
1
523
enoeht
79,465,328
1,273,987
Arrays of size 0 in NumPy
<p>I need to work with arrays that can have zeros in their shapes. However, I am encountering an issue. Here's an example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np arr = np.array([[]]) assert arr.shape == (1,0) arr.reshape((1,0)) # No problem (nothing changes) arr.reshape((-1,0)) # Valu...
<python><arrays><numpy><numpy-ndarray>
2025-02-25 03:28:26
1
2,105
Ziofil
79,465,264
2,000,548
How to cancel a Ray job submitted to a Ray cluster?
<p>I have a long-run Ray job.</p> <p>main.py</p> <pre class="lang-py prettyprint-override"><code>import time import ray @ray.remote def square(n: int) -&gt; int: time.sleep(50000000) return n * n @ray.remote def sum_list(numbers: list[int]) -&gt; int: return sum(numbers) if __name__ == &quot;__main__...
<python><ray>
2025-02-25 02:27:12
1
50,638
Hongbo Miao
79,465,204
1,914,781
plotly - remove holiday from stock plot not work as expected
<p>Since 2025/2/17 is a holiday, It should be removed from plot.<code>rangebreaks</code> looks exactly for this case, but,it generate a very weird graph.</p> <p>full code:</p> <pre><code>#!/usr/bin/env python3 import yfinance as yf import plotly.graph_objs as go from plotly.subplots import make_subplots import pandas a...
<python><plotly>
2025-02-25 01:30:34
0
9,011
lucky1928
79,465,038
2,072,516
Narrowing typing on a subclass
<p>I have a Pydantic class to represent how my general API response should look:</p> <pre><code>class RootDataResponseSchema(BaseModel): status: Literal[&quot;success&quot;, &quot;fail&quot;] data: BaseModel </code></pre> <p>I went with <code>BaseModel</code> for data, as the idea would be I'd subclass <code>Ro...
<python><python-typing><pydantic>
2025-02-24 23:21:12
2
3,210
Rohit
79,465,001
849,076
Find corner of annotation with background
<p>I am trying to find the corners of the box produced by adding a matplotlib annotation with background color. This is what I have tried:</p> <pre><code>a = ax.annotate( label, xy=(x, y), backgroundcolor=(0.69, 0.6, 0.65, 0.65), color=&quot;#444444&quot;, fontsize=14, xytext=(0, 0), textcoords=&quot;offs...
<python><matplotlib>
2025-02-24 22:54:19
1
8,641
leo
79,464,768
15,524,510
Catboost error when loading pool from disk
<p>I am creating a catboost pool from a pandas dataframe (columns have strings as names, not sure if thats relevant) and then quantizing it and saving to disk using this code:</p> <pre><code>import catboost as cb import pandas as pd data = { 'label': np.random.randint(0, 5, 100), # Random integers 0-4 for label ...
<python><pandas><save><catboost>
2025-02-24 20:48:33
1
363
helloimgeorgia
79,464,713
2,438,371
Turtle - screen.update() not working with copy method?
<p>I have a list with several turtle instances. I want to create a copy of one object and let this one move forward.</p> <p>This works fine. But when I disable screen udpates and do it manually in my code it gives me a different result and I don't see the turtle on its new position. But I do see that it has moved there...
<python><turtle-graphics><python-turtle>
2025-02-24 20:21:25
1
659
Denny Crane
79,464,633
2,077,648
Copying certain cells of an excel file to fix the report in Python
<p>In the below table how can we copy the column tempx cells for each test from partition column long cell to the corresponding test cell<br></p> <p>For example when we filter Scenario Column cell A1.results.0.test1 , it has two rows corresponding to each partition type;<br> Here need to make sure both rows Temp1 to Te...
<python><python-3.x><pandas><dataframe><openpyxl>
2025-02-24 19:36:57
2
967
user2077648
79,464,608
8,887,483
How do I correctly order conv1d weights in PyTorch when using groups for per-batch unique filters?
<p>I'm working on a PyTorch project where I have a special parameter that learns conv1d weights. After obtaining these weights, I apply a multiplying factor that can vary for each item in the batch. My goal is to use the groups argument in the convolution operation so that each batch item gets its own unique filter.</p...
<python><pytorch>
2025-02-24 19:21:32
0
605
Sami Wood
79,464,593
2,893,712
Python Requests Disable zstd Encoding
<p>My Synology DS418play recently updated to the <a href="https://www.synology.com/en-nz/releaseNote/DSM?model=DS418play#ver_69057-7" rel="nofollow noreferrer">latest version of DSM7</a> that is available. I noticed that a lot of the python scripts that I had have started returning weirdly encoded data. Here is an exam...
<python><python-requests><zstd>
2025-02-24 19:15:10
2
8,806
Bijan
79,464,425
9,110,646
How to full join / merge two frames with polars while updating left with right values?
<p>So I got two csv which I load as polars frames:</p> <p><strong>left:</strong></p> <pre class="lang-py prettyprint-override"><code>left_csv = b&quot;&quot;&quot; track_name,type,yield,group 8CEB45v1,corn,0.146957,A A188v2,corn,0.86308,A B73v6,corn,0.326076,A CI6621v1,sweetcorn,0.0357792,A CML103v1,sweetcorn,0.510464,...
<python><dataframe><python-polars>
2025-02-24 17:51:39
1
423
Pm740
79,464,391
18,950
Django/Celery SQLite database locked on concurrent access
<p>I have a local Django 5.1/Celery 5.4 project that is using SQLite. I am the only user.</p> <p>Certain model saves trigger a Celery task that queries (<code>SELECT</code>) for the updated record (using the Django ORM), then runs an API call to update a remote record based on the local data, and then runs another <cod...
<python><django><sqlite>
2025-02-24 17:32:46
2
12,651
David Eyk
79,464,353
2,006,674
How to prevent duplicate code for exception handling in Python
<p>What is a Pythonic way to not have duplicated code for exception handling?</p> <p>In a real code base, it is not <code>2 / 0</code>, but reading or writing from an async socket, and I have more exceptions to catch, ConnectionResetError, BrokenPipeError, and TimeoutError.</p> <p>I do not want to duplicate on code for...
<python><exception><dry>
2025-02-24 17:16:24
1
7,392
WebOrCode
79,464,314
5,269,892
Pandas astype becomes in-place operation for data loaded from pickle files
<p>Pandas <code>astype()</code> appears to unexpectedly switch to performing in-place operations after loading data from a pickle file. Concretly, for <code>astype(str)</code>, the data type of the input dataframe values is modified. What is causing this behavior?</p> <p>Pandas version: 2.0.3</p> <p><strong>Minimal exa...
<python><pandas><type-conversion><pickle>
2025-02-24 16:59:46
1
1,314
silence_of_the_lambdas
79,464,311
7,437,143
Urwid example with input validation per keypress on a datetime entry?
<h2>Context</h2> <p>Suppose one would like two, modular, input boxes in which one can enter a date in format <code>yyyy-mm-dd</code> and optionally the time in format: <code>HH-MM</code>, like:</p> <pre class="lang-bash prettyprint-override"><code>Please enter the date in format YYYY-MM-DD, (and optionally the time in ...
<python><tui><urwid>
2025-02-24 16:57:08
0
2,887
a.t.
79,464,199
7,091,135
How to implement batch resource using SimPy
<p>I spent some time looking for the solution to this kind of simple problem but still could not find it. The problem is to simulate process when some events can be processes concurrently by limited amount of resources while some events require aggregating first and then batch processing. Here is a simple code example ...
<python><simpy>
2025-02-24 16:08:05
1
359
Alexander Lyapin
79,464,131
266,254
bind parameters by array index
<p>I'm trying to migrate from <code>cx_Oracle 8.1.0</code> to <code>oracledb 2.5.1</code> library. Before such query was working:</p> <pre class="lang-sql prettyprint-override"><code>update command_center set E_ID = :1, E_ASPECTS = :2, E_CREATED_TIMESTAMP = :3 WHERE e_id = :1 </code...
<python><cx-oracle><python-oracledb>
2025-02-24 15:47:24
2
5,056
bilak
79,463,940
11,092,636
Visual Studio Code not letting me choose Virtual environment Python
<p>This is a bug I cannot wrap my head around. I should first mention that everything works perfectly on PyCharm notebook Professional Edition (but I prefer VSCode's way of using notebooks).</p> <p>When I click on <code>Select Kernel</code>, I only see my two base Python environments. Both work. I would however like to...
<python><visual-studio-code>
2025-02-24 14:52:45
5
720
FluidMechanics Potential Flows
79,463,478
589,352
Testing a flask-WTForms app that uses csrf token (pytest)
<p>I have a flask app based on the tutorial here <a href="https://flask.palletsprojects.com/en/stable/tutorial/" rel="nofollow noreferrer">https://flask.palletsprojects.com/en/stable/tutorial/</a>. The tutorial comes with a test suite but having adapted the app to use WTForms the tests that post form data stopped worki...
<python><flask><pytest><csrf><flask-wtforms>
2025-02-24 12:09:15
0
1,937
jaybee
79,463,465
1,450,343
use pydantic settings cli to parse partial json from file
<p>I want to use pydantic-settings for the following scenario: I have two options to write CLI parameters to my application, either by providing a json file or a command. E.g.</p> <pre><code>myapp --config myconfig.json --logger DEBUG </code></pre> <p>The command line arguments should override the definitions in the js...
<python><command-line-interface><pydantic><pydantic-settings>
2025-02-24 12:02:53
0
816
ModdyFire
79,463,344
2,883,209
Dynamically adding columns to panda dataframes
<p>Trying to use pandas to create a data frame that contains the total of time spent on each task over a period of time, then add a column for each week in the data, dynamically identifying what weeks to add.</p> <p>It feels like the kind of task that pandas should excel at, but (more likely due to my lack of expertise...
<python><pandas>
2025-02-24 11:21:03
0
1,244
vrghost
79,463,169
2,509,085
Create nested lists based on split of characters
<p>I have a list made by strings, correctly cleaned (<code>split(',')</code> can be safely used), and correctly sorted depending on numbers. As a small example:</p> <pre><code>l = ['C1', 'C1,C2', 'C2,C3', 'C3,C4', 'C4', 'C5', 'C5,C6', 'C6,C7', 'C7,C8', 'C8', 'C10', 'C10,C11', 'C11,C12', 'C12,C13', 'C13'] </code></pre> ...
<python><list><split>
2025-02-24 10:18:49
6
4,991
matteo
79,463,096
3,189,980
python logging use two different loggers with different formatting
<p>I am new to python!</p> <p>I would like to setup two different loggers, both logging to stdout, but with different formats.</p> <p>What I tried:</p> <pre><code>import logging logging.basicConfig( level=logging.NOTSET, format='### %(levelname)-8s - %(message)s' ) v_obj_CONSOLE = logging.StreamHandler() v_obj_CO...
<python><logging><formatter>
2025-02-24 09:59:24
1
357
averlon
79,463,058
8,137,301
How to pass multiple inputs to a Python script in macOS Shortcuts?
<p>I’ve been using a Python script to perform multiple find/replace actions at once. It that has 3 inputs right inside the code, in a form like this:</p> <pre><code>def main(): text_passage = &quot;&quot;&quot; (Here be huge blocks of text) “&quot;&quot; to_replace_input = “&quot;&quot; (Here be large strings to loo...
<python><macos><shortcut>
2025-02-24 09:49:34
1
307
Crabgrass0899
79,462,962
2,201,385
PyCharm cannot connect to local postgresql database
<p>I'm trying to configure PyCharm's Data Source tool to use a locally running postgres database (not in a container) and it simply fails with the (not very helpful) message &quot;[08001] The connection attempt failed.&quot;</p> <p>I can connect to it in the shell with the command <code>psql -hlocalhost -p5432 -Umac1 l...
<python><postgresql><pycharm>
2025-02-24 09:14:18
0
581
Tony Beta Lambda
79,462,913
200,783
In Python, how can I find the class in which a method is defined?
<p>If I have a class hierarchy in Python (we can assume there's no multiple inheritance), how can I find the class in which a method is defined? For example:</p> <pre><code>class C: def f(): pass class D(C): def f(): pass class E(D): pass </code></pre> <p>If I call <code>E().f()</code>, this calls the met...
<python><class><oop><methods>
2025-02-24 08:54:41
1
14,493
user200783
79,462,736
4,489,082
Error while creating Neo4jGraph object using langchain
<p>I am trying to create a neo4j object using the following code. While I run the code, I receive error. Kindly help me fix this error. I have verified that the environment variables are read correctly. I am running this on my local Ubuntu machine.</p> <p>Code -</p> <pre><code>from langchain_neo4j import Neo4jGraph im...
<python><neo4j><langchain>
2025-02-24 07:38:46
2
793
pkj
79,462,563
8,813,473
Not able to retain &apos; in the xml ElementTree write in python
<p>After parsing an xml string with an attribute value containing the <code>&amp;apos;</code> characters, when I try to write it to a file or output it as a string, I am not able to retain <code>&amp;apos;</code> occurrences. I know, the final xml is still valid, but from the diff perspective, I want to retain the <cod...
<python><xml>
2025-02-24 05:52:39
1
410
Amit Tendulkar
79,462,501
10,787,403
IterableDataset not supported on GRPOTrainer
<p>The following program crashes upon execution</p> <pre class="lang-py prettyprint-override"><code>from datasets import IterableDataset, Dataset from trl import GRPOConfig, GRPOTrainer prompts = [&quot;Hi&quot;, &quot;Hello&quot;] def data_generator(): while True: for s in prompts: yield {&quo...
<python><machine-learning><huggingface-datasets><huggingface-trainer>
2025-02-24 05:08:12
0
376
PMM
79,462,383
4,330,537
Trying to use chrome with seleniumbase and uc=true option
<p>I am trying to scrape a site that has a cloudflare bot check I currently use</p> <pre><code>import undetected_chromedriver as uc </code></pre> <p>and portable CHROME.EXE</p> <p>however this seems to not get me around the bot check , so now I am going to try</p> <pre><code>from seleniumbase import SB </code></pre> <p...
<python><web-scraping><seleniumbase>
2025-02-24 03:19:41
1
835
RobM
79,462,354
2,537,486
How to access secondary axis properties in Matplotlib?
<p>My goal is to plot two sets of data against two different y axes, at the left and right spines, with two different colors. In addition, I want the following elements colored with the same two colors on each side:</p> <ul> <li>left and right vertical spine</li> <li>ticks (major and minor)</li> <li>tick labels</li> </...
<python><matplotlib>
2025-02-24 02:46:19
1
1,749
germ
79,462,214
986,533
How can I reuse a function in NiceGUI slots without client-side code duplication?
<p>NiceGUI documentation on <a href="https://nicegui.io/documentation/table#conditional_formatting" rel="nofollow noreferrer">conditional formatting in Table</a> suggests the following:</p> <pre class="lang-py prettyprint-override"><code>table.add_slot('body-cell-age', ''' &lt;q-td key=&quot;age&quot; :props=&quot;...
<javascript><python><nicegui>
2025-02-24 00:29:34
1
3,630
Konrad Jamrozik
79,462,149
2,057,516
Why does this sorted key lambda encounter an IndexError
<p>I thought I understood the <code>key</code> argument for the <code>sorted</code> function, but for the life of me, I cannot figure out why it appears to be applying the tuple index to the string inside the tuple instead of to the tuple? What is going on here? I'm running python 3.9.</p> <p>I narrowed it down to th...
<python><python-3.x><sorting><indexing><tuples>
2025-02-23 23:19:01
1
1,225
hepcat72
79,461,783
170,614
pandas resample and candlestick chart
<p>I'm trying to figure out how to create a candle stick chart with the data from pandas resample method. But let's start with this simple example:</p> <pre><code>import pandas as pd from datetime import datetime from bokeh.plotting import figure, show data = { 'time': [ datetime(2025, 1, 1), datet...
<python><pandas><bokeh><resample>
2025-02-23 18:44:29
1
2,370
Adam
79,461,655
1,047,788
How do I approximate Scala's call-by-name in Python?
<p>Given the example from <a href="https://docs.scala-lang.org/tour/by-name-parameters.html" rel="nofollow noreferrer">https://docs.scala-lang.org/tour/by-name-parameters.html</a> that implements a while-loop</p> <pre class="lang-scala prettyprint-override"><code>def whileLoop(condition: =&gt; Boolean)(body: =&gt; Unit...
<python><python-3.x><scala><callbyname>
2025-02-23 17:30:54
2
29,820
user7610
79,461,582
12,369,910
Environment variable in conda is not aligning with os.environ, possibly because of un-escaped dollar-sign
<p>I am trying to set an environment variable <code>SOME_VAR</code> in a conda environment. The value begins with a <code>$</code> character. Initially I didn't properly single-quote the variable value, which might have caused a silent error in powershell because that character has special meaning. Later I thought I'...
<python><powershell><environment-variables><conda><spyder>
2025-02-23 16:49:35
2
360
Eli Johnson
79,461,435
14,358,689
How do I connect my python api to enable login to my wordpress website
<p>I am creating an api that would allow users of my wordpress website to also login from a mobile device (I am making use of fast-api). but I cannot figure out how to hash the password from python so that is is compatible with wordpress.</p> <p>I am making use of <code>passlib.phpass</code>.</p> <p>I have access to my...
<python><wordpress><wordpress-rest-api><password-hash>
2025-02-23 15:03:23
0
367
Anthony Aniobi
79,461,432
10,722,752
Getting ModuleNotFoundError: No module named 'mltable' error while executing command job in Azure ml SKD v2
<p>I am trying to run a command job that'd read in a Data Asset and perform some pre processing for further ML tasks.</p> <p>To read in the data in the <code>.py</code> file I used the code in the <code>consume</code> section as below:</p> <pre><code>def get_data(): ml_client = MLClient.from_config(credential=Defa...
<python><azure><azure-machine-learning-service><azureml-python-sdk>
2025-02-23 15:02:48
1
11,560
Karthik S
79,461,242
1,823,068
How to convert float columns without decimal into int columns in Polars?
<p>The following <code>pandas</code> code removes all the <code>.0</code> decimal precision if I have a float column with 1.0, 2.0, 3.0 values:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ &quot;date&quot;: [&quot;2025-01-01&quot;, &quot;2025-01-02&quot;], &quot;a...
<python><dataframe><casting><python-polars>
2025-02-23 12:49:28
1
401
Nyssance
79,461,133
3,727,050
Python list Get Item not O(1)?
<p>I am trying to optimize a piece of code and I saw a lot of time spent into picking a random index out of a list.</p> <p>Using the following <code>timeit</code>, I am seeing that Get Item against a larger list can take ~3x longer, while generating the random index is constant time:</p> <pre><code>import timeit setup ...
<python><list>
2025-02-23 11:14:36
1
5,730
urban
79,460,515
2,280,091
How to validate only part of a document with Cerberus?
<p>I use Cerberus to validate a loaded configuration file. The user may make changes to that configuration within the program, however, and when they do, I’d like to validate <strong>only that change</strong> with Cerberus – not validate the whole document in vain, when I know that the rest hasn’t changed.</p> <p>Take ...
<python><cerberus>
2025-02-23 00:46:22
0
1,519
obskyr
79,460,500
4,913,592
Differentiable Environment Map Failing Backpropagation in Mitsuba 3.6.4
<p>I'm trying to set up a scene in Mitsuba 3 where I optimize an environment map parameter, <code>emitter.data</code>. This seems like it should be possible given their <a href="https://mitsuba.readthedocs.io/en/stable/src/inverse_rendering/caustics_optimization.html" rel="nofollow noreferrer">caustics optimization tut...
<python><graphics><3d><rendering><mitsuba-renderer>
2025-02-23 00:17:58
1
351
Anson Savage
79,460,447
3,624,171
How do I write a query like (A or B) and C in Polars?
<p>I expected either a or b would be 0.0 (not NaN) and c would always be 0.0. The Polars documentation said to use | as &quot;or&quot; and &amp; as &quot;and&quot;. I believe I have the logic right: (((a not Nan) or (b not Nan)) and (c not NaN))</p> <p>However, the output is wrong.</p> <pre class="lang-py prettyprint-...
<python><dataframe><filter><python-polars><polars>
2025-02-22 23:14:17
1
432
Steve Maguire
79,460,405
1,092,125
Executable Flask app server locally: change Debug mode, is it possible?
<p>If I have received executable file that runs Flask app server locally, can I somehow set Debug mode On? I know it is Flask app and I see in CMD</p> <pre><code> * Serving Flask app '09WEB' * Debug mode: off WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server ...
<python><flask><debug-mode>
2025-02-22 22:30:23
0
5,385
renathy
79,460,246
420,409
Dynamically add subcommands in typer
<p>In a typer command line interface with subcommands, is it possible to dynamically (during run time) change the subcommands and parameters that those take?</p> <p>Consider the following script as an example:</p> <pre class="lang-py prettyprint-override"><code>import typer from typing import Annotated, Optional local...
<python><typer>
2025-02-22 20:24:46
0
2,429
Joma
79,460,096
12,990,915
How to GPU-accelerate PDE solvers in Python?
<p>I have been working on a small Python package to solve a class of PDEs using <code>scipy.integrate.solve_ivp</code>. As discretizations are made finer, runtime becomes a bottleneck—especially when I need to solve the PDE for a large number of different initial conditions.</p> <p>I would like to make use of GPU accel...
<python><scipy><scientific-computing><cupy><scipy-integrate>
2025-02-22 18:31:07
1
383
user572780
79,460,071
1,089,715
Is there a way to disable "Just my code" debugging in Visual Studio 2022 for Python?
<p>In Visual Studio 2022, I went to &quot;Debug&quot; =&gt; &quot;Options&quot; =&gt; &quot;General&quot; and unchecked &quot;Enable Just My Code&quot;</p> <p>I also went to &quot;Debug&quot; =&gt; &quot;Options&quot; =&gt; &quot;Python&quot; =&gt; &quot;Debugging&quot; and checked &quot;Enable debugging of the Python ...
<python><visual-studio><debugging><visual-studio-2022><visual-studio-debugging>
2025-02-22 18:16:39
0
4,843
Vitalii
79,459,880
11,062,613
How can I iterate over all columns using pl.all() in Polars?
<p>I've written a custom function in Polars to generate a horizontal forward/backward fill list of expressions. The function accepts an iterable of expressions (or column names) to determine the order of filling. I want to to use all columns via pl.all() as default. The problem is that pl.all() returns a single express...
<python><dataframe><python-polars>
2025-02-22 15:59:56
1
423
Olibarer
79,459,847
11,475,651
ModuleNotFound Error right after I globally install a Python package. What am I missing here?
<p>I'm running Python 3.12.3 on Ubuntu 24.04. I have been trying to install a few different packages to determine timezones from longitude and latitude coordinates, and every time I've tried installing packages the last few days, I simply cannot get python to find/use that package. Below is a screenshot.</p> <p><a href...
<python><python-3.x><pip>
2025-02-22 15:38:39
1
317
Abed
79,459,841
1,251,549
How use @multimethod and Self tohether in python?
<p>Consider the code:</p> <pre><code>from enum import Enum, auto from typing import Self from typing import List from multipledispatch import dispatch from multimethod import multimethod class Name: __id: list[str] def __new__(self, id: list[str]): self.__id = id # ... @multimethod def...
<python><self><multimethod>
2025-02-22 15:31:07
1
33,944
Cherry
79,459,837
179,014
Why does calling curl solve my SSL issues in Python on Windows
<p>This is a pretty bizarre issue. I have created a fresh Windows 11 VM using VMware Fusion on Mac. I installed VMware Tools and Python on it</p> <pre><code>winget install -e --id Python.Python.3.11 </code></pre> <p>I start python from the Powershell terminal and try to connect to Google for testing:</p> <pre><code>&g...
<python><windows><ssl><curl><ssl-certificate>
2025-02-22 15:27:26
2
11,858
asmaier
79,459,741
9,815,697
pyo3 multiple `wrap` found
<p>I am trying to return a <code>HashMap&lt;String, Vec&lt;Vec&lt;f64&gt;&gt;&gt;</code> from Rust to Python.</p> <p>This is the function in PyO3 wrapper:</p> <pre class="lang-rust prettyprint-override"><code> pub fn predict_intervals&lt;'py&gt;( &amp;self, py: Python&lt;'py&gt;, flat_data: P...
<python><rust><pyo3><maturin>
2025-02-22 14:19:09
0
1,182
Mutlu Simsek
79,459,449
4,913,660
Subplots with Plotly ternary plots
<p>I think I am totally lost when it comes to <code>Plotly Express</code>, <code>Plotly_figure_factory</code> etc.</p> <p>I cannot figure how to make subplots with Plotly ternary plots out.</p> <p>First of all, I tried using Plotly Graph Objects, for example I take the ternary plot from <a href="https://plotly.com/pyth...
<python><matplotlib><plotly>
2025-02-22 10:36:01
1
414
user37292
79,459,350
2,457,483
Cloud Run Fails to Import Custom Package from Artifact Registry (Terraform Deployment)
<p>I'm deploying a Cloud Run function using Terraform, and the function depends on a custom Python package that we uploaded to Google Artifact Registry using Twine. However, the deployment fails with the following <code>error:ModuleNotFoundError: No module named 'google.cloud.logging'</code></p> <pre><code>Traceback (m...
<python><terraform><google-cloud-functions><google-cloud-run><google-artifact-registry>
2025-02-22 09:31:28
0
5,411
Daniel
79,459,289
72,437
Comparing WhisperX and Faster-Whisper on RunPod: Speed, Accuracy, and Optimization
<p>Recently, I compared the performance of WhisperX and Faster-Whisper on RunPod's server using the following code snippet.</p> <h1>WhisperX</h1> <pre><code>model = whisperx.load_model( &quot;large-v3&quot;, &quot;cuda&quot; ) def run_whisperx_job(job): start_time = time.time() job_input = job['input'] ...
<python><speech-to-text><openai-whisper>
2025-02-22 08:47:47
0
42,256
Cheok Yan Cheng
79,459,091
5,404,620
VS Code Pylance does not show parameter-specific hints from a module
<p>Actual behaviour: the docstring is missing… <a href="https://i.sstatic.net/UHdGHvED.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UHdGHvED.png" alt="enter image description here" /></a></p> <p>Expected behaviour: the parameter-specific docstring is shown (imagine this in my code instead, not just in...
<python><visual-studio-code><pylance>
2025-02-22 04:38:35
0
2,887
Adler
79,459,070
2,602,410
Remove duplicated definitions of similar arguments in a series of Python functions
<p>I have the following code,</p> <pre class="lang-py prettyprint-override"><code>class Label(QLabel): def __init__(self, *args, width:int|None=None, height:int|None=None, minWidth:int|None=None, minHeight:int|None=None, maxWidth:int|None=None, maxHeight:int|None=...
<python>
2025-02-22 04:13:06
1
1,820
Jcyrss
79,458,938
3,462,494
Why does an integer inside a generator function swallow the object of send()?
<p>I am not trying to achieve anything -- apart from learning how generator functions and coroutines work on a brick level, which I am not really getting yet, despite lots of reading....</p> <pre><code>$cat test.py #No integer def eee(): num = yield print(f&quot;First num: {num}&quot;) num = yield pri...
<python><generator>
2025-02-22 01:21:56
1
3,615
jouell
79,458,703
10,065,473
How can I load a pretrained transformers model that was manually downloaded?
<p>I am unable to download huggingface models through the Python functions due to SSL certificate errors. Perhaps it's due to my company firewall.</p> <p>I am able to download the contents of a huggingface model repo through a browser to a folder. I'm trying to load this model from disk using <code>TFPreTrainedModel....
<python><huggingface-transformers>
2025-02-21 21:54:38
2
2,492
Arthur
79,458,586
2,130,515
pydantic-settings custom_resources does not work as expected
<pre><code>class DummyConfig(BaseSettings): PARAM1: str PARAM2: str API_KEY: str model_config = SettingsConfigDict( env_prefix=&quot;dummy_&quot;, env_file=&quot;.env&quot;, env_file_encoding=&quot;utf-8&quot; ) @classmethod def customise_sources( cls, ini...
<python><fastapi><pydantic><aws-parameter-store><pydantic-v2>
2025-02-21 20:43:34
1
1,790
LearnToGrow
79,458,570
825,227
Create a categorical column from a datetime column in Python
<p>I have a dataframe with a column of datetime type that I'd like to create a 2nd categorical column based upon. The second column should consist of string identifiers using the following logic:</p> <pre><code>ON: [16:00-09:30) FH: [09:30-10:00) M: [10:00-15:00) SLH: [15:00-15:30) LH: [15:30-16:00) </code></pre> <p>...
<python><dataframe><mapping><categorical-data>
2025-02-21 20:34:13
2
1,702
Chris
79,458,453
2,408,629
Python function deepcopy does not copy gym environment LunarLanderContinuous-v2 correctly
<p>As the code and its output shows the deepcopy of this environment does not copy aspects of the environment such as the 'action_space' and the attribute 'continuous'.</p> <p>How can this be resolved?</p> <pre><code> import gym, copy env = gym.make('LunarLanderContinuous-v2') print(env.action_space) pr...
<python><deep-copy><openai-gym>
2025-02-21 19:28:44
1
461
PerceptualRobotics
79,458,157
9,669,142
Get database table names and restore database from BAK-file
<p>I have several BAK-files locally. Each BAK-file has only one database where the name may differ, so I made a piece of code in Python that is able to obtain the name of the database from the BAK-file. I have SQL Server and SQL Server Management Studio (SMSS) installed. This code works and I test it with one public BA...
<python><python-3.x><sql-server><odbc>
2025-02-21 17:08:06
0
567
Fish1996
79,458,134
6,566,916
Attach PyCharm Community to debugpy inside container
<p>I am running a <code>debugpy</code> listener inside a Docker container. I am using docker compose to run the containers. This is my config</p> <pre class="lang-py prettyprint-override"><code>import debugpy debugpy.listen((&quot;0.0.0.0&quot;, 5680)) _logger.info(&quot;Starting debug server at port 5680&quot;) debug...
<python><docker><pycharm><debugpy>
2025-02-21 17:00:21
0
850
Niko
79,457,881
10,006,235
Create column from other columns created within same `with_columns` context
<p>Here, column &quot;AB&quot; is just being created and at the same time is being used as input to create column &quot;ABC&quot;. This fails.</p> <pre><code>df = df.with_columns( (pl.col(&quot;A&quot;)+pl.col(&quot;B&quot;)).alias(&quot;AB&quot;), (pl.col(&quot;AB&quot;)+pl.col(&quot;C&quot;)).alias(&quot;ABC&quot...
<python><python-polars>
2025-02-21 15:31:16
2
474
Nip
79,457,847
1,695,672
Understanding an instance of Python's struct.unpack
<p>I found sample code for interrogating NTP servers on <a href="https://www.mattcrampton.com/blog/query_an_ntp_server_from_python/" rel="nofollow noreferrer">https://www.mattcrampton.com/blog/query_an_ntp_server_from_python/</a>. The code is brief and well-written, but I don't understand the use of <code>struct.unpac...
<python><ntp>
2025-02-21 15:21:17
1
443
Philip Kearns
79,457,647
12,034,466
Python saving audio streamed to node input as speedup and pitchshifted .wav
<p>I am trying to create a ComfyUI node that would take image sequence and audio from respective node inputs (&quot;IMAGE&quot;, &quot;AUDIO&quot;) and saving it to an uncompressed AVI, but for some reason it is speeding-up and pitch shifting the audio.</p> <p>This is the relevant code that I use for saving temporary w...
<python><audio>
2025-02-21 14:11:25
0
513
qraqatit
79,457,564
13,421,357
Selecting and deselecting Plotly subplots?
<p>I am generating several plotly subplots in a grid. I'd like the user to be able to select one or two (or even three) subplot(s) and examine it (/them) detail. Is this possible? Currently, I am generating rows of plots that are large enough to be examined in detail, but that makes comparison across plots difficult (a...
<python><plotly>
2025-02-21 13:43:01
0
847
hainabaraka
79,457,450
3,825,495
Python - Can't Side-Load Minor Versions (Windows 10)
<p>I had 3.12.1 installed (c:/python/python_3_12_1), and ran the installer for 3.12.8, installing to its own folder (c:/python/python_3_12_8). however, when I went to use any applications created with 3.12.1, it wouldn't run them. looking in the 3_12_1 folder, it's removed nearly all of the files.</p> <p>I hadn't see...
<python><windows>
2025-02-21 13:06:45
2
616
Michael James
79,457,387
3,288,787
The type initializer for 'Microsoft.ML.Transforms.TimeSeries.FftUtils' threw an exception. in ML.Net
<pre><code> int forecastSize = 144; var dataPoints = 480; List&lt;PCIDataPoint&gt; pciData = dataPoints.Select(x =&gt; new PCIDataPoint { Value = (float)x }).ToList(); IDataView dataView = mlContext.Data.LoadFromEnumerable(pciData); // Define SSA Forecasting Model var pipeline...
<python><machine-learning><ml.net>
2025-02-21 12:39:40
0
1,256
Srinivas Ch
79,457,363
3,084,842
Python matplotlib tight_layout spacing for subplots
<p>I'm using matplotlib to plot my data in a 4x2 grid of subplots. The <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html" rel="nofollow noreferrer"><code>matplotlib.pyplot.tight_layout</code></a> automatically fits the subplots, legend, and text labels into a figure that I can save...
<python><matplotlib>
2025-02-21 12:30:14
2
3,997
Medulla Oblongata